From 1fc7b425339bd83cf440fc9811773955ccbbfbca Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Mon, 24 Aug 2026 16:48:53 +0300 Subject: [PATCH] Improve web checkout auth: phone normalization and Google web OAuth. Normalize Ethiopian phone inputs for user lookup, accept web Google client IDs for ID token login, and update the checkout integration guide for OTP and social sign-in. Co-authored-by: Cursor --- cmd/main.go | 6 +- docs/web-checkout-client-integration.md | 125 ++++++++++++++----- internal/config/config.go | 2 + internal/repository/user.go | 36 +++++- internal/repository/user_contact.go | 38 +++++- internal/services/authentication/google.go | 54 +++++++- internal/web_server/handlers/auth_handler.go | 6 +- 7 files changed, 225 insertions(+), 42 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 0a0b3c6b..b455095d 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -131,7 +131,11 @@ func main() { cfg.RefreshExpiry, ) - authSvc.InitGoogleOAuth(cfg.GoogleOAuthClientID, cfg.GoogleOAuthClientSecret, cfg.GoogleOAuthRedirectURL) + authSvc.InitGoogleOAuth( + authentication.PrimaryGoogleClientID(cfg.GoogleOAuthClientID), + cfg.GoogleOAuthClientSecret, + cfg.GoogleOAuthRedirectURL, + ) // Initialize producer // topic := "wallet-balance-topic" diff --git a/docs/web-checkout-client-integration.md b/docs/web-checkout-client-integration.md index e9061482..15b05ad8 100644 --- a/docs/web-checkout-client-integration.md +++ b/docs/web-checkout-client-integration.md @@ -177,12 +177,12 @@ flowchart TD | Variable | Example | Purpose | |----------|---------|---------| -| `VITE_API_BASE_URL` | `https://api.yimaru.com` | Yimaru API | +| `VITE_API_BASE_URL` | `https://api.yimaruacademy.com/api/v1` | Yimaru API | | `LEARNER_WEB_CHECKOUT_BASE_URL` (backend) | `https://subscribe.yimaruacademy.com` | Base URL embedded in email/SMS links | | `VITE_APP_STORE_URL` | `https://apps.apple.com/...` | Optional iOS download link on success | | `VITE_PLAY_STORE_URL` | `https://play.google.com/...` | Optional Android link | -Production API base from existing docs: `https://api.yimaru.com/api/v1` +Production API base: `https://api.yimaruacademy.com/api/v1` --- @@ -257,11 +257,11 @@ GET /api/v1/subscription-plans?active_only=true&category=LEARN_ENGLISH --- -### 2. `/subscribe/login` — Login / register +### 2. `/subscribe/login` — Sign in -**Purpose:** Authenticate before checkout. +**Purpose:** Authenticate before checkout. Registration is **not** offered on web — learners create accounts in the mobile app first. -#### Login +#### Email + password ```http POST /api/v1/auth/customer-login @@ -274,25 +274,102 @@ POST /api/v1/auth/customer-login } ``` -Or phone: +#### Google / Apple sign-in + +Same as the mobile app — exchange the provider identity token for Yimaru JWTs. + +**Google (web ID token):** + +```http +POST /api/v1/auth/google/android +``` + +```json +{ + "id_token": "" +} +``` + +**Apple (identity token):** + +```http +POST /api/v1/auth/apple +``` + +```json +{ + "id_token": "", + "email": "optional-on-first-sign-in", + "first_name": "optional", + "last_name": "optional" +} +``` + +**Web checkout env (frontend):** + +| Variable | Backend counterpart | +|----------|---------------------| +| `VITE_GOOGLE_CLIENT_ID` | `GOOGLE_OAUTH_WEB_CLIENT_ID` (or comma-separated in `GOOGLE_OAUTH_CLIENT_ID`) | +| `VITE_APPLE_CLIENT_ID` | include Services ID in `APPLE_SIGN_IN_CLIENT_IDS` | +| `VITE_APPLE_REDIRECT_URI` | must match Apple Developer redirect URL (e.g. `https://subscribe.yimaruacademy.com/subscribe/login`) | + +Buttons are hidden when the corresponding `VITE_*` values are unset. + +#### Phone + OTP (same flow as the mobile app) + +**Step 1 — send code** + +```http +POST /api/v1/user/sendResetCode +``` + +```json +{ + "phone_number": "0912345678" +} +``` + +Sends a 6-digit SMS code to an **existing** learner account. + +**Phone formats:** all of these are accepted and normalized server-side: + +| Input | Normalized | +|-------|------------| +| `0912345678` | `251912345678` | +| `+251912345678` | `251912345678` | +| `251912345678` | `251912345678` | + +**Step 2 — verify code** + +Either: + +```http +POST /api/v1/user/verify-otp +``` ```json { "phone_number": "0912345678", - "password": "your-password" + "otp": "123456" } ``` -OTP login (if your app supports it): +Or the equivalent login endpoint: + +```http +POST /api/v1/auth/customer-login +``` ```json { - "email": "learner@example.com", + "phone_number": "0912345678", "otp_code": "123456" } ``` -**Response `data`:** +**Resend:** `POST /api/v1/user/resend-otp` with `{ "phone_number" }` (requires an active OTP row; otherwise call `sendResetCode` again). + +**Response `data` (both verify paths):** ```json { @@ -303,27 +380,6 @@ OTP login (if your app supports it): } ``` -#### Register (minimal) - -1. Optional OTP: `POST /api/v1/user/sendRegisterCode` with `{ "email" }` or `{ "phone_number" }` -2. Register: - -```http -POST /api/v1/user/register -``` - -```json -{ - "email": "learner@example.com", - "phone_number": "0912345678", - "password": "your-password", - "role": "STUDENT", - "otp_medium": "EMAIL" -} -``` - -3. Redirect to login (register does not return tokens). - **After login:** redirect to `redirect` query param or `/subscribe`. --- @@ -442,9 +498,10 @@ Optional buttons: |------|--------|------|------| | List plans | `GET` | `/subscription-plans` | No | | Get plan | `GET` | `/subscription-plans/:id` | No | -| Login | `POST` | `/auth/customer-login` | No | -| Register | `POST` | `/user/register` | No | -| Send register OTP | `POST` | `/user/sendRegisterCode` | No | +| Login (email) | `POST` | `/auth/customer-login` | No | +| Send phone login OTP | `POST` | `/user/sendResetCode` | No | +| Verify phone OTP | `POST` | `/user/verify-otp` | No | +| Resend OTP | `POST` | `/user/resend-otp` | No | | Refresh token | `POST` | `/auth/refresh` | No | | Request checkout link (iOS paywall) | `POST` | `/subscriptions/request-checkout-link` | Yes | | My subscriptions | `GET` | `/subscriptions/me` | Yes | diff --git a/internal/config/config.go b/internal/config/config.go index 246161bc..b740d229 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -97,6 +97,7 @@ type MinIOConfig struct { type Config struct { GoogleOAuthClientID string + GoogleOAuthWebClientID string GoogleOAuthClientSecret string GoogleOAuthRedirectURL string // AppleSignInClientIDs is a comma-separated list of allowed "aud" values (iOS bundle ID, Services ID, etc.). @@ -182,6 +183,7 @@ func (c *Config) loadEnv() error { c.Env = env c.GoogleOAuthClientID = os.Getenv("GOOGLE_OAUTH_CLIENT_ID") + c.GoogleOAuthWebClientID = os.Getenv("GOOGLE_OAUTH_WEB_CLIENT_ID") c.GoogleOAuthClientSecret = os.Getenv("GOOGLE_OAUTH_CLIENT_SECRET") c.GoogleOAuthRedirectURL = os.Getenv("GOOGLE_OAUTH_REDIRECT_URL") c.AppleSignInClientIDs = os.Getenv("APPLE_SIGN_IN_CLIENT_IDS") diff --git a/internal/repository/user.go b/internal/repository/user.go index 57f312f6..c3704930 100644 --- a/internal/repository/user.go +++ b/internal/repository/user.go @@ -1105,7 +1105,41 @@ func (s *Store) GetUserByEmailPhone( phone string, ) (domain.User, error) { email = normalizeEmail(email) - phone = normalizePhone(phone) + + if email != "" { + return s.getUserByEmailPhoneQuery(ctx, email, "") + } + + if phone == "" { + return domain.User{}, domain.ErrUserNotFound + } + + var lastErr error + for _, candidate := range phoneLookupCandidates(phone) { + user, err := s.getUserByEmailPhoneQuery(ctx, "", candidate) + if err == nil { + return user, nil + } + if errors.Is(err, domain.ErrUserNotFound) { + lastErr = err + continue + } + return domain.User{}, err + } + + if lastErr != nil { + return domain.User{}, lastErr + } + return domain.User{}, domain.ErrUserNotFound +} + +func (s *Store) getUserByEmailPhoneQuery( + ctx context.Context, + email string, + phone string, +) (domain.User, error) { + email = normalizeEmail(email) + phone = strings.TrimSpace(phone) u, err := s.queries.GetUserByEmailPhone(ctx, dbgen.GetUserByEmailPhoneParams{ Email: pgtype.Text{ diff --git a/internal/repository/user_contact.go b/internal/repository/user_contact.go index fab8ff00..011b96c9 100644 --- a/internal/repository/user_contact.go +++ b/internal/repository/user_contact.go @@ -6,6 +6,42 @@ func normalizeEmail(email string) string { return strings.ToLower(strings.TrimSpace(email)) } +// normalizePhone converts common Ethiopian phone inputs to canonical 251XXXXXXXXX form. func normalizePhone(phone string) string { - return strings.TrimSpace(phone) + digits := strings.Map(func(r rune) rune { + if r >= '0' && r <= '9' { + return r + } + return -1 + }, strings.TrimSpace(phone)) + if digits == "" { + return strings.TrimSpace(phone) + } + + switch { + case strings.HasPrefix(digits, "251") && len(digits) >= 12: + return digits + case strings.HasPrefix(digits, "0") && len(digits) >= 10: + return "251" + digits[1:] + case (strings.HasPrefix(digits, "9") || strings.HasPrefix(digits, "7")) && len(digits) == 9: + return "251" + digits + case strings.HasPrefix(digits, "251"): + return digits + default: + return "251" + digits + } +} + +func phoneLookupCandidates(phone string) []string { + normalized := normalizePhone(phone) + candidates := []string{normalized} + + if strings.HasPrefix(normalized, "251") && len(normalized) > 3 { + local := "0" + normalized[3:] + if local != normalized { + candidates = append(candidates, local) + } + } + + return candidates } diff --git a/internal/services/authentication/google.go b/internal/services/authentication/google.go index 836d14d6..8a700251 100644 --- a/internal/services/authentication/google.go +++ b/internal/services/authentication/google.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + "strings" "time" "cloud.google.com/go/auth/credentials/idtoken" @@ -90,23 +91,68 @@ func (s *Service) FetchGoogleUser( return &user, nil } +func PrimaryGoogleClientID(clientIDs string) string { + for _, id := range strings.Split(clientIDs, ",") { + if id = strings.TrimSpace(id); id != "" { + return id + } + } + return strings.TrimSpace(clientIDs) +} + +func GoogleClientIDsForValidation(clientIDs ...string) []string { + seen := make(map[string]struct{}) + out := make([]string, 0) + for _, group := range clientIDs { + for _, id := range strings.Split(group, ",") { + id = strings.TrimSpace(id) + if id == "" { + continue + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + out = append(out, id) + } + } + return out +} + func (s *Service) LoginWithGoogleAndroid( ctx context.Context, idToken string, clientID string, ) (domain.LoginSuccess, error) { + return s.LoginWithGoogleIDToken(ctx, idToken, GoogleClientIDsForValidation(clientID)) +} + +func (s *Service) LoginWithGoogleIDToken( + ctx context.Context, + idToken string, + clientIDs []string, +) (domain.LoginSuccess, error) { if idToken == "" { return domain.LoginSuccess{}, errors.New("missing id token") } - if clientID == "" { + if len(clientIDs) == 0 { return domain.LoginSuccess{}, errors.New("missing google client id") } - payload, err := idtoken.Validate(ctx, idToken, clientID) - if err != nil { - return domain.LoginSuccess{}, fmt.Errorf("invalid google id token: %w", err) + var ( + payload *idtoken.Payload + lastErr error + ) + for _, clientID := range clientIDs { + payload, lastErr = idtoken.Validate(ctx, idToken, clientID) + if lastErr == nil { + break + } + } + if payload == nil { + return domain.LoginSuccess{}, fmt.Errorf("invalid google id token: %w", lastErr) } email, _ := payload.Claims["email"].(string) diff --git a/internal/web_server/handlers/auth_handler.go b/internal/web_server/handlers/auth_handler.go index 9ddb4d75..2b3b35de 100644 --- a/internal/web_server/handlers/auth_handler.go +++ b/internal/web_server/handlers/auth_handler.go @@ -49,7 +49,11 @@ func (h *Handler) GoogleAndroidLogin(c *fiber.Ctx) error { }) } - loginRes, err := h.authSvc.LoginWithGoogleAndroid(c.Context(), req.IDToken, h.Cfg.GoogleOAuthClientID) + loginRes, err := h.authSvc.LoginWithGoogleIDToken( + c.Context(), + req.IDToken, + authentication.GoogleClientIDsForValidation(h.Cfg.GoogleOAuthClientID, h.Cfg.GoogleOAuthWebClientID), + ) if err != nil { h.mongoLoggerSvc.Error("Google Android login failed", zap.Error(err),