From 32cbec3f5f848a2bbd0ac7a6fa506d49cd9dd575 Mon Sep 17 00:00:00 2001 From: vksssdks <2820142.cse@pietgroup.co.in> Date: Tue, 11 Jun 2024 09:32:22 +0530 Subject: [PATCH] added a method to login with email and password with was missing in the package --- auth/email_action_links.go | 64 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/auth/email_action_links.go b/auth/email_action_links.go index 442d5e6f..8ce8c835 100644 --- a/auth/email_action_links.go +++ b/auth/email_action_links.go @@ -136,3 +136,67 @@ func (c *baseClient) generateEmailActionLink( _, err := c.post(ctx, "/accounts:sendOobCode", payload, &result) return result.OOBLink, err } + + +//LoginRequest represents the the request payload +type LoginRequest struct { + Email string `json:"email"` + Password string `json:"password"` + ReturnSecureToken bool `json:"returnSecureToken"` +} + +//response +type LoginResponse struct { + IDToken string `json:"idToken"` + RefreshToken string `json:"refreshToken"` + ExpiresIn string `json:"expiresIn"` + Email string `json:"email"` +} + + +// LoginWithEmailAndPassword logs in a user using email and password with structured logging and detailed error handling. +func (c *baseClient) LoginWithEmailAndPassword(ctx context.Context, email, password string) (*LoginResponse, error) { + if email == "" || password == "" { + return nil, errors.New("email and password must not be empty") + } + + payload := LoginRequest{ + Email: email, + Password: password, + ReturnSecureToken: true, + } + + _, err := c.GetUserByEmail(ctx, email) + if err != nil { + return nil, fmt.Errorf("no account associated with this email") + } + + b, err := json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("failed to marshal payload: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, "POST", c.userManagementEndpoint+"/accounts:signInWithPassword", strings.NewReader(string(b))) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Content-Type", "application/json") + + res, err := c.httpClient.Client.Do(req) + if err != nil { + return nil, fmt.Errorf("request to authentication service failed: %w", err) + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("invalid email or password: status code %d", res.StatusCode) + } + + var result LoginResponse + if err := json.NewDecoder(res.Body).Decode(&result); err != nil { + return nil, fmt.Errorf("failed to decode response: %w", err) + } + + return &result, nil +} \ No newline at end of file