From a5ba18ab78cf512242032fc4771d9bb6c84ed004 Mon Sep 17 00:00:00 2001 From: Maina Wycliffe Date: Sun, 9 Feb 2020 22:49:13 +0300 Subject: [PATCH] feat: add method to find user can find user by id, email or phone --- firebase/auth/findUser.go | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 firebase/auth/findUser.go diff --git a/firebase/auth/findUser.go b/firebase/auth/findUser.go new file mode 100644 index 0000000..dd56b4c --- /dev/null +++ b/firebase/auth/findUser.go @@ -0,0 +1,50 @@ +package auth + +import ( + "context" + "fmt" + + "firebase.google.com/go/auth" + "github.com/mainawycliffe/kamanda/firebase" +) + +type FindUserCriteria int + +const ( + ByUserUIDCriteria FindUserCriteria = 0 + ByUserEmailCriteria FindUserCriteria = 1 + ByUserPhoneCriteria FindUserCriteria = 2 +) + +//IsValid check if user criteria is valid i.e by uid, email or phone +func (c FindUserCriteria) IsValid() bool { + if c != ByUserUIDCriteria && c != ByUserEmailCriteria && c != ByUserPhoneCriteria { + return false + } + return true +} + +// GetUser find a user by either uid, email or phone number +func GetUser(ctx context.Context, query string, criteria FindUserCriteria, includeCustomClaims bool) (*auth.UserRecord, error) { + if isValid := criteria.IsValid(); !isValid { + return nil, fmt.Errorf("Invalid find user criteria.") + } + client, err := firebase.Auth(ctx, "") + if err != nil { + return nil, fmt.Errorf("Error authenticating firebase account: %w", err) + } + var user *auth.UserRecord + var getUserErr error + switch criteria { + case ByUserEmailCriteria: + user, getUserErr = client.GetUserByEmail(ctx, query) + case ByUserPhoneCriteria: + user, getUserErr = client.GetUserByPhoneNumber(ctx, query) + default: // by UID + user, getUserErr = client.GetUser(ctx, query) + } + if getUserErr != nil { + return nil, fmt.Errorf("Error while find user: %w", getUserErr) + } + return user, nil +}