feat(auth): add user profile, phone login, and account deletion
This commit is contained in:
@@ -133,6 +133,10 @@ func (s *Server) Router() *gin.Engine {
|
||||
authed.Use(s.auth.Middleware())
|
||||
|
||||
authed.GET("/auth/me", authHandler.Me)
|
||||
authed.PATCH("/auth/me", authHandler.UpdateMe)
|
||||
authed.POST("/auth/me/password", authHandler.ChangePassword)
|
||||
authed.POST("/auth/me/identifiers", authHandler.AddIdentifier)
|
||||
authed.DELETE("/auth/me", authHandler.DeleteMe)
|
||||
authed.PATCH("/auth/me/preferences", authHandler.UpdatePreferences)
|
||||
authed.GET("/sse/albums/:id", s.albumSSE)
|
||||
authed.GET("/sse/me", s.meSSE)
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"galo/internal/app"
|
||||
"galo/internal/config"
|
||||
"galo/internal/models"
|
||||
)
|
||||
|
||||
// TestAuthProfileFlowOverHTTP drives the whole account lifecycle through the
|
||||
// real HTTP router: register phone-only, log in, add an email, change the
|
||||
// password (revoking sessions), and delete the account.
|
||||
func TestAuthProfileFlowOverHTTP(t *testing.T) {
|
||||
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
srv := app.New(&config.Config{}, st.repos, st.db.PingContext, st.tm, st.storage, st.hub)
|
||||
router := srv.Router()
|
||||
|
||||
do := func(method, path, token string, body any) *httptest.ResponseRecorder {
|
||||
var buf bytes.Buffer
|
||||
if body != nil {
|
||||
_ = json.NewEncoder(&buf).Encode(body)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, &buf)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
type tokens struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
type authBody struct {
|
||||
User models.SelfUser `json:"user"`
|
||||
Tokens tokens `json:"tokens"`
|
||||
}
|
||||
|
||||
phone := "+15550007000"
|
||||
// Register with a phone only — no email.
|
||||
rec := do(http.MethodPost, "/api/auth/register", "", map[string]string{
|
||||
"phone": phone, "password": "password123", "name": "Phone Only",
|
||||
})
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("register status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var registered authBody
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), ®istered); err != nil {
|
||||
t.Fatalf("decode register: %v", err)
|
||||
}
|
||||
if registered.User.Phone != phone || registered.User.Email != "" {
|
||||
t.Fatalf("registered user = %+v", registered.User)
|
||||
}
|
||||
|
||||
// Log in by phone.
|
||||
rec = do(http.MethodPost, "/api/auth/login", "", map[string]string{
|
||||
"identifier": phone, "password": "password123",
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("login status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var logged authBody
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &logged)
|
||||
access := logged.Tokens.AccessToken
|
||||
|
||||
// Add the missing email identifier.
|
||||
rec = do(http.MethodPost, "/api/auth/me/identifiers", access, map[string]string{
|
||||
"email": "phoneonly@test.local",
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("add identifier status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var added struct {
|
||||
User models.SelfUser `json:"user"`
|
||||
}
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &added)
|
||||
if added.User.Email != "phoneonly@test.local" {
|
||||
t.Fatalf("email not added: %+v", added.User)
|
||||
}
|
||||
|
||||
// Change the password, which revokes every refresh token.
|
||||
rec = do(http.MethodPost, "/api/auth/me/password", access, map[string]string{
|
||||
"current_password": "password123", "new_password": "newpassword",
|
||||
})
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("change password status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec = do(http.MethodPost, "/api/auth/refresh", "", map[string]string{
|
||||
"refresh_token": logged.Tokens.RefreshToken,
|
||||
})
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("refresh after password change status = %d, want 401", rec.Code)
|
||||
}
|
||||
|
||||
// The new password works; login by the added email.
|
||||
rec = do(http.MethodPost, "/api/auth/login", "", map[string]string{
|
||||
"identifier": "phoneonly@test.local", "password": "newpassword",
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("login with new password status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var relogged authBody
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &relogged)
|
||||
|
||||
// Delete the account: it disappears immediately.
|
||||
rec = do(http.MethodDelete, "/api/auth/me", relogged.Tokens.AccessToken, map[string]string{
|
||||
"password": "newpassword",
|
||||
})
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("delete status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec = do(http.MethodPost, "/api/auth/login", "", map[string]string{
|
||||
"identifier": phone, "password": "newpassword",
|
||||
})
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("login after delete status = %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
@@ -80,13 +81,118 @@ func openStack(t *testing.T, path, blobRoot string) (*stack, func()) {
|
||||
return &stack{db: database, photos: photosSvc, albums: albumsSvc, auth: authSvc, hub: hub, tm: tm, repos: repos, storage: blob}, func() { database.Close() }
|
||||
}
|
||||
|
||||
func TestUsersSchemaSupportsPhone(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "galo.db")
|
||||
st, closeDB := openStack(t, path, t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
var emailNotNull int
|
||||
if err := st.db.QueryRowContext(ctx,
|
||||
`SELECT "notnull" FROM pragma_table_info('users') WHERE name='email'`).Scan(&emailNotNull); err != nil {
|
||||
t.Fatalf("email column: %v", err)
|
||||
}
|
||||
if emailNotNull != 0 {
|
||||
t.Fatalf("users.email is still NOT NULL")
|
||||
}
|
||||
|
||||
var phoneCols int
|
||||
if err := st.db.QueryRowContext(ctx,
|
||||
`SELECT count(*) FROM pragma_table_info('users') WHERE name='phone'`).Scan(&phoneCols); err != nil {
|
||||
t.Fatalf("phone column: %v", err)
|
||||
}
|
||||
if phoneCols != 1 {
|
||||
t.Fatalf("users.phone column missing")
|
||||
}
|
||||
|
||||
insert := func(id, email, phone string) error {
|
||||
var e any
|
||||
if email != "" {
|
||||
e = email
|
||||
}
|
||||
var p any
|
||||
if phone != "" {
|
||||
p = phone
|
||||
}
|
||||
_, err := st.db.ExecContext(ctx,
|
||||
`INSERT INTO users (id, email, phone, password_hash, name) VALUES ($1, $2, $3, 'x', 'U')`,
|
||||
id, e, p)
|
||||
return err
|
||||
}
|
||||
|
||||
// A phone-only account is allowed (email NULL).
|
||||
if err := insert("u-phone-only", "", "+15550000001"); err != nil {
|
||||
t.Fatalf("insert phone-only user: %v", err)
|
||||
}
|
||||
// A second email-less account is allowed: NULL emails do not collide.
|
||||
if err := insert("u-phone-only-2", "", "+15550000002"); err != nil {
|
||||
t.Fatalf("insert second phone-only user: %v", err)
|
||||
}
|
||||
// Phone must be unique.
|
||||
if err := insert("u-dup-phone", "dup@test.local", "+15550000001"); err == nil {
|
||||
t.Fatalf("duplicate phone accepted")
|
||||
}
|
||||
// A phone-only insert without a phone must be rejected by application
|
||||
// logic; the schema itself still permits it, which is by design.
|
||||
if err := insert("u-email-1", "same@test.local", ""); err != nil {
|
||||
t.Fatalf("insert email user: %v", err)
|
||||
}
|
||||
if err := insert("u-email-dup", "same@test.local", ""); err == nil {
|
||||
t.Fatalf("duplicate email accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAccountRemovesSharedAlbum(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "galo.db")
|
||||
st, closeDB := openStack(t, path, t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
owner, _, err := st.auth.Register(ctx, "ownerdel@test.local", "", "password123", "Owner")
|
||||
if err != nil {
|
||||
t.Fatalf("register owner: %v", err)
|
||||
}
|
||||
member, _, err := st.auth.Register(ctx, "memberdel@test.local", "", "password123", "Member")
|
||||
if err != nil {
|
||||
t.Fatalf("register member: %v", err)
|
||||
}
|
||||
album, err := st.albums.Create(ctx, owner.ID, albums.CreateInput{Title: "Shared"})
|
||||
if err != nil {
|
||||
t.Fatalf("create album: %v", err)
|
||||
}
|
||||
if _, err := st.db.ExecContext(ctx,
|
||||
`INSERT INTO album_members (album_id, user_id, role) VALUES ($1, $2, 'member')`, album.ID, member.ID); err != nil {
|
||||
t.Fatalf("add member: %v", err)
|
||||
}
|
||||
if list, err := st.repos.Albums.ListForUser(ctx, member.ID); err != nil || len(list) != 1 {
|
||||
t.Fatalf("member albums before delete = %d err=%v", len(list), err)
|
||||
}
|
||||
|
||||
if err := st.auth.DeleteAccount(ctx, owner.ID, "password123"); err != nil {
|
||||
t.Fatalf("delete account: %v", err)
|
||||
}
|
||||
|
||||
if list, err := st.repos.Albums.ListForUser(ctx, member.ID); err != nil || len(list) != 0 {
|
||||
t.Fatalf("member albums after owner delete = %d err=%v, want 0", len(list), err)
|
||||
}
|
||||
if _, err := st.repos.Albums.GetByID(ctx, album.ID); !errors.Is(err, albums.ErrNotFound) {
|
||||
t.Fatalf("album survived owner deletion: %v", err)
|
||||
}
|
||||
if role, _ := st.repos.Members.Role(ctx, album.ID, member.ID); role != "" {
|
||||
t.Fatalf("membership survived: %q", role)
|
||||
}
|
||||
if _, err := st.repos.Auth.GetUserByID(ctx, member.ID); err != nil {
|
||||
t.Fatalf("member account removed by cascade: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadSetsDefaultCover(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "galo.db")
|
||||
st, closeDB := openStack(t, path, t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
user, _, err := st.auth.Register(ctx, "cover@test.local", "password123", "C")
|
||||
user, _, err := st.auth.Register(ctx, "cover@test.local", "", "password123", "C")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
@@ -130,7 +236,7 @@ func TestCoverClearedWhenCoverPhotoLeaves(t *testing.T) {
|
||||
st, closeDB := openStack(t, path, t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
user, _, err := st.auth.Register(ctx, "clear@test.local", "password123", "C")
|
||||
user, _, err := st.auth.Register(ctx, "clear@test.local", "", "password123", "C")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
@@ -190,7 +296,7 @@ func TestWorkerPublishesPhotoUpdated(t *testing.T) {
|
||||
defer cancel()
|
||||
go worker.Run(wctx)
|
||||
|
||||
user, _, err := st.auth.Register(ctx, "evt@test.local", "password123", "E")
|
||||
user, _, err := st.auth.Register(ctx, "evt@test.local", "", "password123", "E")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
@@ -228,7 +334,7 @@ func TestSQLiteEndToEndWithRestart(t *testing.T) {
|
||||
wctx, cancel := context.WithCancel(ctx)
|
||||
go worker.Run(wctx)
|
||||
|
||||
user, _, err := st.auth.Register(ctx, "e2e@test.local", "password123", "E2E")
|
||||
user, _, err := st.auth.Register(ctx, "e2e@test.local", "", "password123", "E2E")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestPermanentDeleteAlbumlessPhoto(t *testing.T) {
|
||||
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
user, _, err := st.auth.Register(ctx, "albumless@test.local", "password123", "A")
|
||||
user, _, err := st.auth.Register(ctx, "albumless@test.local", "", "password123", "A")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
@@ -78,11 +78,11 @@ func TestEmptyTrashSkipsForeignPhotos(t *testing.T) {
|
||||
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
owner, _, err := st.auth.Register(ctx, "owner@test.local", "password123", "O")
|
||||
owner, _, err := st.auth.Register(ctx, "owner@test.local", "", "password123", "O")
|
||||
if err != nil {
|
||||
t.Fatalf("register owner: %v", err)
|
||||
}
|
||||
member, _, err := st.auth.Register(ctx, "member@test.local", "password123", "M")
|
||||
member, _, err := st.auth.Register(ctx, "member@test.local", "", "password123", "M")
|
||||
if err != nil {
|
||||
t.Fatalf("register member: %v", err)
|
||||
}
|
||||
@@ -150,7 +150,7 @@ func TestListTrashIdentitiesNotCapped(t *testing.T) {
|
||||
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
user, _, err := st.auth.Register(ctx, "many@test.local", "password123", "M")
|
||||
user, _, err := st.auth.Register(ctx, "many@test.local", "", "password123", "M")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
@@ -184,7 +184,7 @@ func TestEmptyTrashReturnsZeroWhenEmpty(t *testing.T) {
|
||||
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
user, _, err := st.auth.Register(ctx, "empty@test.local", "password123", "E")
|
||||
user, _, err := st.auth.Register(ctx, "empty@test.local", "", "password123", "E")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
@@ -202,7 +202,7 @@ func TestEmptyTrashHTTP(t *testing.T) {
|
||||
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
user, pair, err := st.auth.Register(ctx, "http@test.local", "password123", "H")
|
||||
user, pair, err := st.auth.Register(ctx, "http@test.local", "", "password123", "H")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestVideoUploadPreparedForPlayback(t *testing.T) {
|
||||
st, closeDB := openStack(t, path, t.TempDir())
|
||||
defer closeDB()
|
||||
|
||||
user, _, err := st.auth.Register(ctx, "video@test.local", "password123", "V")
|
||||
user, _, err := st.auth.Register(ctx, "video@test.local", "", "password123", "V")
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import "time"
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
PasswordHash string `json:"-"`
|
||||
Name string `json:"name"`
|
||||
AvatarURL string `json:"avatar_url,omitempty"`
|
||||
@@ -26,6 +27,23 @@ func (u *User) Public() PublicUser {
|
||||
return PublicUser{ID: u.ID, Email: u.Email, Name: u.Name, AvatarURL: u.AvatarURL}
|
||||
}
|
||||
|
||||
// SelfUser is the owner-facing representation of an account. Unlike PublicUser
|
||||
// it carries the phone number, which must never appear in public views.
|
||||
type SelfUser struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Name string `json:"name"`
|
||||
AvatarURL string `json:"avatar_url,omitempty"`
|
||||
}
|
||||
|
||||
func (u *User) Self() SelfUser {
|
||||
if u == nil {
|
||||
return SelfUser{}
|
||||
}
|
||||
return SelfUser{ID: u.ID, Email: u.Email, Phone: u.Phone, Name: u.Name, AvatarURL: u.AvatarURL}
|
||||
}
|
||||
|
||||
type Album struct {
|
||||
ID string `json:"id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPublicUserOmitsPhone(t *testing.T) {
|
||||
u := &User{ID: "u1", Email: "user@test.local", Phone: "+15551234567", Name: "Tester"}
|
||||
|
||||
pub, err := json.Marshal(u.Public())
|
||||
if err != nil {
|
||||
t.Fatalf("marshal public: %v", err)
|
||||
}
|
||||
if strings.Contains(string(pub), "phone") || strings.Contains(string(pub), "+15551234567") {
|
||||
t.Fatalf("PublicUser leaks phone: %s", pub)
|
||||
}
|
||||
|
||||
self, err := json.Marshal(u.Self())
|
||||
if err != nil {
|
||||
t.Fatalf("marshal self: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(self), "+15551234567") {
|
||||
t.Fatalf("SelfUser missing phone: %s", self)
|
||||
}
|
||||
if !strings.Contains(string(self), `"phone"`) {
|
||||
t.Fatalf("SelfUser phone not serialized: %s", self)
|
||||
}
|
||||
}
|
||||
@@ -121,6 +121,46 @@ func testAuth(t *testing.T, ctx context.Context, r Repos) {
|
||||
if _, err := r.Auth.GetUserByEmail(ctx, "missing@test.local"); !errors.Is(err, auth.ErrNotFound) {
|
||||
t.Fatalf("missing email err = %v, want ErrNotFound", err)
|
||||
}
|
||||
if _, err := r.Auth.GetUserByPhone(ctx, "+15550000000"); !errors.Is(err, auth.ErrNotFound) {
|
||||
t.Fatalf("missing phone err = %v, want ErrNotFound", err)
|
||||
}
|
||||
|
||||
// A phone-only account stores NULL email and is retrievable by phone.
|
||||
phoneUser := &models.User{ID: newID(), Phone: "+15550000001", PasswordHash: "x", Name: "Phone Only"}
|
||||
if err := r.Auth.CreateUser(ctx, phoneUser); err != nil {
|
||||
t.Fatalf("create phone-only user: %v", err)
|
||||
}
|
||||
byPhone, err := r.Auth.GetUserByPhone(ctx, phoneUser.Phone)
|
||||
if err != nil || byPhone.ID != phoneUser.ID || byPhone.Email != "" {
|
||||
t.Fatalf("get by phone: %v %+v", err, byPhone)
|
||||
}
|
||||
|
||||
// Adding the missing identifier fills only the empty column.
|
||||
if err := r.Auth.AddIdentifier(ctx, phoneUser.ID, "added@test.local", ""); err != nil {
|
||||
t.Fatalf("add identifier: %v", err)
|
||||
}
|
||||
withEmail, _ := r.Auth.GetUserByID(ctx, phoneUser.ID)
|
||||
if withEmail.Email != "added@test.local" || withEmail.Phone != phoneUser.Phone {
|
||||
t.Fatalf("identifier not added: %+v", withEmail)
|
||||
}
|
||||
|
||||
if err := r.Auth.UpdateName(ctx, u.ID, "Renamed"); err != nil {
|
||||
t.Fatalf("update name: %v", err)
|
||||
}
|
||||
if err := r.Auth.UpdatePasswordHash(ctx, u.ID, "newhash"); err != nil {
|
||||
t.Fatalf("update password: %v", err)
|
||||
}
|
||||
renamed, _ := r.Auth.GetUserByID(ctx, u.ID)
|
||||
if renamed.Name != "Renamed" || renamed.PasswordHash != "newhash" {
|
||||
t.Fatalf("user updates not applied: %+v", renamed)
|
||||
}
|
||||
|
||||
if err := r.Auth.DeleteUser(ctx, phoneUser.ID); err != nil {
|
||||
t.Fatalf("delete user: %v", err)
|
||||
}
|
||||
if _, err := r.Auth.GetUserByID(ctx, phoneUser.ID); !errors.Is(err, auth.ErrNotFound) {
|
||||
t.Fatalf("deleted user still present")
|
||||
}
|
||||
|
||||
if err := r.Auth.UpdatePreferences(ctx, u.ID, []byte(`{"theme":"dark"}`)); err != nil {
|
||||
t.Fatalf("update preferences: %v", err)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE users DROP CONSTRAINT IF EXISTS users_phone_key;
|
||||
ALTER TABLE users DROP COLUMN IF EXISTS phone;
|
||||
ALTER TABLE users ALTER COLUMN email SET NOT NULL;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- A second login identifier: phone (E.164), nullable and unique. Email becomes
|
||||
-- optional so phone-only accounts are possible; the "at least one identifier"
|
||||
-- rule is enforced in the application layer.
|
||||
ALTER TABLE users ALTER COLUMN email DROP NOT NULL;
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS phone text;
|
||||
ALTER TABLE users ADD CONSTRAINT users_phone_key UNIQUE (phone);
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Email is restored to NOT NULL, so phone-only accounts (email IS NULL) cannot
|
||||
-- be represented and are dropped. Down is only safe when no such accounts exist.
|
||||
DELETE FROM users WHERE email IS NULL;
|
||||
|
||||
CREATE TABLE users_old (
|
||||
id TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
avatar_url TEXT,
|
||||
preferences TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
||||
);
|
||||
|
||||
INSERT INTO users_old (id, email, password_hash, name, avatar_url, preferences, created_at)
|
||||
SELECT id, email, password_hash, name, avatar_url, preferences, created_at
|
||||
FROM users WHERE email IS NOT NULL;
|
||||
|
||||
DROP TABLE users;
|
||||
|
||||
ALTER TABLE users_old RENAME TO users;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- SQLite cannot drop a NOT NULL constraint via ALTER, so rebuild the users
|
||||
-- table: email becomes nullable, phone is added as a unique second identifier,
|
||||
-- and existing rows are carried across (phone stays NULL).
|
||||
CREATE TABLE users_new (
|
||||
id TEXT PRIMARY KEY,
|
||||
email TEXT UNIQUE,
|
||||
phone TEXT UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
avatar_url TEXT,
|
||||
preferences TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
||||
);
|
||||
|
||||
INSERT INTO users_new (id, email, phone, password_hash, name, avatar_url, preferences, created_at)
|
||||
SELECT id, email, NULL, password_hash, name, avatar_url, preferences, created_at FROM users;
|
||||
|
||||
DROP TABLE users;
|
||||
|
||||
ALTER TABLE users_new RENAME TO users;
|
||||
Reference in New Issue
Block a user