feat(auth): add email handling for user authentication and account setup
feat(api): update API methods to include email and identifier for authentication feat(ui): enhance authentication forms to support email input feat(settings): implement language selection in settings dialog feat(language): add language management for multilingual support
This commit is contained in:
1 parent
cac2faae2e
commit
6394374766
9 files changed
+210
-53
No files matched your search
+49
-10
@@ -19,6 +19,7 @@ const (
|
|||||||
sessionTTL = 24 * time.Hour
|
sessionTTL = 24 * time.Hour
|
||||||
minPasswordLength = 8
|
minPasswordLength = 8
|
||||||
maxUsernameLength = 64
|
maxUsernameLength = 64
|
||||||
|
maxEmailLength = 254
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -26,6 +27,7 @@ var (
|
|||||||
errSetupComplete = errors.New("Setup has already been completed.")
|
errSetupComplete = errors.New("Setup has already been completed.")
|
||||||
errInvalidCredentials = errors.New("Invalid username or password.")
|
errInvalidCredentials = errors.New("Invalid username or password.")
|
||||||
errUsernameRequired = errors.New("Username is required.")
|
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.")
|
errPasswordTooShort = errors.New("Password must be at least 8 characters.")
|
||||||
errCurrentPasswordBad = errors.New("Current password is incorrect.")
|
errCurrentPasswordBad = errors.New("Current password is incorrect.")
|
||||||
)
|
)
|
||||||
@@ -47,6 +49,18 @@ func normalizeUsername(value string) (string, error) {
|
|||||||
return value, nil
|
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 {
|
func validatePassword(value string) error {
|
||||||
if len([]rune(value)) < minPasswordLength {
|
if len([]rune(value)) < minPasswordLength {
|
||||||
return errPasswordTooShort
|
return errPasswordTooShort
|
||||||
@@ -159,10 +173,13 @@ type authStatusResponse struct {
|
|||||||
SetupRequired bool `json:"setupRequired"`
|
SetupRequired bool `json:"setupRequired"`
|
||||||
Authenticated bool `json:"authenticated"`
|
Authenticated bool `json:"authenticated"`
|
||||||
Username string `json:"username,omitempty"`
|
Username string `json:"username,omitempty"`
|
||||||
|
Email string `json:"email,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type credentialsRequest struct {
|
type credentialsRequest struct {
|
||||||
|
Identifier string `json:"identifier"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,7 +203,7 @@ func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, authStatusResponse{})
|
writeJSON(w, http.StatusOK, authStatusResponse{})
|
||||||
return
|
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) {
|
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())
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
email, err := normalizeEmail(request.Email)
|
||||||
|
if err != nil {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
if err := validatePassword(request.Password); err != nil {
|
if err := validatePassword(request.Password); err != nil {
|
||||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
@@ -221,7 +243,7 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||||
return
|
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 err != nil {
|
||||||
if errors.Is(err, ErrSingletonUserExists) {
|
if errors.Is(err, ErrSingletonUserExists) {
|
||||||
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
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")
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||||
return
|
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) {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
username, err := normalizeUsername(request.Username)
|
identifier := strings.TrimSpace(request.Identifier)
|
||||||
if err != nil {
|
if identifier == "" {
|
||||||
|
identifier = strings.TrimSpace(request.Username)
|
||||||
|
}
|
||||||
|
if identifier == "" {
|
||||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||||
return
|
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 {
|
if err != nil {
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||||
return
|
return
|
||||||
@@ -262,7 +291,7 @@ func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||||
return
|
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) {
|
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 {
|
type updateCredentialsRequest struct {
|
||||||
CurrentPassword string `json:"currentPassword"`
|
CurrentPassword *string `json:"currentPassword"`
|
||||||
NewUsername *string `json:"newUsername"`
|
NewUsername *string `json:"newUsername"`
|
||||||
|
NewEmail *string `json:"newEmail"`
|
||||||
NewPassword *string `json:"newPassword"`
|
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")
|
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||||
return
|
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())
|
writeJSONError(w, http.StatusBadRequest, errCurrentPasswordBad.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -301,6 +331,15 @@ func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Req
|
|||||||
return
|
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
|
passwordHash := user.PasswordHash
|
||||||
if request.NewPassword != nil && *request.NewPassword != "" {
|
if request.NewPassword != nil && *request.NewPassword != "" {
|
||||||
@@ -316,7 +355,7 @@ func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Req
|
|||||||
passwordHash = string(hash)
|
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")
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-15
@@ -117,10 +117,13 @@ func (d *DB) initSchema(ctx context.Context) error {
|
|||||||
CREATE TABLE IF NOT EXISTS auth_users (
|
CREATE TABLE IF NOT EXISTS auth_users (
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
username TEXT NOT NULL UNIQUE,
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
email TEXT NOT NULL DEFAULT '',
|
||||||
password_hash TEXT NOT NULL,
|
password_hash TEXT NOT NULL,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
updated_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 UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||||
@@ -186,6 +189,7 @@ func (d *DB) cleanupNotifications(ctx context.Context) {
|
|||||||
type AuthUser struct {
|
type AuthUser struct {
|
||||||
ID int64
|
ID int64
|
||||||
Username string
|
Username string
|
||||||
|
Email string
|
||||||
PasswordHash string
|
PasswordHash string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,13 +203,13 @@ func (d *DB) countUsers(ctx context.Context) (int, error) {
|
|||||||
return count, nil
|
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
|
var user AuthUser
|
||||||
err := d.pool.QueryRow(ctx, `
|
err := d.pool.QueryRow(ctx, `
|
||||||
INSERT INTO auth_users (username, password_hash, updated_at)
|
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||||
VALUES ($1, $2, now())
|
VALUES ($1, $2, $3, now())
|
||||||
RETURNING id, username
|
RETURNING id, username, email
|
||||||
`, username, passwordHash).Scan(&user.ID, &user.Username)
|
`, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var pgErr *pgconn.PgError
|
var pgErr *pgconn.PgError
|
||||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
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
|
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
|
var user AuthUser
|
||||||
err := d.pool.QueryRow(ctx, `
|
err := d.pool.QueryRow(ctx, `
|
||||||
SELECT id, username, password_hash
|
SELECT id, username, email, password_hash
|
||||||
FROM auth_users
|
FROM auth_users
|
||||||
WHERE username = $1
|
WHERE username = $1 OR lower(email) = lower($1)
|
||||||
`, username).Scan(&user.ID, &user.Username, &user.PasswordHash)
|
`, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, nil
|
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) {
|
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
|
||||||
var user AuthUser
|
var user AuthUser
|
||||||
err := d.pool.QueryRow(ctx, `
|
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
|
FROM auth_sessions s
|
||||||
JOIN auth_users u ON u.id = s.user_id
|
JOIN auth_users u ON u.id = s.user_id
|
||||||
WHERE s.token_hash = $1 AND s.expires_at > now()
|
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) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -269,12 +273,12 @@ func (d *DB) deleteSession(ctx context.Context, tokenHash string) error {
|
|||||||
return nil
|
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, `
|
_, err := d.pool.Exec(ctx, `
|
||||||
UPDATE auth_users
|
UPDATE auth_users
|
||||||
SET username = $1, password_hash = $2, updated_at = now()
|
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||||
WHERE id = $3
|
WHERE id = $4
|
||||||
`, username, passwordHash, userID)
|
`, username, email, passwordHash, userID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("update user credentials: %w", err)
|
return fmt.Errorf("update user credentials: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,21 +41,21 @@ export async function fetchAuthStatus() {
|
|||||||
return getJson('/api/auth/status');
|
return getJson('/api/auth/status');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setupAccount(username, password) {
|
export async function setupAccount(username, email, password) {
|
||||||
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, password }) });
|
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function login(username, password) {
|
export async function login(identifier, password) {
|
||||||
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) });
|
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function logout() {
|
export async function logout() {
|
||||||
return request('/api/auth/logout', { method: 'POST' });
|
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', {
|
return request('/api/auth/credentials', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ currentPassword, newUsername, newPassword }),
|
body: JSON.stringify({ newUsername, newEmail, newPassword }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -118,5 +118,9 @@
|
|||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<CredentialsDialog bind:open={credentialsOpen} currentUsername={auth.status?.username ?? ''} />
|
<CredentialsDialog
|
||||||
|
bind:open={credentialsOpen}
|
||||||
|
currentUsername={auth.status?.username ?? ''}
|
||||||
|
currentEmail={auth.status?.email ?? ''}
|
||||||
|
/>
|
||||||
<SettingsDialog bind:open={settingsOpen} />
|
<SettingsDialog bind:open={settingsOpen} />
|
||||||
@@ -8,6 +8,8 @@
|
|||||||
const auth = useAuth();
|
const auth = useAuth();
|
||||||
|
|
||||||
let username = $state('');
|
let username = $state('');
|
||||||
|
let email = $state('');
|
||||||
|
let identifier = $state('');
|
||||||
let password = $state('');
|
let password = $state('');
|
||||||
let confirmPassword = $state('');
|
let confirmPassword = $state('');
|
||||||
let submitting = $state(false);
|
let submitting = $state(false);
|
||||||
@@ -25,9 +27,9 @@
|
|||||||
submitting = true;
|
submitting = true;
|
||||||
try {
|
try {
|
||||||
if (setupRequired) {
|
if (setupRequired) {
|
||||||
await auth.setup(username, password);
|
await auth.setup(username, email, password);
|
||||||
} else {
|
} else {
|
||||||
await auth.login(username, password);
|
await auth.login(identifier, password);
|
||||||
}
|
}
|
||||||
} catch (submitError) {
|
} catch (submitError) {
|
||||||
error = submitError instanceof Error ? submitError.message : 'Request failed.';
|
error = submitError instanceof Error ? submitError.message : 'Request failed.';
|
||||||
@@ -48,7 +50,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form class="space-y-4" onsubmit={submit}>
|
<form class="space-y-4" onsubmit={submit}>
|
||||||
<div>
|
{#if setupRequired}
|
||||||
<label for="auth-username" class="mb-1 block text-sm font-medium">Username</label>
|
<label for="auth-username" class="mb-1 block text-sm font-medium">Username</label>
|
||||||
<!-- svelte-ignore a11y_autofocus -->
|
<!-- svelte-ignore a11y_autofocus -->
|
||||||
<input
|
<input
|
||||||
@@ -59,7 +61,27 @@
|
|||||||
required
|
required
|
||||||
autofocus
|
autofocus
|
||||||
/>
|
/>
|
||||||
</div>
|
<label for="auth-email" class="mb-1 block text-sm font-medium">Email</label>
|
||||||
|
<input
|
||||||
|
id="auth-email"
|
||||||
|
type="email"
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
bind:value={email}
|
||||||
|
autocomplete="email"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<label for="auth-identifier" class="mb-1 block text-sm font-medium">Username or email</label>
|
||||||
|
<!-- svelte-ignore a11y_autofocus -->
|
||||||
|
<input
|
||||||
|
id="auth-identifier"
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
bind:value={identifier}
|
||||||
|
autocomplete="username"
|
||||||
|
required
|
||||||
|
autofocus
|
||||||
|
/>
|
||||||
|
{/if}
|
||||||
<div>
|
<div>
|
||||||
<label for="auth-password" class="mb-1 block text-sm font-medium">Password</label>
|
<label for="auth-password" class="mb-1 block text-sm font-medium">Password</label>
|
||||||
<input
|
<input
|
||||||
|
|||||||
@@ -3,19 +3,22 @@
|
|||||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
|
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
|
||||||
import { useAuth } from '$lib/features/auth/auth.svelte.js';
|
import { useAuth } from '$lib/features/auth/auth.svelte.js';
|
||||||
|
|
||||||
let { open = $bindable(false), currentUsername } = $props();
|
let { open = $bindable(false), currentUsername, currentEmail } = $props();
|
||||||
|
|
||||||
const auth = useAuth();
|
const auth = useAuth();
|
||||||
|
|
||||||
let username = $state('');
|
let username = $state('');
|
||||||
let currentPassword = $state('');
|
let email = $state('');
|
||||||
let newPassword = $state('');
|
let newPassword = $state('');
|
||||||
let confirmPassword = $state('');
|
let confirmPassword = $state('');
|
||||||
let error = $state('');
|
let error = $state('');
|
||||||
let saving = $state(false);
|
let saving = $state(false);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (open) username = currentUsername;
|
if (open) {
|
||||||
|
username = currentUsername;
|
||||||
|
email = currentEmail;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
async function submit(event) {
|
async function submit(event) {
|
||||||
@@ -29,11 +32,10 @@
|
|||||||
saving = true;
|
saving = true;
|
||||||
try {
|
try {
|
||||||
await auth.updateCredentials({
|
await auth.updateCredentials({
|
||||||
currentPassword,
|
|
||||||
newUsername: username.trim() || undefined,
|
newUsername: username.trim() || undefined,
|
||||||
|
newEmail: email.trim() || undefined,
|
||||||
newPassword: newPassword || undefined,
|
newPassword: newPassword || undefined,
|
||||||
});
|
});
|
||||||
currentPassword = '';
|
|
||||||
newPassword = '';
|
newPassword = '';
|
||||||
confirmPassword = '';
|
confirmPassword = '';
|
||||||
open = false;
|
open = false;
|
||||||
@@ -62,13 +64,13 @@
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label for="credentials-current-password" class="mb-1 block text-sm font-medium">Current password</label>
|
<label for="credentials-email" class="mb-1 block text-sm font-medium">Email</label>
|
||||||
<input
|
<input
|
||||||
id="credentials-current-password"
|
id="credentials-email"
|
||||||
type="password"
|
type="email"
|
||||||
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
bind:value={currentPassword}
|
bind:value={email}
|
||||||
autocomplete="current-password"
|
autocomplete="email"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -81,7 +83,7 @@
|
|||||||
bind:value={newPassword}
|
bind:value={newPassword}
|
||||||
autocomplete="new-password"
|
autocomplete="new-password"
|
||||||
minlength={8}
|
minlength={8}
|
||||||
placeholder="Leave blank to keep current password"
|
placeholder="Leave blank to keep your password"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -13,10 +13,10 @@ export function createAuthStore() {
|
|||||||
queryFn: fetchAuthStatus,
|
queryFn: fetchAuthStatus,
|
||||||
}));
|
}));
|
||||||
const setupMutation = createMutation(() => ({
|
const setupMutation = createMutation(() => ({
|
||||||
mutationFn: ({ username, password }) => setupAccount(username, password),
|
mutationFn: ({ username, email, password }) => setupAccount(username, email, password),
|
||||||
}));
|
}));
|
||||||
const loginMutation = createMutation(() => ({
|
const loginMutation = createMutation(() => ({
|
||||||
mutationFn: ({ username, password }) => login(username, password),
|
mutationFn: ({ identifier, password }) => login(identifier, password),
|
||||||
}));
|
}));
|
||||||
const logoutMutation = createMutation(() => ({
|
const logoutMutation = createMutation(() => ({
|
||||||
mutationFn: () => logout(),
|
mutationFn: () => logout(),
|
||||||
@@ -37,12 +37,12 @@ export function createAuthStore() {
|
|||||||
get error() {
|
get error() {
|
||||||
return statusQuery.error;
|
return statusQuery.error;
|
||||||
},
|
},
|
||||||
async setup(username, password) {
|
async setup(username, email, password) {
|
||||||
await setupMutation.mutateAsync({ username, password });
|
await setupMutation.mutateAsync({ username, email, password });
|
||||||
await refresh();
|
await refresh();
|
||||||
},
|
},
|
||||||
async login(username, password) {
|
async login(identifier, password) {
|
||||||
await loginMutation.mutateAsync({ username, password });
|
await loginMutation.mutateAsync({ identifier, password });
|
||||||
await refresh();
|
await refresh();
|
||||||
},
|
},
|
||||||
async logout() {
|
async logout() {
|
||||||
|
|||||||
@@ -2,9 +2,13 @@
|
|||||||
import { Moon, Sun, SunMoon } from '@lucide/svelte';
|
import { Moon, Sun, SunMoon } from '@lucide/svelte';
|
||||||
import Button from '$lib/components/ui/button.svelte';
|
import Button from '$lib/components/ui/button.svelte';
|
||||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
|
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '$lib/components/ui/dialog';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '$lib/components/ui/select';
|
||||||
|
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte.js';
|
||||||
import { themeState } from '$lib/theme.svelte.js';
|
import { themeState } from '$lib/theme.svelte.js';
|
||||||
|
|
||||||
let { open = $bindable(false) } = $props();
|
let { open = $bindable(false) } = $props();
|
||||||
|
|
||||||
|
const languageItems = languages.map((language) => ({ value: language.id, label: language.label }));
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Dialog bind:open>
|
<Dialog bind:open>
|
||||||
@@ -47,6 +51,24 @@
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="mt-5">
|
||||||
|
<label for="settings-language" class="mb-2 block text-sm font-medium">Language</label>
|
||||||
|
<Select
|
||||||
|
type="single"
|
||||||
|
value={currentLanguage()}
|
||||||
|
items={languageItems}
|
||||||
|
onValueChange={(value) => setLanguage(value)}
|
||||||
|
>
|
||||||
|
<SelectTrigger id="settings-language" class="w-full">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{#each languageItems as item (item.value)}
|
||||||
|
<SelectItem value={item.value} label={item.label}>{item.label}</SelectItem>
|
||||||
|
{/each}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
|
<Button type="button" variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { browser } from '$app/environment';
|
||||||
|
|
||||||
|
export const languages = [
|
||||||
|
{ id: 'ar', label: 'العربية' },
|
||||||
|
{ id: 'ca', label: 'Català' },
|
||||||
|
{ id: 'de', label: 'Deutsch' },
|
||||||
|
{ id: 'en', label: 'English' },
|
||||||
|
{ id: 'es', label: 'Español' },
|
||||||
|
{ id: 'fr', label: 'Français' },
|
||||||
|
{ id: 'hi', label: 'हिन्दी' },
|
||||||
|
{ id: 'it', label: 'Italiano' },
|
||||||
|
{ id: 'ja', label: '日本語' },
|
||||||
|
{ id: 'nl', label: 'Nederlands' },
|
||||||
|
{ id: 'pt', label: 'Português' },
|
||||||
|
{ id: 'ru', label: 'Русский' },
|
||||||
|
{ id: 'tr', label: 'Türkçe' },
|
||||||
|
{ id: 'uk', label: 'Українська' },
|
||||||
|
{ id: 'zh', label: '中文' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const defaultLanguage = 'en';
|
||||||
|
const storageKey = 'collabtable-language';
|
||||||
|
const supportedIds = new Set(languages.map((language) => language.id));
|
||||||
|
const rtlLanguages = new Set(['ar']);
|
||||||
|
|
||||||
|
/** @param {string | null | undefined} value @returns {value is string} */
|
||||||
|
function isLanguage(value) {
|
||||||
|
return Boolean(value && supportedIds.has(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function getInitialLanguage() {
|
||||||
|
if (!browser) return defaultLanguage;
|
||||||
|
|
||||||
|
const stored = localStorage.getItem(storageKey);
|
||||||
|
if (isLanguage(stored)) return stored;
|
||||||
|
|
||||||
|
const automatic = navigator.language?.split('-')[0];
|
||||||
|
return isLanguage(automatic) ? automatic : defaultLanguage;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} language */
|
||||||
|
function applyLanguage(language) {
|
||||||
|
document.documentElement.lang = language;
|
||||||
|
document.documentElement.dir = rtlLanguages.has(language) ? 'rtl' : 'ltr';
|
||||||
|
}
|
||||||
|
|
||||||
|
let selectedLanguage = $state(getInitialLanguage());
|
||||||
|
|
||||||
|
export function currentLanguage() {
|
||||||
|
return selectedLanguage;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} language */
|
||||||
|
export function setLanguage(language) {
|
||||||
|
if (!isLanguage(language)) return;
|
||||||
|
|
||||||
|
selectedLanguage = language;
|
||||||
|
if (browser) {
|
||||||
|
localStorage.setItem(storageKey, language);
|
||||||
|
applyLanguage(language);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (browser) applyLanguage(currentLanguage());
|
||||||
Reference in new issue
Block a user