diff --git a/CollabTableServer/auth.go b/CollabTableServer/auth.go
index 72d888b..f32c45f 100644
--- a/CollabTableServer/auth.go
+++ b/CollabTableServer/auth.go
@@ -19,6 +19,7 @@ const (
sessionTTL = 24 * time.Hour
minPasswordLength = 8
maxUsernameLength = 64
+ maxEmailLength = 254
)
var (
@@ -26,6 +27,7 @@ var (
errSetupComplete = errors.New("Setup has already been completed.")
errInvalidCredentials = errors.New("Invalid username or password.")
errUsernameRequired = errors.New("Username is required.")
+ errEmailRequired = errors.New("Email is required and must be valid.")
errPasswordTooShort = errors.New("Password must be at least 8 characters.")
errCurrentPasswordBad = errors.New("Current password is incorrect.")
)
@@ -47,6 +49,18 @@ func normalizeUsername(value string) (string, error) {
return value, nil
}
+func normalizeEmail(value string) (string, error) {
+ value = strings.ToLower(strings.TrimSpace(value))
+ if value == "" || len([]rune(value)) > maxEmailLength || strings.Count(value, "@") != 1 {
+ return "", errEmailRequired
+ }
+ parts := strings.SplitN(value, "@", 2)
+ if parts[0] == "" || parts[1] == "" || !strings.Contains(parts[1], ".") {
+ return "", errEmailRequired
+ }
+ return value, nil
+}
+
func validatePassword(value string) error {
if len([]rune(value)) < minPasswordLength {
return errPasswordTooShort
@@ -159,11 +173,14 @@ type authStatusResponse struct {
SetupRequired bool `json:"setupRequired"`
Authenticated bool `json:"authenticated"`
Username string `json:"username,omitempty"`
+ Email string `json:"email,omitempty"`
}
type credentialsRequest struct {
- Username string `json:"username"`
- Password string `json:"password"`
+ Identifier string `json:"identifier"`
+ Username string `json:"username"`
+ Email string `json:"email"`
+ Password string `json:"password"`
}
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
@@ -186,7 +203,7 @@ func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, authStatusResponse{})
return
}
- writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
+ writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
}
func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
@@ -211,6 +228,11 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
+ email, err := normalizeEmail(request.Email)
+ if err != nil {
+ writeJSONError(w, http.StatusBadRequest, err.Error())
+ return
+ }
if err := validatePassword(request.Password); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
@@ -221,7 +243,7 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return
}
- user, err := a.db.createUser(r.Context(), username, string(hash))
+ user, err := a.db.createUser(r.Context(), username, email, string(hash))
if err != nil {
if errors.Is(err, ErrSingletonUserExists) {
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
@@ -234,7 +256,7 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return
}
- writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
+ writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
}
func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
@@ -244,12 +266,19 @@ func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
return
}
- username, err := normalizeUsername(request.Username)
- if err != nil {
+ identifier := strings.TrimSpace(request.Identifier)
+ if identifier == "" {
+ identifier = strings.TrimSpace(request.Username)
+ }
+ if identifier == "" {
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
return
}
- user, err := a.db.getUserByUsername(r.Context(), username)
+ if len([]rune(identifier)) > maxEmailLength {
+ writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
+ return
+ }
+ user, err := a.db.getUserByIdentifier(r.Context(), identifier)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return
@@ -262,7 +291,7 @@ func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return
}
- writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username})
+ writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
}
func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
@@ -277,8 +306,9 @@ func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *Au
}
type updateCredentialsRequest struct {
- CurrentPassword string `json:"currentPassword"`
+ CurrentPassword *string `json:"currentPassword"`
NewUsername *string `json:"newUsername"`
+ NewEmail *string `json:"newEmail"`
NewPassword *string `json:"newPassword"`
}
@@ -288,7 +318,7 @@ func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Req
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
return
}
- if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.CurrentPassword)) != nil {
+ if request.CurrentPassword != nil && *request.CurrentPassword != "" && bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(*request.CurrentPassword)) != nil {
writeJSONError(w, http.StatusBadRequest, errCurrentPasswordBad.Error())
return
}
@@ -301,6 +331,15 @@ func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Req
return
}
}
+ email := user.Email
+ if request.NewEmail != nil {
+ normalized, err := normalizeEmail(*request.NewEmail)
+ if err != nil {
+ writeJSONError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ email = normalized
+ }
passwordHash := user.PasswordHash
if request.NewPassword != nil && *request.NewPassword != "" {
@@ -316,7 +355,7 @@ func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Req
passwordHash = string(hash)
}
- if err := a.db.updateUserCredentials(r.Context(), user.ID, username, passwordHash); err != nil {
+ if err := a.db.updateUserCredentials(r.Context(), user.ID, username, email, passwordHash); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return
}
diff --git a/CollabTableServer/db.go b/CollabTableServer/db.go
index 08c4c30..14fbbd0 100644
--- a/CollabTableServer/db.go
+++ b/CollabTableServer/db.go
@@ -117,10 +117,13 @@ func (d *DB) initSchema(ctx context.Context) error {
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
+ email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+ ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
+ CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
CREATE TABLE IF NOT EXISTS auth_sessions (
@@ -186,6 +189,7 @@ func (d *DB) cleanupNotifications(ctx context.Context) {
type AuthUser struct {
ID int64
Username string
+ Email string
PasswordHash string
}
@@ -199,13 +203,13 @@ func (d *DB) countUsers(ctx context.Context) (int, error) {
return count, nil
}
-func (d *DB) createUser(ctx context.Context, username, passwordHash string) (*AuthUser, error) {
+func (d *DB) createUser(ctx context.Context, username, email, passwordHash string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
- INSERT INTO auth_users (username, password_hash, updated_at)
- VALUES ($1, $2, now())
- RETURNING id, username
- `, username, passwordHash).Scan(&user.ID, &user.Username)
+ INSERT INTO auth_users (username, email, password_hash, updated_at)
+ VALUES ($1, $2, $3, now())
+ RETURNING id, username, email
+ `, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
@@ -217,13 +221,13 @@ func (d *DB) createUser(ctx context.Context, username, passwordHash string) (*Au
return &user, nil
}
-func (d *DB) getUserByUsername(ctx context.Context, username string) (*AuthUser, error) {
+func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
- SELECT id, username, password_hash
+ SELECT id, username, email, password_hash
FROM auth_users
- WHERE username = $1
- `, username).Scan(&user.ID, &user.Username, &user.PasswordHash)
+ WHERE username = $1 OR lower(email) = lower($1)
+ `, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
@@ -236,11 +240,11 @@ func (d *DB) getUserByUsername(ctx context.Context, username string) (*AuthUser,
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
- SELECT u.id, u.username, u.password_hash
+ SELECT u.id, u.username, u.email, u.password_hash
FROM auth_sessions s
JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > now()
- `, tokenHash).Scan(&user.ID, &user.Username, &user.PasswordHash)
+ `, tokenHash).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
@@ -269,12 +273,12 @@ func (d *DB) deleteSession(ctx context.Context, tokenHash string) error {
return nil
}
-func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, passwordHash string) error {
+func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, email, passwordHash string) error {
_, err := d.pool.Exec(ctx, `
UPDATE auth_users
- SET username = $1, password_hash = $2, updated_at = now()
- WHERE id = $3
- `, username, passwordHash, userID)
+ SET username = $1, email = $2, password_hash = $3, updated_at = now()
+ WHERE id = $4
+ `, username, email, passwordHash, userID)
if err != nil {
return fmt.Errorf("update user credentials: %w", err)
}
diff --git a/CollabTableServer/webui/src/lib/api.js b/CollabTableServer/webui/src/lib/api.js
index 93209bc..00060d3 100644
--- a/CollabTableServer/webui/src/lib/api.js
+++ b/CollabTableServer/webui/src/lib/api.js
@@ -41,21 +41,21 @@ export async function fetchAuthStatus() {
return getJson('/api/auth/status');
}
-export async function setupAccount(username, password) {
- return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, password }) });
+export async function setupAccount(username, email, password) {
+ return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) });
}
-export async function login(username, password) {
- return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) });
+export async function login(identifier, password) {
+ return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password }) });
}
export async function logout() {
return request('/api/auth/logout', { method: 'POST' });
}
-export async function updateCredentials({ currentPassword, newUsername, newPassword }) {
+export async function updateCredentials({ newUsername, newEmail, newPassword }) {
return request('/api/auth/credentials', {
method: 'POST',
- body: JSON.stringify({ currentPassword, newUsername, newPassword }),
+ body: JSON.stringify({ newUsername, newEmail, newPassword }),
});
}
diff --git a/CollabTableServer/webui/src/lib/components/Header.svelte b/CollabTableServer/webui/src/lib/components/Header.svelte
index 0891275..ffbad5a 100644
--- a/CollabTableServer/webui/src/lib/components/Header.svelte
+++ b/CollabTableServer/webui/src/lib/components/Header.svelte
@@ -118,5 +118,9 @@
-