Skip to content

Commit

Permalink
added a method to login with email and password with was missing in t…
Browse files Browse the repository at this point in the history
…he package
  • Loading branch information
vksssdks committed Jun 11, 2024
1 parent c4441ec commit 32cbec3
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions auth/email_action_links.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 32cbec3

Please sign in to comment.