feat(auth): add user profile, phone login, and account deletion

This commit is contained in:
iu
2026-10-12 14:26:32 +03:00
parent 1cb9aaf198
commit 86aff695df
46 changed files with 2893 additions and 134 deletions
+87 -10
View File
@@ -18,7 +18,8 @@ type Handler struct {
func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} }
type registerRequest struct {
Email string `json:"email" binding:"required"`
Email string `json:"email"`
Phone string `json:"phone"`
Password string `json:"password" binding:"required"`
Name string `json:"name" binding:"required"`
}
@@ -26,34 +27,34 @@ type registerRequest struct {
func (h *Handler) Register(c *gin.Context) {
var req registerRequest
if err := c.ShouldBindJSON(&req); err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_request", "email, password and name are required"))
httpx.RespondError(c, httpx.BadRequest("invalid_request", "name and password are required"))
return
}
u, pair, err := h.svc.Register(c.Request.Context(), req.Email, req.Password, req.Name)
u, pair, err := h.svc.Register(c.Request.Context(), req.Email, req.Phone, req.Password, req.Name)
if err != nil {
httpx.RespondError(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{"user": u.Public(), "tokens": pair})
c.JSON(http.StatusCreated, gin.H{"user": u.Self(), "tokens": pair})
}
type loginRequest struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
Identifier string `json:"identifier" binding:"required"`
Password string `json:"password" binding:"required"`
}
func (h *Handler) Login(c *gin.Context) {
var req loginRequest
if err := c.ShouldBindJSON(&req); err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_request", "email and password are required"))
httpx.RespondError(c, httpx.BadRequest("invalid_request", "identifier and password are required"))
return
}
u, pair, err := h.svc.Login(c.Request.Context(), req.Email, req.Password)
u, pair, err := h.svc.Login(c.Request.Context(), req.Identifier, req.Password)
if err != nil {
httpx.RespondError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"user": u.Public(), "tokens": pair})
c.JSON(http.StatusOK, gin.H{"user": u.Self(), "tokens": pair})
}
type refreshRequest struct {
@@ -96,7 +97,83 @@ func (h *Handler) Me(c *gin.Context) {
if prefs == nil {
prefs = map[string]any{}
}
c.JSON(http.StatusOK, gin.H{"user": u.Public(), "preferences": prefs})
c.JSON(http.StatusOK, gin.H{"user": u.Self(), "preferences": prefs})
}
type updateMeRequest struct {
Name string `json:"name"`
}
// UpdateMe changes the display name of the authenticated user.
func (h *Handler) UpdateMe(c *gin.Context) {
var req updateMeRequest
if err := c.ShouldBindJSON(&req); err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_request", "name is required"))
return
}
u, err := h.svc.UpdateName(c.Request.Context(), UserID(c), req.Name)
if err != nil {
httpx.RespondError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"user": u.Self()})
}
type changePasswordRequest struct {
CurrentPassword string `json:"current_password" binding:"required"`
NewPassword string `json:"new_password" binding:"required"`
}
// ChangePassword verifies the current password and revokes all refresh tokens.
func (h *Handler) ChangePassword(c *gin.Context) {
var req changePasswordRequest
if err := c.ShouldBindJSON(&req); err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_request", "current_password and new_password are required"))
return
}
if err := h.svc.ChangePassword(c.Request.Context(), UserID(c), req.CurrentPassword, req.NewPassword); err != nil {
httpx.RespondError(c, err)
return
}
c.Status(http.StatusNoContent)
}
type addIdentifierRequest struct {
Email string `json:"email"`
Phone string `json:"phone"`
}
// AddIdentifier adds the one missing login identifier.
func (h *Handler) AddIdentifier(c *gin.Context) {
var req addIdentifierRequest
if err := c.ShouldBindJSON(&req); err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_request", "email or phone is required"))
return
}
u, err := h.svc.AddIdentifier(c.Request.Context(), UserID(c), req.Email, req.Phone)
if err != nil {
httpx.RespondError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"user": u.Self()})
}
type deleteMeRequest struct {
Password string `json:"password" binding:"required"`
}
// DeleteMe deletes the authenticated account and all cascading content.
func (h *Handler) DeleteMe(c *gin.Context) {
var req deleteMeRequest
if err := c.ShouldBindJSON(&req); err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_request", "password is required"))
return
}
if err := h.svc.DeleteAccount(c.Request.Context(), UserID(c), req.Password); err != nil {
httpx.RespondError(c, err)
return
}
c.Status(http.StatusNoContent)
}
const (
+215
View File
@@ -0,0 +1,215 @@
package auth
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"galo/internal/models"
)
type authResponse struct {
User models.SelfUser `json:"user"`
Tokens *TokenPair `json:"tokens"`
}
func newTestRouter(t *testing.T) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
r := gin.New()
h := NewHandler(newTestService(t))
r.POST("/auth/register", h.Register)
r.POST("/auth/login", h.Login)
authed := r.Group("")
authed.Use(h.svc.Middleware())
authed.GET("/auth/me", h.Me)
authed.PATCH("/auth/me", h.UpdateMe)
authed.POST("/auth/me/password", h.ChangePassword)
authed.POST("/auth/me/identifiers", h.AddIdentifier)
authed.DELETE("/auth/me", h.DeleteMe)
return r
}
func doJSON(r *gin.Engine, method, path, token string, body any) *httptest.ResponseRecorder {
var buf bytes.Buffer
if body != nil {
_ = json.NewEncoder(&buf).Encode(body)
} else {
buf.WriteString("{}")
}
req := httptest.NewRequest(method, path, &buf)
req.Header.Set("Content-Type", "application/json")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec
}
func decodeAuth(t *testing.T, rec *httptest.ResponseRecorder) authResponse {
t.Helper()
var out authResponse
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("decode %s: %v", rec.Body.String(), err)
}
return out
}
func TestRegisterHandlerPhoneOnly(t *testing.T) {
r := newTestRouter(t)
rec := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"phone": "+15550000021", "password": "password123", "name": "Phone",
})
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String())
}
out := decodeAuth(t, rec)
if out.User.Phone != "+15550000021" || out.User.Email != "" {
t.Fatalf("user = %+v", out.User)
}
if out.Tokens == nil || out.Tokens.AccessToken == "" {
t.Fatalf("no tokens")
}
}
func TestRegisterHandlerRequiresIdentifier(t *testing.T) {
r := newTestRouter(t)
rec := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"password": "password123", "name": "NoId",
})
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body.String())
}
}
func TestLoginHandlerByIdentifier(t *testing.T) {
r := newTestRouter(t)
reg := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "handler@test.local", "password": "password123", "name": "H",
})
if reg.Code != http.StatusCreated {
t.Fatalf("register status = %d", reg.Code)
}
rec := doJSON(r, http.MethodPost, "/auth/login", "", map[string]string{
"identifier": "Handler@Test.Local", "password": "password123",
})
if rec.Code != http.StatusOK {
t.Fatalf("login status = %d body = %s", rec.Code, rec.Body.String())
}
if out := decodeAuth(t, rec); out.Tokens == nil {
t.Fatalf("no tokens")
}
}
func TestMeHandlerExposesPhoneToOwner(t *testing.T) {
r := newTestRouter(t)
reg := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "me@test.local", "phone": "+15550000022", "password": "password123", "name": "Me",
})
out := decodeAuth(t, reg)
rec := doJSON(r, http.MethodGet, "/auth/me", out.Tokens.AccessToken, nil)
if rec.Code != http.StatusOK {
t.Fatalf("me status = %d body = %s", rec.Code, rec.Body.String())
}
var body struct {
User models.SelfUser `json:"user"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode: %v", err)
}
if body.User.Phone != "+15550000022" {
t.Fatalf("phone not exposed to owner: %s", rec.Body.String())
}
}
func TestUpdateMeHandler(t *testing.T) {
r := newTestRouter(t)
reg := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "upd@test.local", "password": "password123", "name": "Old",
})
token := decodeAuth(t, reg).Tokens.AccessToken
if rec := doJSON(r, http.MethodPatch, "/auth/me", token, map[string]string{"name": " "}); rec.Code != http.StatusBadRequest {
t.Fatalf("empty name status = %d body = %s", rec.Code, rec.Body.String())
}
rec := doJSON(r, http.MethodPatch, "/auth/me", token, map[string]string{"name": "New"})
if rec.Code != http.StatusOK {
t.Fatalf("update status = %d body = %s", rec.Code, rec.Body.String())
}
var body struct {
User models.SelfUser `json:"user"`
}
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body.User.Name != "New" {
t.Fatalf("name not updated: %s", rec.Body.String())
}
}
func TestChangePasswordHandler(t *testing.T) {
r := newTestRouter(t)
reg := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "cp@test.local", "password": "password123", "name": "CP",
})
out := decodeAuth(t, reg)
if rec := doJSON(r, http.MethodPost, "/auth/me/password", out.Tokens.AccessToken, map[string]string{
"current_password": "wrong", "new_password": "newpassword",
}); rec.Code != http.StatusUnauthorized {
t.Fatalf("wrong current status = %d", rec.Code)
}
if rec := doJSON(r, http.MethodPost, "/auth/me/password", out.Tokens.AccessToken, map[string]string{
"current_password": "password123", "new_password": "newpassword",
}); rec.Code != http.StatusNoContent {
t.Fatalf("change status = %d body = %s", rec.Code, rec.Body.String())
}
}
func TestAddIdentifierHandler(t *testing.T) {
r := newTestRouter(t)
reg := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "addh@test.local", "password": "password123", "name": "Add",
})
token := decodeAuth(t, reg).Tokens.AccessToken
if rec := doJSON(r, http.MethodPost, "/auth/me/identifiers", token, map[string]string{"email": "x@test.local"}); rec.Code != http.StatusBadRequest {
t.Fatalf("re-set email status = %d", rec.Code)
}
rec := doJSON(r, http.MethodPost, "/auth/me/identifiers", token, map[string]string{"phone": "+15550000023"})
if rec.Code != http.StatusOK {
t.Fatalf("add status = %d body = %s", rec.Code, rec.Body.String())
}
var body struct {
User models.SelfUser `json:"user"`
}
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body.User.Phone != "+15550000023" {
t.Fatalf("phone not added: %s", rec.Body.String())
}
}
func TestDeleteMeHandler(t *testing.T) {
r := newTestRouter(t)
reg := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "delh@test.local", "password": "password123", "name": "Del",
})
token := decodeAuth(t, reg).Tokens.AccessToken
if rec := doJSON(r, http.MethodDelete, "/auth/me", token, map[string]string{"password": "wrong"}); rec.Code != http.StatusUnauthorized {
t.Fatalf("wrong password status = %d", rec.Code)
}
if rec := doJSON(r, http.MethodDelete, "/auth/me", token, map[string]string{"password": "password123"}); rec.Code != http.StatusNoContent {
t.Fatalf("delete status = %d body = %s", rec.Code, rec.Body.String())
}
if rec := doJSON(r, http.MethodGet, "/auth/me", token, nil); rec.Code != http.StatusUnauthorized {
t.Fatalf("me after delete status = %d", rec.Code)
}
}
+63
View File
@@ -0,0 +1,63 @@
package auth
import (
"strings"
"galo/internal/httpx"
)
// Identifier kinds for login and registration.
const (
IdentifierEmail = "email"
IdentifierPhone = "phone"
)
// NormalizePhone validates and canonicalises a phone number to E.164: a leading
// plus followed by 8–15 digits. It is the single normalisation point used by
// registration, identifier addition and login, so lookups compare canonical
// values only.
func NormalizePhone(raw string) (string, error) {
s := strings.TrimSpace(raw)
if s == "" {
return "", httpx.BadRequest("invalid_phone", "phone is required")
}
if !strings.HasPrefix(s, "+") {
return "", httpx.BadRequest("invalid_phone", "phone must be in E.164 format with a leading +")
}
digits := s[1:]
if len(digits) < 8 || len(digits) > 15 {
return "", httpx.BadRequest("invalid_phone", "phone must contain between 8 and 15 digits")
}
for _, r := range digits {
if r < '0' || r > '9' {
return "", httpx.BadRequest("invalid_phone", "phone may contain digits only after the leading +")
}
}
return s, nil
}
func validEmail(s string) bool {
i := strings.Index(s, "@")
return i > 0 && i < len(s)-1 && !strings.ContainsAny(s, " \t\r\n")
}
// NormalizeIdentifier classifies a login identifier as email (contains `@`) or
// phone, returning the canonical value for lookups.
func NormalizeIdentifier(raw string) (kind, value string, err error) {
s := strings.TrimSpace(raw)
if s == "" {
return "", "", httpx.BadRequest("invalid_identifier", "identifier is required")
}
if strings.Contains(s, "@") {
v := strings.ToLower(s)
if !validEmail(v) {
return "", "", httpx.BadRequest("invalid_identifier", "valid email is required")
}
return IdentifierEmail, v, nil
}
v, err := NormalizePhone(s)
if err != nil {
return "", "", err
}
return IdentifierPhone, v, nil
}
+63
View File
@@ -0,0 +1,63 @@
package auth
import "testing"
func TestNormalizePhone(t *testing.T) {
valid := []string{
"+15551234567",
"+442071234567",
"+12345678",
"+123456789012345",
}
for _, in := range valid {
got, err := NormalizePhone(in)
if err != nil {
t.Errorf("NormalizePhone(%q) error: %v", in, err)
}
if got != in {
t.Errorf("NormalizePhone(%q) = %q, want unchanged", in, got)
}
}
invalid := []string{
"",
"15551234567",
"+",
"+1234567",
"+1234567890123456",
"+1555abc4567",
"+1-555-123-4567",
"+1555 1234567",
}
for _, in := range invalid {
if _, err := NormalizePhone(in); err == nil {
t.Errorf("NormalizePhone(%q) accepted an invalid number", in)
}
}
if got, err := NormalizePhone(" +15551234567 "); err != nil || got != "+15551234567" {
t.Errorf("NormalizePhone trimmed = %q err=%v", got, err)
}
}
func TestNormalizeIdentifier(t *testing.T) {
kind, value, err := NormalizeIdentifier(" User@Test.Local ")
if err != nil || kind != IdentifierEmail || value != "user@test.local" {
t.Fatalf("email identifier = %q/%q err=%v", kind, value, err)
}
kind, value, err = NormalizeIdentifier("+15551234567")
if err != nil || kind != IdentifierPhone || value != "+15551234567" {
t.Fatalf("phone identifier = %q/%q err=%v", kind, value, err)
}
if _, _, err := NormalizeIdentifier(""); err == nil {
t.Errorf("empty identifier accepted")
}
if _, _, err := NormalizeIdentifier("no-at-sign"); err == nil {
t.Errorf("non-phone identifier accepted")
}
if _, _, err := NormalizeIdentifier("@bad"); err == nil {
t.Errorf("malformed email accepted")
}
}
+7
View File
@@ -10,7 +10,14 @@ import (
type Repository interface {
CreateUser(ctx context.Context, u *models.User) error
GetUserByEmail(ctx context.Context, email string) (*models.User, error)
GetUserByPhone(ctx context.Context, phone string) (*models.User, error)
GetUserByID(ctx context.Context, id string) (*models.User, error)
UpdateName(ctx context.Context, userID, name string) error
UpdatePasswordHash(ctx context.Context, userID, hash string) error
// AddIdentifier sets the missing email and/or phone of a user. The caller
// has already validated that only a missing identifier is provided.
AddIdentifier(ctx context.Context, userID, email, phone string) error
DeleteUser(ctx context.Context, userID string) error
UpdatePreferences(ctx context.Context, userID string, raw []byte) error
CreateRefreshToken(ctx context.Context, t *models.RefreshToken) error
GetRefreshToken(ctx context.Context, hash string) (*models.RefreshToken, error)
+185 -17
View File
@@ -26,23 +26,38 @@ func NewService(store Repository, tm *TokenManager) *Service {
return &Service{store: store, tm: tm}
}
func (s *Service) Register(ctx context.Context, email, password, name string) (*models.User, *TokenPair, error) {
email = strings.TrimSpace(strings.ToLower(email))
// Register creates an account with at least one of email/phone. A missing
// identifier is stored as NULL so phone-only accounts are possible.
func (s *Service) Register(ctx context.Context, email, phone, password, name string) (*models.User, *TokenPair, error) {
name = strings.TrimSpace(name)
if email == "" || !strings.Contains(email, "@") {
return nil, nil, httpx.BadRequest("invalid_email", "valid email is required")
if name == "" {
return nil, nil, httpx.BadRequest("invalid_name", "name is required")
}
if len(password) < 8 {
return nil, nil, httpx.BadRequest("weak_password", "password must be at least 8 characters")
}
if name == "" {
return nil, nil, httpx.BadRequest("invalid_name", "name is required")
normEmail, normPhone, err := s.normalizeIdentifiers(email, phone)
if err != nil {
return nil, nil, err
}
if normEmail == "" && normPhone == "" {
return nil, nil, httpx.BadRequest("identifier_required", "email or phone is required")
}
if _, err := s.store.GetUserByEmail(ctx, email); err == nil {
return nil, nil, httpx.Conflict("email_taken", "email is already registered")
} else if !errors.Is(err, ErrNotFound) {
return nil, nil, err
if normEmail != "" {
if _, err := s.store.GetUserByEmail(ctx, normEmail); err == nil {
return nil, nil, httpx.Conflict("email_taken", "email is already registered")
} else if !errors.Is(err, ErrNotFound) {
return nil, nil, err
}
}
if normPhone != "" {
if _, err := s.store.GetUserByPhone(ctx, normPhone); err == nil {
return nil, nil, httpx.Conflict("phone_taken", "phone is already registered")
} else if !errors.Is(err, ErrNotFound) {
return nil, nil, err
}
}
hash, err := HashPassword(password)
@@ -51,13 +66,14 @@ func (s *Service) Register(ctx context.Context, email, password, name string) (*
}
u := &models.User{
ID: NewID(),
Email: email,
Email: normEmail,
Phone: normPhone,
PasswordHash: hash,
Name: name,
CreatedAt: time.Now(),
}
if err := s.store.CreateUser(ctx, u); err != nil {
return nil, nil, err
return nil, nil, mapIdentifierConflict(err)
}
pair, err := s.issuePair(ctx, u)
@@ -67,17 +83,27 @@ func (s *Service) Register(ctx context.Context, email, password, name string) (*
return u, pair, nil
}
func (s *Service) Login(ctx context.Context, email, password string) (*models.User, *TokenPair, error) {
email = strings.TrimSpace(strings.ToLower(email))
u, err := s.store.GetUserByEmail(ctx, email)
// Login authenticates by a single identifier — email or E.164 phone — and never
// reveals which part of the credentials was wrong.
func (s *Service) Login(ctx context.Context, identifier, password string) (*models.User, *TokenPair, error) {
kind, value, err := NormalizeIdentifier(identifier)
if err != nil {
return nil, nil, invalidCredentials()
}
var u *models.User
if kind == IdentifierEmail {
u, err = s.store.GetUserByEmail(ctx, value)
} else {
u, err = s.store.GetUserByPhone(ctx, value)
}
if err != nil {
if errors.Is(err, ErrNotFound) {
return nil, nil, httpx.Unauthorized("invalid_credentials", "invalid email or password")
return nil, nil, invalidCredentials()
}
return nil, nil, err
}
if !CheckPassword(u.PasswordHash, password) {
return nil, nil, httpx.Unauthorized("invalid_credentials", "invalid email or password")
return nil, nil, invalidCredentials()
}
pair, err := s.issuePair(ctx, u)
if err != nil {
@@ -120,6 +146,148 @@ func (s *Service) Logout(ctx context.Context, refreshToken string) error {
return s.store.RevokeRefreshToken(ctx, t.ID)
}
// UpdateName changes the display name, rejecting an empty one.
func (s *Service) UpdateName(ctx context.Context, userID, name string) (*models.User, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, httpx.BadRequest("invalid_name", "name is required")
}
if err := s.store.UpdateName(ctx, userID, name); err != nil {
return nil, userErr(err)
}
return s.store.GetUserByID(ctx, userID)
}
// ChangePassword verifies the current password and revokes every refresh token
// so all sessions must log in again.
func (s *Service) ChangePassword(ctx context.Context, userID, current, newPassword string) error {
if len(newPassword) < 8 {
return httpx.BadRequest("weak_password", "password must be at least 8 characters")
}
u, err := s.store.GetUserByID(ctx, userID)
if err != nil {
return userErr(err)
}
if !CheckPassword(u.PasswordHash, current) {
return httpx.Unauthorized("current_password_incorrect", "current password is incorrect")
}
hash, err := HashPassword(newPassword)
if err != nil {
return err
}
if err := s.store.UpdatePasswordHash(ctx, userID, hash); err != nil {
return userErr(err)
}
return s.store.RevokeAllUserTokens(ctx, userID)
}
// AddIdentifier adds the one missing login identifier. Rejecting an attempt to
// re-set an existing one or to provide both at once keeps identifiers immutable.
func (s *Service) AddIdentifier(ctx context.Context, userID, email, phone string) (*models.User, error) {
u, err := s.store.GetUserByID(ctx, userID)
if err != nil {
return nil, userErr(err)
}
normEmail, normPhone, err := s.normalizeIdentifiers(email, phone)
if err != nil {
return nil, err
}
if normEmail == "" && normPhone == "" {
return nil, httpx.BadRequest("identifier_required", "email or phone is required")
}
if normEmail != "" && normPhone != "" {
return nil, httpx.BadRequest("invalid_request", "provide only one identifier at a time")
}
if u.Email != "" && u.Phone != "" {
return nil, httpx.BadRequest("identifiers_complete", "both identifiers are already set")
}
if normEmail != "" {
if u.Email != "" {
return nil, httpx.BadRequest("email_already_set", "email can no longer be changed")
}
if _, err := s.store.GetUserByEmail(ctx, normEmail); err == nil {
return nil, httpx.Conflict("email_taken", "email is already registered")
} else if !errors.Is(err, ErrNotFound) {
return nil, err
}
}
if normPhone != "" {
if u.Phone != "" {
return nil, httpx.BadRequest("phone_already_set", "phone can no longer be changed")
}
if _, err := s.store.GetUserByPhone(ctx, normPhone); err == nil {
return nil, httpx.Conflict("phone_taken", "phone is already registered")
} else if !errors.Is(err, ErrNotFound) {
return nil, err
}
}
if err := s.store.AddIdentifier(ctx, userID, normEmail, normPhone); err != nil {
return nil, mapIdentifierConflict(err)
}
return s.store.GetUserByID(ctx, userID)
}
// DeleteAccount removes the account and everything that cascades from it after
// confirming the password. It is immediate and irreversible.
func (s *Service) DeleteAccount(ctx context.Context, userID, password string) error {
u, err := s.store.GetUserByID(ctx, userID)
if err != nil {
return userErr(err)
}
if !CheckPassword(u.PasswordHash, password) {
return httpx.Unauthorized("current_password_incorrect", "password is incorrect")
}
if err := s.store.DeleteUser(ctx, userID); err != nil {
return userErr(err)
}
return nil
}
// normalizeIdentifiers trims and canonicalises the provided email/phone. Empty
// fields stay empty; supplied ones must be valid.
func (s *Service) normalizeIdentifiers(email, phone string) (string, string, error) {
var normEmail, normPhone string
if e := strings.TrimSpace(email); e != "" {
e = strings.ToLower(e)
if !validEmail(e) {
return "", "", httpx.BadRequest("invalid_email", "valid email is required")
}
normEmail = e
}
if p := strings.TrimSpace(phone); p != "" {
np, err := NormalizePhone(p)
if err != nil {
return "", "", err
}
normPhone = np
}
return normEmail, normPhone, nil
}
func invalidCredentials() error {
return httpx.Unauthorized("invalid_credentials", "invalid identifier or password")
}
// userErr converts a missing user into an unauthorized/not-found style error
// appropriate for authenticated profile operations.
func userErr(err error) error {
if errors.Is(err, ErrNotFound) {
return httpx.Unauthorized("unauthorized", "user not found")
}
return err
}
func mapIdentifierConflict(err error) error {
switch {
case errors.Is(err, ErrEmailTaken):
return httpx.Conflict("email_taken", "email is already registered")
case errors.Is(err, ErrPhoneTaken):
return httpx.Conflict("phone_taken", "phone is already registered")
default:
return err
}
}
func (s *Service) issuePair(ctx context.Context, u *models.User) (*TokenPair, error) {
access, err := s.tm.GenerateAccess(u.ID, u.Email)
if err != nil {
+239
View File
@@ -0,0 +1,239 @@
package auth
import (
"context"
"errors"
"io/fs"
"path/filepath"
"testing"
"time"
assets "galo"
"galo/internal/db"
"galo/internal/httpx"
)
func newTestService(t *testing.T) *Service {
t.Helper()
migFS, err := fs.Sub(assets.Migrations, "migrations/sqlite")
if err != nil {
t.Fatalf("migrations fs: %v", err)
}
path := filepath.Join(t.TempDir(), "auth.db")
if err := db.MigrateSQLite(path, migFS); err != nil {
t.Fatalf("migrate: %v", err)
}
database, err := db.OpenSQLite(path)
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() { database.Close() })
return NewService(NewSQLiteStore(database), NewTokenManager("secret", 15*time.Minute, time.Hour))
}
func errCode(t *testing.T, err error) string {
t.Helper()
var appErr *httpx.AppError
if !errors.As(err, &appErr) {
t.Fatalf("expected AppError, got %v", err)
}
return appErr.Code
}
func TestRegisterByEmailOrPhone(t *testing.T) {
ctx := context.Background()
svc := newTestService(t)
u, pair, err := svc.Register(ctx, "User@Test.Local", "", "password123", "Tester")
if err != nil {
t.Fatalf("register email: %v", err)
}
if u.Email != "user@test.local" || u.Phone != "" {
t.Fatalf("email registration stored %+v", u)
}
if pair == nil || pair.AccessToken == "" || pair.RefreshToken == "" {
t.Fatalf("no tokens issued")
}
p, _, err := svc.Register(ctx, "", "+15550000001", "password123", "Phone")
if err != nil {
t.Fatalf("register phone: %v", err)
}
if p.Email != "" || p.Phone != "+15550000001" {
t.Fatalf("phone registration stored %+v", p)
}
both, _, err := svc.Register(ctx, "both@test.local", "+15550000002", "password123", "Both")
if err != nil {
t.Fatalf("register both: %v", err)
}
if both.Email != "both@test.local" || both.Phone != "+15550000002" {
t.Fatalf("both registration stored %+v", both)
}
}
func TestRegisterValidation(t *testing.T) {
ctx := context.Background()
svc := newTestService(t)
if _, _, err := svc.Register(ctx, "", "", "password123", "N"); errCode(t, err) != "identifier_required" {
t.Fatalf("no identifier code = %v", err)
}
if _, _, err := svc.Register(ctx, "a@test.local", "", "short", "N"); errCode(t, err) != "weak_password" {
t.Fatalf("weak password code = %v", err)
}
if _, _, err := svc.Register(ctx, "a@test.local", "", "password123", ""); errCode(t, err) != "invalid_name" {
t.Fatalf("empty name code = %v", err)
}
if _, _, err := svc.Register(ctx, "not-an-email", "", "password123", "N"); errCode(t, err) != "invalid_email" {
t.Fatalf("invalid email code = %v", err)
}
if _, _, err := svc.Register(ctx, "", "5550000", "password123", "N"); errCode(t, err) != "invalid_phone" {
t.Fatalf("invalid phone code = %v", err)
}
}
func TestRegisterConflicts(t *testing.T) {
ctx := context.Background()
svc := newTestService(t)
if _, _, err := svc.Register(ctx, "dup@test.local", "", "password123", "A"); err != nil {
t.Fatalf("first register: %v", err)
}
if _, _, err := svc.Register(ctx, "Dup@Test.Local", "", "password123", "B"); errCode(t, err) != "email_taken" {
t.Fatalf("duplicate email code = %v", err)
}
if _, _, err := svc.Register(ctx, "", "+15550000009", "password123", "C"); err != nil {
t.Fatalf("phone register: %v", err)
}
if _, _, err := svc.Register(ctx, "", "+15550000009", "password123", "D"); errCode(t, err) != "phone_taken" {
t.Fatalf("duplicate phone code = %v", err)
}
}
func TestLoginByIdentifier(t *testing.T) {
ctx := context.Background()
svc := newTestService(t)
if _, _, err := svc.Register(ctx, "login@test.local", "+15550000010", "password123", "Login"); err != nil {
t.Fatalf("register: %v", err)
}
if _, pair, err := svc.Login(ctx, "Login@Test.Local", "password123"); err != nil || pair == nil {
t.Fatalf("login by email: %v", err)
}
if _, pair, err := svc.Login(ctx, "+15550000010", "password123"); err != nil || pair == nil {
t.Fatalf("login by phone: %v", err)
}
_, _, errMissing := svc.Login(ctx, "nobody@test.local", "password123")
_, _, errWrong := svc.Login(ctx, "login@test.local", "wrong-password")
if errCode(t, errMissing) != "invalid_credentials" {
t.Fatalf("missing user code = %v", errMissing)
}
if errCode(t, errWrong) != "invalid_credentials" {
t.Fatalf("wrong password code = %v", errWrong)
}
if errMissing.Error() != errWrong.Error() {
t.Fatalf("errors distinguishable: %q vs %q", errMissing, errWrong)
}
}
func TestUpdateName(t *testing.T) {
ctx := context.Background()
svc := newTestService(t)
u, _, err := svc.Register(ctx, "name@test.local", "", "password123", "Old")
if err != nil {
t.Fatalf("register: %v", err)
}
if _, err := svc.UpdateName(ctx, u.ID, " "); errCode(t, err) != "invalid_name" {
t.Fatalf("empty name code = %v", err)
}
got, err := svc.UpdateName(ctx, u.ID, " New Name ")
if err != nil || got.Name != "New Name" {
t.Fatalf("update name = %+v err=%v", got, err)
}
}
func TestChangePasswordRevokesTokens(t *testing.T) {
ctx := context.Background()
svc := newTestService(t)
u, pair, err := svc.Register(ctx, "pass@test.local", "", "password123", "Pass")
if err != nil {
t.Fatalf("register: %v", err)
}
if err := svc.ChangePassword(ctx, u.ID, "wrong", "newpassword"); errCode(t, err) != "current_password_incorrect" {
t.Fatalf("wrong current password code = %v", err)
}
if err := svc.ChangePassword(ctx, u.ID, "password123", "short"); errCode(t, err) != "weak_password" {
t.Fatalf("weak new password code = %v", err)
}
if err := svc.ChangePassword(ctx, u.ID, "password123", "newpassword"); err != nil {
t.Fatalf("change password: %v", err)
}
if _, _, err := svc.Login(ctx, "pass@test.local", "newpassword"); err != nil {
t.Fatalf("login with new password: %v", err)
}
if _, _, err := svc.Login(ctx, "pass@test.local", "password123"); errCode(t, err) != "invalid_credentials" {
t.Fatalf("old password still works: %v", err)
}
if _, err := svc.Refresh(ctx, pair.RefreshToken); errCode(t, err) != "invalid_refresh_token" {
t.Fatalf("refresh token not revoked: %v", err)
}
}
func TestAddIdentifier(t *testing.T) {
ctx := context.Background()
svc := newTestService(t)
u, _, err := svc.Register(ctx, "add@test.local", "", "password123", "Add")
if err != nil {
t.Fatalf("register: %v", err)
}
if _, err := svc.AddIdentifier(ctx, u.ID, "other@test.local", ""); errCode(t, err) != "email_already_set" {
t.Fatalf("re-set email code = %v", err)
}
if _, err := svc.AddIdentifier(ctx, u.ID, "", ""); errCode(t, err) != "identifier_required" {
t.Fatalf("no identifier code = %v", err)
}
if _, err := svc.AddIdentifier(ctx, u.ID, "x@test.local", "+15550000011"); errCode(t, err) != "invalid_request" {
t.Fatalf("both at once code = %v", err)
}
got, err := svc.AddIdentifier(ctx, u.ID, "", "+15550000011")
if err != nil || got.Phone != "+15550000011" {
t.Fatalf("add phone = %+v err=%v", got, err)
}
if _, err := svc.AddIdentifier(ctx, u.ID, "later@test.local", ""); errCode(t, err) != "identifiers_complete" {
t.Fatalf("both set code = %v", err)
}
other, _, _ := svc.Register(ctx, "owner@test.local", "", "password123", "Owner")
if _, err := svc.AddIdentifier(ctx, other.ID, "", "+15550000011"); errCode(t, err) != "phone_taken" {
t.Fatalf("phone conflict code = %v", err)
}
}
func TestDeleteAccount(t *testing.T) {
ctx := context.Background()
svc := newTestService(t)
u, _, err := svc.Register(ctx, "delete@test.local", "", "password123", "Delete")
if err != nil {
t.Fatalf("register: %v", err)
}
if err := svc.DeleteAccount(ctx, u.ID, "wrong"); errCode(t, err) != "current_password_incorrect" {
t.Fatalf("wrong password code = %v", err)
}
if err := svc.DeleteAccount(ctx, u.ID, "password123"); err != nil {
t.Fatalf("delete account: %v", err)
}
if _, _, err := svc.Login(ctx, "delete@test.local", "password123"); errCode(t, err) != "invalid_credentials" {
t.Fatalf("deleted account can still log in: %v", err)
}
if _, err := svc.store.GetUserByID(ctx, u.ID); !errors.Is(err, ErrNotFound) {
t.Fatalf("user row survived deletion: %v", err)
}
}
+61 -13
View File
@@ -5,6 +5,7 @@ import (
"database/sql"
"encoding/json"
"errors"
"strings"
"time"
"galo/internal/models"
@@ -18,32 +19,36 @@ type SQLiteStore struct {
func NewSQLiteStore(db *sql.DB) *SQLiteStore { return &SQLiteStore{db: db} }
const sqliteUserColumns = `id, COALESCE(email, ''), COALESCE(phone, ''), password_hash, name,
COALESCE(avatar_url, ''), COALESCE(preferences, '{}'), created_at`
func (s *SQLiteStore) CreateUser(ctx context.Context, u *models.User) error {
_, err := s.db.ExecContext(ctx,
`INSERT INTO users (id, email, password_hash, name, avatar_url)
VALUES ($1, $2, $3, $4, $5)`,
u.ID, u.Email, u.PasswordHash, u.Name, nullIfEmpty(u.AvatarURL))
return err
`INSERT INTO users (id, email, phone, password_hash, name, avatar_url)
VALUES ($1, $2, $3, $4, $5, $6)`,
u.ID, nullIfEmpty(u.Email), nullIfEmpty(u.Phone), u.PasswordHash, u.Name, nullIfEmpty(u.AvatarURL))
return mapUniqueViolationSQLite(err)
}
func (s *SQLiteStore) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
return s.scanUser(s.db.QueryRowContext(ctx,
`SELECT id, email, password_hash, name, COALESCE(avatar_url, ''),
COALESCE(preferences, '{}'), created_at
FROM users WHERE lower(email) = lower($1)`, email))
`SELECT `+sqliteUserColumns+` FROM users WHERE lower(email) = lower($1)`, email))
}
func (s *SQLiteStore) GetUserByPhone(ctx context.Context, phone string) (*models.User, error) {
return s.scanUser(s.db.QueryRowContext(ctx,
`SELECT `+sqliteUserColumns+` FROM users WHERE phone = $1`, phone))
}
func (s *SQLiteStore) GetUserByID(ctx context.Context, id string) (*models.User, error) {
return s.scanUser(s.db.QueryRowContext(ctx,
`SELECT id, email, password_hash, name, COALESCE(avatar_url, ''),
COALESCE(preferences, '{}'), created_at
FROM users WHERE id = $1`, id))
`SELECT `+sqliteUserColumns+` FROM users WHERE id = $1`, id))
}
func (s *SQLiteStore) scanUser(row *sql.Row) (*models.User, error) {
var u models.User
var prefs, createdAt string
if err := row.Scan(&u.ID, &u.Email, &u.PasswordHash, &u.Name, &u.AvatarURL, &prefs, &createdAt); err != nil {
if err := row.Scan(&u.ID, &u.Email, &u.Phone, &u.PasswordHash, &u.Name, &u.AvatarURL, &prefs, &createdAt); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
@@ -56,9 +61,34 @@ func (s *SQLiteStore) scanUser(row *sql.Row) (*models.User, error) {
return &u, nil
}
func (s *SQLiteStore) UpdateName(ctx context.Context, userID, name string) error {
return s.requireRow(s.db.ExecContext(ctx, `UPDATE users SET name = $2 WHERE id = $1`, userID, name))
}
func (s *SQLiteStore) UpdatePasswordHash(ctx context.Context, userID, hash string) error {
return s.requireRow(s.db.ExecContext(ctx, `UPDATE users SET password_hash = $2 WHERE id = $1`, userID, hash))
}
func (s *SQLiteStore) AddIdentifier(ctx context.Context, userID, email, phone string) error {
err := s.requireRow(s.db.ExecContext(ctx,
`UPDATE users
SET email = COALESCE(NULLIF($2, ''), email),
phone = COALESCE(NULLIF($3, ''), phone)
WHERE id = $1`,
userID, email, phone))
return mapUniqueViolationSQLite(err)
}
func (s *SQLiteStore) DeleteUser(ctx context.Context, userID string) error {
return s.requireRow(s.db.ExecContext(ctx, `DELETE FROM users WHERE id = $1`, userID))
}
func (s *SQLiteStore) UpdatePreferences(ctx context.Context, userID string, raw []byte) error {
res, err := s.db.ExecContext(ctx,
`UPDATE users SET preferences = $2 WHERE id = $1`, userID, string(raw))
return s.requireRow(s.db.ExecContext(ctx,
`UPDATE users SET preferences = $2 WHERE id = $1`, userID, string(raw)))
}
func (s *SQLiteStore) requireRow(res sql.Result, err error) error {
if err != nil {
return err
}
@@ -109,3 +139,21 @@ func (s *SQLiteStore) RevokeAllUserTokens(ctx context.Context, userID string) er
userID, sqliteutil.FormatTime(time.Now()))
return err
}
// mapUniqueViolationSQLite converts a SQLite unique constraint violation into
// the domain sentinel so the service can return a conflict for the right field.
func mapUniqueViolationSQLite(err error) error {
if err == nil {
return nil
}
msg := err.Error()
if strings.Contains(msg, "UNIQUE constraint failed") {
if strings.Contains(msg, "users.phone") {
return ErrPhoneTaken
}
if strings.Contains(msg, "users.email") {
return ErrEmailTaken
}
}
return err
}
+84 -18
View File
@@ -4,8 +4,10 @@ import (
"context"
"encoding/json"
"errors"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"galo/internal/models"
@@ -13,39 +15,51 @@ import (
var ErrNotFound = errors.New("not found")
// ErrEmailTaken and ErrPhoneTaken are returned when a unique constraint on the
// corresponding identifier is violated, so callers can map a race to the same
// conflict code as the pre-flight existence check.
var (
ErrEmailTaken = errors.New("email taken")
ErrPhoneTaken = errors.New("phone taken")
)
type Store struct {
pool *pgxpool.Pool
}
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
const userColumns = `id, COALESCE(email, ''), COALESCE(phone, ''), password_hash, name,
COALESCE(avatar_url, ''), COALESCE(preferences, '{}'::jsonb)::text, created_at`
func (s *Store) CreateUser(ctx context.Context, u *models.User) error {
_, err := s.pool.Exec(ctx,
`INSERT INTO users (id, email, password_hash, name, avatar_url)
VALUES ($1, $2, $3, $4, $5)`,
u.ID, u.Email, u.PasswordHash, u.Name, nullIfEmpty(u.AvatarURL),
`INSERT INTO users (id, email, phone, password_hash, name, avatar_url)
VALUES ($1, $2, $3, $4, $5, $6)`,
u.ID, nullIfEmpty(u.Email), nullIfEmpty(u.Phone), u.PasswordHash, u.Name, nullIfEmpty(u.AvatarURL),
)
return err
return mapUniqueViolation(err)
}
func (s *Store) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
return s.scanUser(s.pool.QueryRow(ctx,
`SELECT id, email, password_hash, name, COALESCE(avatar_url, ''),
COALESCE(preferences, '{}'::jsonb)::text, created_at
FROM users WHERE lower(email) = lower($1)`, email))
`SELECT `+userColumns+` FROM users WHERE lower(email) = lower($1)`, email))
}
func (s *Store) GetUserByPhone(ctx context.Context, phone string) (*models.User, error) {
return s.scanUser(s.pool.QueryRow(ctx,
`SELECT `+userColumns+` FROM users WHERE phone = $1`, phone))
}
func (s *Store) GetUserByID(ctx context.Context, id string) (*models.User, error) {
return s.scanUser(s.pool.QueryRow(ctx,
`SELECT id, email, password_hash, name, COALESCE(avatar_url, ''),
COALESCE(preferences, '{}'::jsonb)::text, created_at
FROM users WHERE id = $1`, id))
`SELECT `+userColumns+` FROM users WHERE id = $1`, id))
}
func (s *Store) scanUser(row pgx.Row) (*models.User, error) {
var u models.User
var prefs string
if err := row.Scan(&u.ID, &u.Email, &u.PasswordHash, &u.Name, &u.AvatarURL, &prefs, &u.CreatedAt); err != nil {
if err := row.Scan(&u.ID, &u.Email, &u.Phone, &u.PasswordHash, &u.Name, &u.AvatarURL, &prefs, &u.CreatedAt); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
@@ -57,16 +71,38 @@ func (s *Store) scanUser(row pgx.Row) (*models.User, error) {
return &u, nil
}
func (s *Store) UpdateName(ctx context.Context, userID, name string) error {
tag, err := s.pool.Exec(ctx, `UPDATE users SET name = $2 WHERE id = $1`, userID, name)
return requireRow(tag, err)
}
func (s *Store) UpdatePasswordHash(ctx context.Context, userID, hash string) error {
tag, err := s.pool.Exec(ctx, `UPDATE users SET password_hash = $2 WHERE id = $1`, userID, hash)
return requireRow(tag, err)
}
func (s *Store) AddIdentifier(ctx context.Context, userID, email, phone string) error {
tag, err := s.pool.Exec(ctx,
`UPDATE users
SET email = COALESCE(NULLIF($2, ''), email),
phone = COALESCE(NULLIF($3, ''), phone)
WHERE id = $1`,
userID, email, phone)
if err != nil {
return mapUniqueViolation(err)
}
return requireRow(tag, nil)
}
func (s *Store) DeleteUser(ctx context.Context, userID string) error {
tag, err := s.pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, userID)
return requireRow(tag, err)
}
func (s *Store) UpdatePreferences(ctx context.Context, userID string, raw []byte) error {
tag, err := s.pool.Exec(ctx,
`UPDATE users SET preferences = $2::jsonb WHERE id = $1`, userID, string(raw))
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
return requireRow(tag, err)
}
func (s *Store) CreateRefreshToken(ctx context.Context, t *models.RefreshToken) error {
@@ -111,3 +147,33 @@ func nullIfEmpty(s string) *string {
}
return &s
}
type commandTag interface {
RowsAffected() int64
}
func requireRow(tag commandTag, err error) error {
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
// mapUniqueViolation converts a PostgreSQL unique constraint violation into the
// domain sentinel so the service can return a conflict for the right field.
func mapUniqueViolation(err error) error {
if err == nil {
return nil
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
if strings.Contains(pgErr.ConstraintName, "phone") {
return ErrPhoneTaken
}
return ErrEmailTaken
}
return err
}