diff --git a/README.md b/README.md index 1c45b13..f66155a 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr ## What works today -- **Accounts.** The first user to register becomes the admin and registration then closes; admins create the other users. Short-lived access tokens (JWT) plus rotating refresh tokens, so a stolen refresh token is detected. +- **Accounts.** An account is an email address and a password. The first user to register becomes the admin and registration then closes; admins create the other users. The address only identifies the account: Sonda sends no mail, does not check that the address exists, and keeps it on your server. It is trimmed and lowercased, and unique. Accounts made before addresses were asked for keep the plain name they had as their login. Short-lived access tokens (JWT) plus rotating refresh tokens, so a stolen refresh token is detected. - **Libraries.** A library is a name and a folder, managed through the API. Sonda only ever reads your music folders: it never writes, renames or deletes a file. - **Scanner.** Reads MP3 and FLAC tags and audio properties with several workers in parallel. Rescans are incremental, renamed files keep their identity, vanished files are flagged (never deleted), and a library whose folder looks empty or unreadable (an unmounted NAS) is left alone instead of being wiped. Audio in other formats (m4a, ogg, opus, wav, wma and similar) is not read yet, but it is counted as `unsupported` in the scan result instead of disappearing silently. NAS housekeeping folders (`@Recycle`, `#recycle`, `@eaDir`, `.@__thumb`, `$RECYCLE.BIN`) are skipped. - **Catalog.** Browse and search artists, albums and tracks, with paging, by library, artist or album. Only tracks you can actually play are listed. @@ -134,9 +134,9 @@ BASE=http://127.0.0.1:8080/api/v1 curl -s $BASE/health # The first user becomes the admin; registration is then closed. -curl -s -X POST $BASE/auth/register -d '{"username":"alice","password":"correct horse battery"}' +curl -s -X POST $BASE/auth/register -d '{"email":"alice@example.org","password":"correct horse battery"}' -LOGIN=$(curl -s -X POST $BASE/auth/login -d '{"username":"alice","password":"correct horse battery"}') +LOGIN=$(curl -s -X POST $BASE/auth/login -d '{"email":"alice@example.org","password":"correct horse battery"}') TOKEN=$(echo "$LOGIN" | jq -r .access_token) REFRESH=$(echo "$LOGIN" | jq -r .refresh_token) AUTH="Authorization: Bearer $TOKEN" @@ -204,9 +204,9 @@ Each refresh token works once. Presenting a spent one again, more than ten secon **9. Add another user** (admins only): ```bash -TOKEN=$(curl -s -X POST $BASE/auth/login -d '{"username":"alice","password":"correct horse battery"}' | jq -r .access_token) +TOKEN=$(curl -s -X POST $BASE/auth/login -d '{"email":"alice@example.org","password":"correct horse battery"}' | jq -r .access_token) AUTH="Authorization: Bearer $TOKEN" -curl -s -X POST $BASE/users -H "$AUTH" -d '{"username":"bob","password":"another long password"}' | jq +curl -s -X POST $BASE/users -H "$AUTH" -d '{"email":"bob@example.org","password":"another long password"}' | jq ``` ## External providers diff --git a/internal/api/http/api_test.go b/internal/api/http/api_test.go index 0bd2bf4..82a9eb2 100644 --- a/internal/api/http/api_test.go +++ b/internal/api/http/api_test.go @@ -189,7 +189,7 @@ func errCode(r resp) string { // registerAndLogin creates the first user and returns a valid token. func registerAndLogin(t *testing.T, h http.Handler) string { t.Helper() - creds := map[string]string{"username": "alice", "password": "longenough"} + creds := map[string]string{"email": "alice@example.org", "password": "longenough"} if r := do(t, h, "POST", "/api/v1/auth/register", "", creds); r.Code != http.StatusCreated { t.Fatalf("register: %d %v", r.Code, r.Body) } @@ -215,7 +215,7 @@ func TestRegisterThenClosed(t *testing.T) { h := newTestAPI(t) registerAndLogin(t, h) - r := do(t, h, "POST", "/api/v1/auth/register", "", map[string]string{"username": "bob", "password": "longenough"}) + r := do(t, h, "POST", "/api/v1/auth/register", "", map[string]string{"email": "bob@example.org", "password": "longenough"}) if r.Code != http.StatusForbidden || errCode(r) != "registration_closed" { t.Fatalf("second register: %d %v", r.Code, r.Body) } @@ -224,8 +224,8 @@ func TestRegisterThenClosed(t *testing.T) { func TestRegisterInvalid(t *testing.T) { h := newTestAPI(t) for name, body := range map[string]any{ - "short password": map[string]string{"username": "alice", "password": "x"}, - "bad username": map[string]string{"username": "a", "password": "longenough"}, + "short password": map[string]string{"email": "alice@example.org", "password": "x"}, + "bad email": map[string]string{"email": "a", "password": "longenough"}, "malformed json": "{not json", } { r := do(t, h, "POST", "/api/v1/auth/register", "", body) @@ -238,7 +238,7 @@ func TestRegisterInvalid(t *testing.T) { func TestLoginWrongPassword(t *testing.T) { h := newTestAPI(t) registerAndLogin(t, h) - r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": "alice", "password": "nopenopenope"}) + r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"email": "alice@example.org", "password": "nopenopenope"}) if r.Code != http.StatusUnauthorized || errCode(r) != "invalid_credentials" { t.Fatalf("login: %d %v", r.Code, r.Body) } @@ -256,7 +256,7 @@ func TestListenRequiresAuth(t *testing.T) { } // A token signed with another secret is rejected. - other, _, _ := auth.NewTokenIssuer("ffffffffffffffffffffffffffffffff", time.Hour).Issue(auth.User{ID: 1, Username: "alice"}) + other, _, _ := auth.NewTokenIssuer("ffffffffffffffffffffffffffffffff", time.Hour).Issue(auth.User{ID: 1, Email: "alice"}) if r := do(t, h, "POST", "/api/v1/listens", other, body); r.Code != http.StatusUnauthorized { t.Errorf("foreign token: %d", r.Code) } @@ -305,7 +305,7 @@ func TestListenFlow(t *testing.T) { func TestBodyTooLarge(t *testing.T) { h := newTestAPI(t) - huge := `{"username":"` + strings.Repeat("a", 200_000) + `","password":"longenough"}` + huge := `{"email":"` + strings.Repeat("a", 200_000) + `","password":"longenough"}` r := do(t, h, "POST", "/api/v1/auth/register", "", huge) if r.Code != http.StatusBadRequest && r.Code != http.StatusRequestEntityTooLarge { t.Fatalf("huge body: %d", r.Code) diff --git a/internal/api/http/auth_test.go b/internal/api/http/auth_test.go index 3d4e537..2d6db3b 100644 --- a/internal/api/http/auth_test.go +++ b/internal/api/http/auth_test.go @@ -4,6 +4,7 @@ import ( "net/http" "net/http/httptest" "strconv" + "strings" "testing" ) @@ -20,7 +21,7 @@ func sub(m map[string]any, key string) map[string]any { // loginSession logs in and returns the whole session body. func loginSession(t *testing.T, h http.Handler, user, pass string) map[string]any { t.Helper() - r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": user, "password": pass}) + r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"email": address(user), "password": pass}) if r.Code != http.StatusOK { t.Fatalf("login %s: %d %v", user, r.Code, r.Body) } @@ -31,7 +32,7 @@ func loginSession(t *testing.T, h http.Handler, user, pass string) map[string]an func addUser(t *testing.T, h http.Handler, adminTok, name string, admin bool) (id float64, token string) { t.Helper() r := do(t, h, "POST", "/api/v1/users", adminTok, - map[string]any{"username": name, "password": "longenough", "is_admin": admin}) + map[string]any{"email": address(name), "password": "longenough", "is_admin": admin}) if r.Code != http.StatusCreated { t.Fatalf("create %s: %d %v", name, r.Code, r.Body) } @@ -56,7 +57,7 @@ func TestLoginReturnsSessionWithRoles(t *testing.T) { } } u := sub(s, "user") - if u["username"] != "alice" || u["is_admin"] != true { + if u["email"] != "alice@example.org" || u["is_admin"] != true { t.Errorf("user = %v, want alice as admin", u) } } @@ -69,7 +70,7 @@ func TestMe(t *testing.T) { t.Errorf("no token: %d", r.Code) } r := do(t, h, "GET", "/api/v1/auth/me", tok, nil) - if r.Code != http.StatusOK || r.Body["username"] != "alice" || r.Body["is_admin"] != true { + if r.Code != http.StatusOK || r.Body["email"] != "alice@example.org" || r.Body["is_admin"] != true { t.Fatalf("me: %d %v", r.Code, r.Body) } if _, leaked := r.Body["password_hash"]; leaked { @@ -182,7 +183,7 @@ func TestChangePassword(t *testing.T) { t.Fatalf("change: %d %v", r.Code, r.Body) } - if r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": "alice", "password": "longenough"}); r.Code != http.StatusUnauthorized { + if r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"email": "alice@example.org", "password": "longenough"}); r.Code != http.StatusUnauthorized { t.Errorf("old password still works: %d", r.Code) } loginSession(t, h, "alice", "brandnewpass") @@ -210,7 +211,7 @@ func TestAdminEndpointsRejectNonAdmins(t *testing.T) { if r := do(t, h, c.method, c.path, "", nil); r.Code != http.StatusUnauthorized { t.Errorf("%s %s without token: %d", c.method, c.path, r.Code) } - r := do(t, h, c.method, c.path, bob, map[string]any{"username": "x", "password": "longenough", "is_admin": true}) + r := do(t, h, c.method, c.path, bob, map[string]any{"email": "x", "password": "longenough", "is_admin": true}) if r.Code != http.StatusForbidden || errCode(r) != "admin_required" { t.Errorf("%s %s as non-admin: %d %v", c.method, c.path, r.Code, r.Body) } @@ -238,10 +239,10 @@ func TestAdminUserLifecycle(t *testing.T) { } } - if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"username": "BOB", "password": "longenough"}); r.Code != http.StatusConflict || errCode(r) != "username_taken" { + if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"email": "BOB@example.org", "password": "longenough"}); r.Code != http.StatusConflict || errCode(r) != "email_taken" { t.Errorf("duplicate: %d %v", r.Code, r.Body) } - if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"username": "x", "password": "longenough"}); r.Code != http.StatusBadRequest { + if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"email": "x", "password": "longenough"}); r.Code != http.StatusBadRequest { t.Errorf("invalid: %d", r.Code) } @@ -389,3 +390,11 @@ func TestListenWithADeletedAccountsTokenIsUnauthorized(t *testing.T) { } } } + +// address makes an email of a short test name: "bob" is "bob@example.org". +func address(name string) string { + if strings.Contains(name, "@") { + return name + } + return name + "@example.org" +} diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go index 95008e8..90bd447 100644 --- a/internal/api/http/contract_test.go +++ b/internal/api/http/contract_test.go @@ -299,12 +299,12 @@ func TestResponsesMatchTheSpec(t *testing.T) { c.expect(c.call("GET", "/openapi.yaml", "", nil), 200, "openapi.yaml") // ---- auth ---- - creds := map[string]string{"username": "alice", "password": "correct horse"} - c.expect(c.call("POST", "/auth/register", "", map[string]string{"username": "x", "password": "short"}), 400, "register invalid", "invalid_input") + creds := map[string]string{"email": "alice@example.org", "password": "correct horse"} + c.expect(c.call("POST", "/auth/register", "", map[string]string{"email": "x", "password": "short"}), 400, "register invalid", "invalid_input") c.expect(c.call("POST", "/auth/register", "", creds), 201, "register") - c.expect(c.call("POST", "/auth/register", "", map[string]string{"username": "eve", "password": "correct horse"}), 403, "register closed", "registration_closed") + c.expect(c.call("POST", "/auth/register", "", map[string]string{"email": "eve@example.org", "password": "correct horse"}), 403, "register closed", "registration_closed") - c.expect(c.call("POST", "/auth/login", "", map[string]string{"username": "alice", "password": "wrong password"}), 401, "login wrong", "invalid_credentials") + c.expect(c.call("POST", "/auth/login", "", map[string]string{"email": "alice@example.org", "password": "wrong password"}), 401, "login wrong", "invalid_credentials") c.expect(c.call("POST", "/auth/login", "", "not an object"), 400, "login with a bad body", "invalid_input") session := c.expect(c.call("POST", "/auth/login", "", creds), 200, "login") token := session["access_token"].(string) @@ -327,10 +327,10 @@ func TestResponsesMatchTheSpec(t *testing.T) { token = c.expect(c.call("POST", "/auth/login", "", creds), 200, "login again")["access_token"].(string) // ---- users ---- - bob := c.expect(c.call("POST", "/users", token, map[string]any{"username": "bob", "password": "bobs long pass"}), 201, "create user") - c.expect(c.call("POST", "/users", token, map[string]any{"username": "BOB", "password": "bobs long pass"}), 409, "create duplicate", "username_taken") - c.expect(c.call("POST", "/users", token, map[string]any{"username": "x", "password": "bobs long pass"}), 400, "create invalid", "invalid_input") - bobToken := c.expect(c.call("POST", "/auth/login", "", map[string]string{"username": "bob", "password": "bobs long pass"}), 200, "bob logs in")["access_token"].(string) + bob := c.expect(c.call("POST", "/users", token, map[string]any{"email": "bob@example.org", "password": "bobs long pass"}), 201, "create user") + c.expect(c.call("POST", "/users", token, map[string]any{"email": "BOB@example.org", "password": "bobs long pass"}), 409, "create duplicate", "email_taken") + c.expect(c.call("POST", "/users", token, map[string]any{"email": "x", "password": "bobs long pass"}), 400, "create invalid", "invalid_input") + bobToken := c.expect(c.call("POST", "/auth/login", "", map[string]string{"email": "bob@example.org", "password": "bobs long pass"}), 200, "bob logs in")["access_token"].(string) c.expect(c.call("GET", "/users", bobToken, nil), 403, "users as non-admin", "admin_required") c.expect(c.call("GET", "/providers", bobToken, nil), 403, "providers as non-admin", "admin_required") c.expect(c.call("GET", "/users", token, nil), 200, "list users") diff --git a/internal/api/http/discover_test.go b/internal/api/http/discover_test.go index 39f7602..c4f4f9b 100644 --- a/internal/api/http/discover_test.go +++ b/internal/api/http/discover_test.go @@ -188,7 +188,7 @@ func TestTheSettingBelongsToEachUser(t *testing.T) { e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1") e.allowListening(t) // alice allows it - body := map[string]any{"username": "bob", "password": "longenough"} + body := map[string]any{"email": "bob@example.org", "password": "longenough"} if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated { t.Fatalf("create bob: %d %v", r.Code, r.Body) } diff --git a/internal/api/http/feedback_test.go b/internal/api/http/feedback_test.go index f3f7322..b9f6dfb 100644 --- a/internal/api/http/feedback_test.go +++ b/internal/api/http/feedback_test.go @@ -21,7 +21,7 @@ func (e *discoverEnv) gamma(t *testing.T) int64 { func (e *discoverEnv) bob(t *testing.T) string { t.Helper() - body := map[string]any{"username": "bob", "password": "longenough"} + body := map[string]any{"email": "bob@example.org", "password": "longenough"} if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated { t.Fatalf("create bob: %d %v", r.Code, r.Body) } diff --git a/internal/api/http/handlers_auth.go b/internal/api/http/handlers_auth.go index 874f0f3..e045005 100644 --- a/internal/api/http/handlers_auth.go +++ b/internal/api/http/handlers_auth.go @@ -13,18 +13,18 @@ import ( type authHandlers struct{ svc authService } type credentials struct { - Username string `json:"username"` + Email string `json:"email"` Password string `json:"password"` } type userJSON struct { - ID int64 `json:"id"` - Username string `json:"username"` - IsAdmin bool `json:"is_admin"` + ID int64 `json:"id"` + Email string `json:"email"` + IsAdmin bool `json:"is_admin"` } func toUserJSON(u auth.User) userJSON { - return userJSON{ID: u.ID, Username: u.Username, IsAdmin: u.IsAdmin} + return userJSON{ID: u.ID, Email: u.Email, IsAdmin: u.IsAdmin} } func sessionJSON(s auth.Session) gin.H { @@ -53,8 +53,8 @@ func writeAuthError(c *gin.Context, err error) { writeError(c, http.StatusBadRequest, "invalid_input", err.Error()) case errors.Is(err, auth.ErrRegistrationClosed): writeError(c, http.StatusForbidden, "registration_closed", err.Error()) - case errors.Is(err, auth.ErrUsernameTaken): - writeError(c, http.StatusConflict, "username_taken", err.Error()) + case errors.Is(err, auth.ErrEmailTaken): + writeError(c, http.StatusConflict, "email_taken", err.Error()) case errors.Is(err, auth.ErrUserNotFound): writeError(c, http.StatusNotFound, "user_not_found", err.Error()) case errors.Is(err, auth.ErrLastAdmin): @@ -75,7 +75,7 @@ func (h *authHandlers) register(c *gin.Context) { if !bindJSON(c, &req) { return } - user, err := h.svc.Register(c.Request.Context(), req.Username, req.Password) + user, err := h.svc.Register(c.Request.Context(), req.Email, req.Password) if err != nil { writeAuthError(c, err) return @@ -88,7 +88,7 @@ func (h *authHandlers) login(c *gin.Context) { if !bindJSON(c, &req) { return } - sess, err := h.svc.Login(c.Request.Context(), req.Username, req.Password) + sess, err := h.svc.Login(c.Request.Context(), req.Email, req.Password) if err != nil { writeAuthError(c, err) return diff --git a/internal/api/http/handlers_users.go b/internal/api/http/handlers_users.go index 532df9a..4b8bd06 100644 --- a/internal/api/http/handlers_users.go +++ b/internal/api/http/handlers_users.go @@ -24,7 +24,7 @@ func (h *usersHandlers) list(c *gin.Context) { } type createUserRequest struct { - Username string `json:"username"` + Email string `json:"email"` Password string `json:"password"` IsAdmin bool `json:"is_admin"` } @@ -34,7 +34,7 @@ func (h *usersHandlers) create(c *gin.Context) { if !bindJSON(c, &req) { return } - user, err := h.svc.CreateUser(c.Request.Context(), req.Username, req.Password, req.IsAdmin) + user, err := h.svc.CreateUser(c.Request.Context(), req.Email, req.Password, req.IsAdmin) if err != nil { writeAuthError(c, err) return diff --git a/internal/api/http/jobs_test.go b/internal/api/http/jobs_test.go index 956781a..267181f 100644 --- a/internal/api/http/jobs_test.go +++ b/internal/api/http/jobs_test.go @@ -60,7 +60,7 @@ func newJobAPI(t *testing.T, jc jobCase) (http.Handler, *fakeJob, string, string h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { jc.set(d, fake) }) admin := registerAndLogin(t, h) // A second user who is not an admin. - cred := map[string]any{"username": "bob", "password": "longenough"} + cred := map[string]any{"email": "bob@example.org", "password": "longenough"} if r := do(t, h, "POST", "/api/v1/users", admin, cred); r.Code != http.StatusCreated { t.Fatalf("create bob: %d %v", r.Code, r.Body) } diff --git a/internal/api/http/middleware.go b/internal/api/http/middleware.go index 4b8e674..a728384 100644 --- a/internal/api/http/middleware.go +++ b/internal/api/http/middleware.go @@ -14,9 +14,9 @@ import ( ) const ( - ctxUserID = "user_id" - ctxUsername = "username" - ctxAccount = "account" // the auth.User that requireAuth already looked up + ctxUserID = "user_id" + ctxEmail = "email" + ctxAccount = "account" // the auth.User that requireAuth already looked up ) // limitBody caps the request body size. @@ -150,13 +150,13 @@ func requireAuth(tokens tokenParser, users userLookup, allowQuery bool) gin.Hand _ = c.Error(err) writeError(c, http.StatusInternalServerError, "internal", "internal error") return - case user.Username != claims.Username || user.CreatedAt.Unix() > claims.IssuedAt.Unix(): + case user.Email != claims.Email || user.CreatedAt.Unix() > claims.IssuedAt.Unix(): writeError(c, http.StatusUnauthorized, "unauthorized", "invalid or expired token") return } c.Set(ctxUserID, claims.UserID) c.Set(ctxAccount, user) - c.Set(ctxUsername, claims.Username) + c.Set(ctxEmail, claims.Email) c.Next() } } diff --git a/internal/api/http/middleware_test.go b/internal/api/http/middleware_test.go index f98a1eb..5dbf107 100644 --- a/internal/api/http/middleware_test.go +++ b/internal/api/http/middleware_test.go @@ -30,17 +30,17 @@ func (f fakeUsers) User(context.Context, int64) (auth.User, error) { return f.us func TestRequireAuthChecksWhoTheTokenWasIssuedFor(t *testing.T) { issued := time.Unix(1_700_000_000, 0) - token := auth.Claims{UserID: 5, Username: "bob", IssuedAt: issued} + token := auth.Claims{UserID: 5, Email: "bob", IssuedAt: issued} for _, tt := range []struct { name string users fakeUsers want int }{ - {"the same account", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued.Add(-time.Hour)}}, http.StatusOK}, - {"created in the same second as the token", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued}}, http.StatusOK}, + {"the same account", fakeUsers{user: auth.User{ID: 5, Email: "bob", CreatedAt: issued.Add(-time.Hour)}}, http.StatusOK}, + {"created in the same second as the token", fakeUsers{user: auth.User{ID: 5, Email: "bob", CreatedAt: issued}}, http.StatusOK}, {"the account is gone", fakeUsers{err: auth.ErrUserNotFound}, http.StatusUnauthorized}, - {"the id now belongs to somebody else", fakeUsers{user: auth.User{ID: 5, Username: "carol", CreatedAt: issued.Add(-time.Hour)}}, http.StatusUnauthorized}, - {"the id was reused for the same name, later", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued.Add(time.Minute)}}, http.StatusUnauthorized}, + {"the id now belongs to somebody else", fakeUsers{user: auth.User{ID: 5, Email: "carol", CreatedAt: issued.Add(-time.Hour)}}, http.StatusUnauthorized}, + {"the id was reused for the same name, later", fakeUsers{user: auth.User{ID: 5, Email: "bob", CreatedAt: issued.Add(time.Minute)}}, http.StatusUnauthorized}, {"the database fails", fakeUsers{err: errors.New("boom")}, http.StatusInternalServerError}, } { r := gin.New() @@ -66,7 +66,7 @@ func TestRequireAuthDoesNotCallAClientThatLeftAnInternalError(t *testing.T) { r := gin.New() var logged int r.Use(func(c *gin.Context) { c.Next(); logged = len(c.Errors) }) - r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Username: "bob"}}, fakeUsers{err: context.Canceled}, false), func(c *gin.Context) { + r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Email: "bob"}}, fakeUsers{err: context.Canceled}, false), func(c *gin.Context) { t.Error("the handler ran for a client that left") }) req := httptest.NewRequest("GET", "/x", nil).WithContext(ctx) @@ -80,9 +80,9 @@ func TestRequireAuthDoesNotCallAClientThatLeftAnInternalError(t *testing.T) { func TestAdminCheckReusesTheAccountAlreadyLookedUp(t *testing.T) { calls := 0 - users := countingUsers{user: auth.User{ID: 5, Username: "root", IsAdmin: true}, calls: &calls} + users := countingUsers{user: auth.User{ID: 5, Email: "root", IsAdmin: true}, calls: &calls} r := gin.New() - r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Username: "root", IssuedAt: time.Now()}}, users, false), + r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Email: "root", IssuedAt: time.Now()}}, users, false), requireAdmin(users), func(c *gin.Context) { c.Status(http.StatusOK) }) req := httptest.NewRequest("GET", "/x", nil) req.Header.Set("Authorization", "Bearer anything") @@ -123,7 +123,7 @@ func TestATokenOfADeletedUserDoesNotWorkAsWhoeverGetsTheSameId(t *testing.T) { h := newTestAPI(t) admin := registerAndLogin(t, h) create := func(name string) (id int64, token string) { - cred := map[string]any{"username": name, "password": "longenough"} + cred := map[string]any{"email": address(name), "password": "longenough"} r := do(t, h, "POST", "/api/v1/users", admin, cred) if r.Code != http.StatusCreated { t.Fatalf("create %s: %d %v", name, r.Code, r.Body) diff --git a/internal/api/http/router.go b/internal/api/http/router.go index c9d2228..4659106 100644 --- a/internal/api/http/router.go +++ b/internal/api/http/router.go @@ -32,14 +32,14 @@ import ( const maxBodyBytes = 64 << 10 type authService interface { - Register(ctx context.Context, username, password string) (auth.User, error) - Login(ctx context.Context, username, password string) (auth.Session, error) + Register(ctx context.Context, email, password string) (auth.User, error) + Login(ctx context.Context, email, password string) (auth.Session, error) Refresh(ctx context.Context, refreshToken string) (auth.Session, error) Logout(ctx context.Context, refreshToken string) error User(ctx context.Context, id int64) (auth.User, error) ChangePassword(ctx context.Context, userID int64, current, next string) error ListUsers(ctx context.Context) ([]auth.User, error) - CreateUser(ctx context.Context, username, password string, isAdmin bool) (auth.User, error) + CreateUser(ctx context.Context, email, password string, isAdmin bool) (auth.User, error) SetAdmin(ctx context.Context, id int64, isAdmin bool) (auth.User, error) ResetPassword(ctx context.Context, id int64, password string) error DeleteUser(ctx context.Context, id int64) error diff --git a/internal/api/http/taste_test.go b/internal/api/http/taste_test.go index aac8f5c..eed7c07 100644 --- a/internal/api/http/taste_test.go +++ b/internal/api/http/taste_test.go @@ -105,7 +105,7 @@ func TestTasteIsPrivate(t *testing.T) { e := newTasteEnv(t) e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1") - body := map[string]any{"username": "bob", "password": "longenough"} + body := map[string]any{"email": "bob@example.org", "password": "longenough"} if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated { t.Fatalf("create bob: %d %v", r.Code, r.Body) } diff --git a/internal/api/http/usersettings_test.go b/internal/api/http/usersettings_test.go index 28f7b50..31436fa 100644 --- a/internal/api/http/usersettings_test.go +++ b/internal/api/http/usersettings_test.go @@ -43,7 +43,7 @@ func TestSettingsStartOffAndStayMine(t *testing.T) { } // Another user has their own. - cred := map[string]any{"username": "bob", "password": "longenough"} + cred := map[string]any{"email": "bob@example.org", "password": "longenough"} if c := do(t, h, "POST", "/api/v1/users", alice, cred); c.Code != http.StatusCreated { t.Fatalf("create bob: %d %v", c.Code, c.Body) } @@ -119,7 +119,7 @@ func TestSettingsAcceptOnlyOneExactObject(t *testing.T) { func TestSettingsOfADeletedAccountAreRefused(t *testing.T) { h := newTestAPI(t) admin := registerAndLogin(t, h) - cred := map[string]any{"username": "bob", "password": "longenough"} + cred := map[string]any{"email": "bob@example.org", "password": "longenough"} created := do(t, h, "POST", "/api/v1/users", admin, cred) if created.Code != http.StatusCreated { t.Fatalf("create bob: %d %v", created.Code, created.Body) diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index 588587c..5cd0e43 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -96,7 +96,7 @@ paths: application/json: schema: {$ref: '#/components/schemas/Error'} '409': - description: The username is taken (`username_taken`). + description: The email is already registered (`email_taken`). content: application/json: schema: {$ref: '#/components/schemas/Error'} @@ -119,7 +119,7 @@ paths: schema: {$ref: '#/components/schemas/Session'} '400': {$ref: '#/components/responses/InvalidInput'} '401': - description: Wrong username or password (`invalid_credentials`). + description: Wrong email or password (`invalid_credentials`). content: application/json: schema: {$ref: '#/components/schemas/Error'} @@ -249,7 +249,7 @@ paths: '401': {$ref: '#/components/responses/Unauthorized'} '403': {$ref: '#/components/responses/AdminRequired'} '409': - description: The username is taken (`username_taken`). + description: The email is already registered (`email_taken`). content: application/json: schema: {$ref: '#/components/schemas/Error'} @@ -2124,13 +2124,14 @@ components: Credentials: type: object - required: [username, password] + required: [email, password] properties: - username: + email: type: string - minLength: 3 - maxLength: 64 - pattern: '^[A-Za-z0-9._-]+$' + maxLength: 254 + description: | + An address like `name@example.org`, with no display name. It is trimmed and lowercased, + and it is unique. Sonda sends no mail and does not check that the address exists. password: type: string format: password @@ -2138,9 +2139,13 @@ components: LoginRequest: type: object - required: [username, password] + required: [email, password] properties: - username: {type: string} + email: + type: string + description: | + The address of the account, in any case. An account made before addresses were asked + for logs in with the plain name it has. password: {type: string, format: password} CreateUser: @@ -2153,10 +2158,10 @@ components: User: type: object additionalProperties: false - required: [id, username, is_admin] + required: [id, email, is_admin] properties: id: {type: integer, format: int64} - username: {type: string} + email: {type: string} is_admin: {type: boolean} Session: diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go index 15d8bee..ba2af12 100644 --- a/internal/auth/auth_test.go +++ b/internal/auth/auth_test.go @@ -48,7 +48,7 @@ const testSecret = "0123456789abcdef0123456789abcdef" func TestTokenRoundTrip(t *testing.T) { iss := NewTokenIssuer(testSecret, time.Hour) - tok, exp, err := iss.Issue(User{ID: 7, Username: "bob"}) + tok, exp, err := iss.Issue(User{ID: 7, Email: "bob"}) if err != nil { t.Fatal(err) } @@ -59,7 +59,7 @@ func TestTokenRoundTrip(t *testing.T) { if err != nil { t.Fatal(err) } - if claims.UserID != 7 || claims.Username != "bob" { + if claims.UserID != 7 || claims.Email != "bob" { t.Errorf("claims = %+v", claims) } } @@ -68,7 +68,7 @@ func TestTokenCarriesTheMomentItWasIssued(t *testing.T) { iss := NewTokenIssuer(testSecret, time.Hour) at := time.Date(2026, 5, 6, 7, 8, 9, 500_000_000, time.UTC) iss.now = func() time.Time { return at } - tok, _, err := iss.Issue(User{ID: 7, Username: "bob"}) + tok, _, err := iss.Issue(User{ID: 7, Email: "bob"}) if err != nil { t.Fatal(err) } @@ -84,7 +84,7 @@ func TestTokenCarriesTheMomentItWasIssued(t *testing.T) { func TestTokenExpired(t *testing.T) { iss := NewTokenIssuer(testSecret, time.Hour) iss.now = func() time.Time { return time.Now().Add(-2 * time.Hour) } - tok, _, err := iss.Issue(User{ID: 1, Username: "a"}) + tok, _, err := iss.Issue(User{ID: 1, Email: "a"}) if err != nil { t.Fatal(err) } @@ -95,7 +95,7 @@ func TestTokenExpired(t *testing.T) { } func TestTokenWrongSecret(t *testing.T) { - tok, _, _ := NewTokenIssuer(testSecret, time.Hour).Issue(User{ID: 1, Username: "a"}) + tok, _, _ := NewTokenIssuer(testSecret, time.Hour).Issue(User{ID: 1, Email: "a"}) other := NewTokenIssuer("ffffffffffffffffffffffffffffffff", time.Hour) if _, err := other.Parse(tok); err == nil { t.Fatal("token signed with another secret accepted") diff --git a/internal/auth/service.go b/internal/auth/service.go index 4e780c0..fd9739e 100644 --- a/internal/auth/service.go +++ b/internal/auth/service.go @@ -10,7 +10,8 @@ import ( "encoding/hex" "errors" "fmt" - "regexp" + "net/mail" + "strings" "sync" "time" ) @@ -18,15 +19,16 @@ import ( // Errors returned by the service. Handlers map them to HTTP statuses. var ( ErrInvalidInput = errors.New("invalid input") - ErrUsernameTaken = errors.New("username already taken") + ErrEmailTaken = errors.New("email already registered") ErrUserNotFound = errors.New("user not found") - ErrInvalidCredentials = errors.New("invalid username or password") + ErrInvalidCredentials = errors.New("invalid email or password") ErrRegistrationClosed = errors.New("registration is closed") ErrInvalidRefreshToken = errors.New("invalid refresh token") ErrLastAdmin = errors.New("cannot remove the last admin") ) -var usernameRe = regexp.MustCompile(`^[A-Za-z0-9._-]{3,64}$`) +// maxEmailLen is the longest address there can be (RFC 5321). +const maxEmailLen = 254 const ( minPasswordLen = 8 @@ -41,7 +43,7 @@ const RefreshReuseGrace = 10 * time.Second // User is a local account. The password hash never leaves the store layer. type User struct { ID int64 - Username string + Email string IsAdmin bool CreatedAt time.Time } @@ -57,10 +59,10 @@ type RefreshToken struct { type UserStore interface { CountUsers(ctx context.Context) (int, error) CountAdmins(ctx context.Context) (int, error) - // CreateUser returns ErrUsernameTaken when the name exists (case-insensitive). - CreateUser(ctx context.Context, username, passwordHash string, isAdmin bool) (User, error) - // UserByUsername and UserByID return the password hash too, and ErrUserNotFound. - UserByUsername(ctx context.Context, username string) (User, string, error) + // CreateUser returns ErrEmailTaken when the address exists (case-insensitive). + CreateUser(ctx context.Context, email, passwordHash string, isAdmin bool) (User, error) + // UserByEmail (case-insensitive) and UserByID return the password hash too, and ErrUserNotFound. + UserByEmail(ctx context.Context, email string) (User, string, error) UserByID(ctx context.Context, id int64) (User, string, error) ListUsers(ctx context.Context) ([]User, error) // The three below return ErrUserNotFound for an unknown id. @@ -119,11 +121,16 @@ func NewService(users UserStore, refresh RefreshStore, tokens *TokenIssuer, refr // ---- validation ---- -func validateUsername(username string) error { - if !usernameRe.MatchString(username) { - return fmt.Errorf("%w: username must be 3-64 characters: letters, digits, '.', '_' or '-'", ErrInvalidInput) +// normalizeEmail checks the shape of an address and returns it trimmed and lowercased, which is +// how it is stored and compared. It is only a shape: Sonda sends no mail and does not check that +// the address exists. A display name ("Alice ") is not an address. +func normalizeEmail(email string) (string, error) { + email = strings.ToLower(strings.TrimSpace(email)) + a, err := mail.ParseAddress(email) + if err != nil || a.Address != email || len(email) > maxEmailLen { + return "", fmt.Errorf("%w: email must be an address like name@example.org", ErrInvalidInput) } - return nil + return email, nil } func validatePassword(password string) error { @@ -137,8 +144,9 @@ func validatePassword(password string) error { // Register creates the first user, who becomes the admin. Once any user // exists, registration is closed: admins create further accounts. -func (s *Service) Register(ctx context.Context, username, password string) (User, error) { - if err := validateUsername(username); err != nil { +func (s *Service) Register(ctx context.Context, email, password string) (User, error) { + email, err := normalizeEmail(email) + if err != nil { return User{}, err } if err := validatePassword(password); err != nil { @@ -159,13 +167,16 @@ func (s *Service) Register(ctx context.Context, username, password string) (User if err != nil { return User{}, err } - return s.users.CreateUser(ctx, username, hash, true) + return s.users.CreateUser(ctx, email, hash, true) } // Login checks the credentials and opens a session. // Unknown user and wrong password are indistinguishable to the caller. -func (s *Service) Login(ctx context.Context, username, password string) (Session, error) { - user, hash, err := s.users.UserByUsername(ctx, username) +// +// The address is not checked for its shape: an account made before addresses were asked for +// logs in with the plain name it has. +func (s *Service) Login(ctx context.Context, email, password string) (Session, error) { + user, hash, err := s.users.UserByEmail(ctx, strings.ToLower(strings.TrimSpace(email))) if errors.Is(err, ErrUserNotFound) { // Spend the same time as a real check to avoid revealing which names exist. VerifyPassword(s.fakeHash(), password) @@ -302,8 +313,9 @@ func (s *Service) ListUsers(ctx context.Context) ([]User, error) { } // CreateUser creates an account. Callers must have checked that the actor is an admin. -func (s *Service) CreateUser(ctx context.Context, username, password string, isAdmin bool) (User, error) { - if err := validateUsername(username); err != nil { +func (s *Service) CreateUser(ctx context.Context, email, password string, isAdmin bool) (User, error) { + email, err := normalizeEmail(email) + if err != nil { return User{}, err } if err := validatePassword(password); err != nil { @@ -313,7 +325,7 @@ func (s *Service) CreateUser(ctx context.Context, username, password string, isA if err != nil { return User{}, err } - return s.users.CreateUser(ctx, username, hash, isAdmin) + return s.users.CreateUser(ctx, email, hash, isAdmin) } // SetAdmin grants or removes the admin role. The last admin cannot be demoted. diff --git a/internal/auth/service_test.go b/internal/auth/service_test.go index 7bf6e76..83619be 100644 --- a/internal/auth/service_test.go +++ b/internal/auth/service_test.go @@ -34,9 +34,9 @@ func newFakeStore() *fakeStore { return &fakeStore{users: map[int64]*fakeUserRow{}, tokens: map[string]*fakeRefreshRow{}} } -func (f *fakeStore) find(username string) *fakeUserRow { +func (f *fakeStore) find(email string) *fakeUserRow { for _, r := range f.users { - if strings.EqualFold(r.u.Username, username) { + if strings.EqualFold(r.u.Email, email) { return r } } @@ -55,18 +55,18 @@ func (f *fakeStore) CountAdmins(context.Context) (int, error) { return n, nil } -func (f *fakeStore) CreateUser(_ context.Context, username, hash string, isAdmin bool) (User, error) { - if f.find(username) != nil { - return User{}, ErrUsernameTaken +func (f *fakeStore) CreateUser(_ context.Context, email, hash string, isAdmin bool) (User, error) { + if f.find(email) != nil { + return User{}, ErrEmailTaken } f.nextID++ - u := User{ID: f.nextID, Username: username, IsAdmin: isAdmin, CreatedAt: time.Now()} + u := User{ID: f.nextID, Email: email, IsAdmin: isAdmin, CreatedAt: time.Now()} f.users[u.ID] = &fakeUserRow{u: u, hash: hash} return u, nil } -func (f *fakeStore) UserByUsername(_ context.Context, username string) (User, string, error) { - r := f.find(username) +func (f *fakeStore) UserByEmail(_ context.Context, email string) (User, string, error) { + r := f.find(email) if r == nil { return User{}, "", ErrUserNotFound } @@ -171,7 +171,7 @@ func newTestService() (*Service, *fakeStore) { func bootstrap(t *testing.T) (*Service, *fakeStore, User) { t.Helper() s, st := newTestService() - u, err := s.Register(context.Background(), "alice", "longenough") + u, err := s.Register(context.Background(), "alice@example.org", "longenough") if err != nil { t.Fatal(err) } @@ -185,7 +185,7 @@ func TestRegisterFirstUserIsAdminThenClosed(t *testing.T) { if !u.IsAdmin { t.Error("the first user must be an admin") } - if _, err := s.Register(context.Background(), "bob", "longenough"); !errors.Is(err, ErrRegistrationClosed) { + if _, err := s.Register(context.Background(), "bob@example.org", "longenough"); !errors.Is(err, ErrRegistrationClosed) { t.Fatalf("err = %v, want ErrRegistrationClosed", err) } } @@ -194,11 +194,16 @@ func TestRegisterValidation(t *testing.T) { tests := []struct { name, user, pass string }{ - {"short username", "ab", "longenough"}, - {"long username", strings.Repeat("a", 65), "longenough"}, - {"bad chars", "bad name!", "longenough"}, - {"short password", "alice", "short"}, - {"huge password", "alice", strings.Repeat("x", 300)}, + {"no address", "", "longenough"}, + {"a name, not an address", "alice", "longenough"}, + {"no domain", "alice@", "longenough"}, + {"no name", "@example.org", "longenough"}, + {"two at signs", "a@b@example.org", "longenough"}, + {"a space", "al ice@example.org", "longenough"}, + {"a display name", "Alice ", "longenough"}, + {"too long", strings.Repeat("a", 250) + "@example.org", "longenough"}, + {"short password", "alice@example.org", "short"}, + {"huge password", "alice@example.org", strings.Repeat("x", 300)}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -214,11 +219,11 @@ func TestLoginIssuesBothTokens(t *testing.T) { s, _, _ := bootstrap(t) ctx := context.Background() - sess, err := s.Login(ctx, "ALICE", "longenough") // usernames are case-insensitive + sess, err := s.Login(ctx, "ALICE@Example.org", "longenough") // addresses are case-insensitive if err != nil { t.Fatal(err) } - if sess.AccessToken == "" || sess.RefreshToken == "" || sess.User.Username != "alice" || !sess.User.IsAdmin { + if sess.AccessToken == "" || sess.RefreshToken == "" || sess.User.Email != "alice@example.org" || !sess.User.IsAdmin { t.Fatalf("session = %+v", sess) } if !sess.RefreshExpiresAt.After(sess.AccessExpiresAt) { @@ -228,7 +233,7 @@ func TestLoginIssuesBothTokens(t *testing.T) { t.Errorf("access token does not verify: %v", err) } - if _, err := s.Login(ctx, "alice", "wrongpass1"); !errors.Is(err, ErrInvalidCredentials) { + if _, err := s.Login(ctx, "alice@example.org", "wrongpass1"); !errors.Is(err, ErrInvalidCredentials) { t.Errorf("wrong password: err = %v", err) } if _, err := s.Login(ctx, "nobody", "longenough"); !errors.Is(err, ErrInvalidCredentials) { @@ -238,7 +243,7 @@ func TestLoginIssuesBothTokens(t *testing.T) { func TestRefreshTokenIsStoredHashed(t *testing.T) { s, st, _ := bootstrap(t) - sess, _ := s.Login(context.Background(), "alice", "longenough") + sess, _ := s.Login(context.Background(), "alice@example.org", "longenough") if _, ok := st.tokens[sess.RefreshToken]; ok { t.Fatal("the raw refresh token is stored; only its hash may be") } @@ -252,13 +257,13 @@ func TestRefreshTokenIsStoredHashed(t *testing.T) { func TestRefreshRotates(t *testing.T) { s, _, _ := bootstrap(t) ctx := context.Background() - first, _ := s.Login(ctx, "alice", "longenough") + first, _ := s.Login(ctx, "alice@example.org", "longenough") second, err := s.Refresh(ctx, first.RefreshToken) if err != nil { t.Fatal(err) } - if second.RefreshToken == first.RefreshToken || second.AccessToken == "" || second.User.Username != "alice" { + if second.RefreshToken == first.RefreshToken || second.AccessToken == "" || second.User.Email != "alice@example.org" { t.Fatalf("second = %+v", second) } // The new token works. @@ -270,7 +275,7 @@ func TestRefreshRotates(t *testing.T) { func TestReusedRefreshTokenRevokesEverySession(t *testing.T) { s, _, _ := bootstrap(t) ctx := context.Background() - first, _ := s.Login(ctx, "alice", "longenough") + first, _ := s.Login(ctx, "alice@example.org", "longenough") second, _ := s.Refresh(ctx, first.RefreshToken) // Well after the grace window, presenting the rotated token looks like theft. @@ -289,7 +294,7 @@ func TestReusedRefreshTokenRevokesEverySession(t *testing.T) { func TestReplayInsideTheGraceWindowKeepsTheNewToken(t *testing.T) { s, _, _ := bootstrap(t) ctx := context.Background() - first, _ := s.Login(ctx, "alice", "longenough") + first, _ := s.Login(ctx, "alice@example.org", "longenough") second, err := s.Refresh(ctx, first.RefreshToken) if err != nil { t.Fatal(err) @@ -306,7 +311,7 @@ func TestReplayInsideTheGraceWindowKeepsTheNewToken(t *testing.T) { func TestRefreshRejectsExpiredUnknownAndEmpty(t *testing.T) { s, _, _ := bootstrap(t) ctx := context.Background() - sess, _ := s.Login(ctx, "alice", "longenough") + sess, _ := s.Login(ctx, "alice@example.org", "longenough") for _, tok := range []string{"", "not-a-token", strings.Repeat("a", 43)} { if _, err := s.Refresh(ctx, tok); !errors.Is(err, ErrInvalidRefreshToken) { @@ -323,11 +328,11 @@ func TestRefreshRejectsExpiredUnknownAndEmpty(t *testing.T) { func TestRefreshFailsForDeletedUser(t *testing.T) { s, _, admin := bootstrap(t) ctx := context.Background() - bob, err := s.CreateUser(ctx, "bob", "longenough", false) + bob, err := s.CreateUser(ctx, "bob@example.org", "longenough", false) if err != nil { t.Fatal(err) } - bobSess, _ := s.Login(ctx, "bob", "longenough") + bobSess, _ := s.Login(ctx, "bob@example.org", "longenough") if err := s.DeleteUser(ctx, bob.ID); err != nil { t.Fatal(err) @@ -343,7 +348,7 @@ func TestRefreshFailsForDeletedUser(t *testing.T) { func TestLogoutRevokesTheToken(t *testing.T) { s, _, _ := bootstrap(t) ctx := context.Background() - sess, _ := s.Login(ctx, "alice", "longenough") + sess, _ := s.Login(ctx, "alice@example.org", "longenough") if err := s.Logout(ctx, sess.RefreshToken); err != nil { t.Fatal(err) @@ -363,7 +368,7 @@ func TestLogoutRevokesTheToken(t *testing.T) { func TestChangePassword(t *testing.T) { s, _, u := bootstrap(t) ctx := context.Background() - sess, _ := s.Login(ctx, "alice", "longenough") + sess, _ := s.Login(ctx, "alice@example.org", "longenough") if err := s.ChangePassword(ctx, u.ID, "wrong-current", "brandnewpass"); !errors.Is(err, ErrInvalidCredentials) { t.Fatalf("wrong current: err = %v", err) @@ -375,10 +380,10 @@ func TestChangePassword(t *testing.T) { t.Fatal(err) } - if _, err := s.Login(ctx, "alice", "longenough"); !errors.Is(err, ErrInvalidCredentials) { + if _, err := s.Login(ctx, "alice@example.org", "longenough"); !errors.Is(err, ErrInvalidCredentials) { t.Error("old password still works") } - if _, err := s.Login(ctx, "alice", "brandnewpass"); err != nil { + if _, err := s.Login(ctx, "alice@example.org", "brandnewpass"); err != nil { t.Errorf("new password: %v", err) } if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) { @@ -392,18 +397,18 @@ func TestAdminCreateAndListUsers(t *testing.T) { s, _, _ := bootstrap(t) ctx := context.Background() - bob, err := s.CreateUser(ctx, "bob", "longenough", false) + bob, err := s.CreateUser(ctx, "bob@example.org", "longenough", false) if err != nil || bob.IsAdmin { t.Fatalf("bob = %+v err=%v", bob, err) } - if _, err := s.CreateUser(ctx, "BOB", "longenough", false); !errors.Is(err, ErrUsernameTaken) { + if _, err := s.CreateUser(ctx, "BOB@example.org", "longenough", false); !errors.Is(err, ErrEmailTaken) { t.Errorf("duplicate: err = %v", err) } if _, err := s.CreateUser(ctx, "x", "longenough", false); !errors.Is(err, ErrInvalidInput) { - t.Errorf("bad username: err = %v", err) + t.Errorf("bad email: err = %v", err) } users, err := s.ListUsers(ctx) - if err != nil || len(users) != 2 || users[0].Username != "alice" || users[1].Username != "bob" { + if err != nil || len(users) != 2 || users[0].Email != "alice@example.org" || users[1].Email != "bob@example.org" { t.Fatalf("users = %+v err=%v", users, err) } } @@ -411,7 +416,7 @@ func TestAdminCreateAndListUsers(t *testing.T) { func TestSetAdminAndLastAdminGuard(t *testing.T) { s, _, alice := bootstrap(t) ctx := context.Background() - bob, _ := s.CreateUser(ctx, "bob", "longenough", false) + bob, _ := s.CreateUser(ctx, "bob@example.org", "longenough", false) // The only admin cannot be demoted. if _, err := s.SetAdmin(ctx, alice.ID, false); !errors.Is(err, ErrLastAdmin) { @@ -438,7 +443,7 @@ func TestSetAdminAndLastAdminGuard(t *testing.T) { func TestDeleteUserGuards(t *testing.T) { s, _, alice := bootstrap(t) ctx := context.Background() - bob, _ := s.CreateUser(ctx, "bob", "longenough", false) + bob, _ := s.CreateUser(ctx, "bob@example.org", "longenough", false) if err := s.DeleteUser(ctx, alice.ID); !errors.Is(err, ErrLastAdmin) { t.Fatalf("deleting the last admin: err = %v", err) @@ -454,8 +459,8 @@ func TestDeleteUserGuards(t *testing.T) { func TestResetPasswordRevokesSessions(t *testing.T) { s, _, _ := bootstrap(t) ctx := context.Background() - bob, _ := s.CreateUser(ctx, "bob", "longenough", false) - sess, _ := s.Login(ctx, "bob", "longenough") + bob, _ := s.CreateUser(ctx, "bob@example.org", "longenough", false) + sess, _ := s.Login(ctx, "bob@example.org", "longenough") if err := s.ResetPassword(ctx, bob.ID, "short"); !errors.Is(err, ErrInvalidInput) { t.Fatalf("weak password: err = %v", err) @@ -463,7 +468,7 @@ func TestResetPasswordRevokesSessions(t *testing.T) { if err := s.ResetPassword(ctx, bob.ID, "resetpassword"); err != nil { t.Fatal(err) } - if _, err := s.Login(ctx, "bob", "resetpassword"); err != nil { + if _, err := s.Login(ctx, "bob@example.org", "resetpassword"); err != nil { t.Errorf("login with the reset password: %v", err) } if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) { @@ -477,10 +482,40 @@ func TestResetPasswordRevokesSessions(t *testing.T) { func TestUserLookup(t *testing.T) { s, _, alice := bootstrap(t) u, err := s.User(context.Background(), alice.ID) - if err != nil || u.Username != "alice" || !u.IsAdmin { + if err != nil || u.Email != "alice@example.org" || !u.IsAdmin { t.Fatalf("u = %+v err=%v", u, err) } if _, err := s.User(context.Background(), 999); !errors.Is(err, ErrUserNotFound) { t.Errorf("err = %v", err) } } + +func TestAnAddressIsTrimmedAndLowercased(t *testing.T) { + s, _ := newTestService() + ctx := context.Background() + u, err := s.Register(ctx, " Alice@Example.ORG ", "longenough") + if err != nil || u.Email != "alice@example.org" { + t.Fatalf("user = %+v err = %v", u, err) + } + if _, err := s.Login(ctx, " ALICE@example.org", "longenough"); err != nil { + t.Errorf("login with another spelling: %v", err) + } + if _, err := s.CreateUser(ctx, "alice@EXAMPLE.org", "longenough", false); !errors.Is(err, ErrEmailTaken) { + t.Errorf("same address, other case: err = %v", err) + } +} + +// Accounts made before addresses were asked for have a plain name: it stays their login. +func TestAnOldAccountNameStillLogsIn(t *testing.T) { + s, st := newTestService() + hash, err := HashPassword("longenough") + if err != nil { + t.Fatal(err) + } + if _, err := st.CreateUser(context.Background(), "olduser", hash, true); err != nil { + t.Fatal(err) + } + if _, err := s.Login(context.Background(), "OldUser", "longenough"); err != nil { + t.Errorf("an old name no longer logs in: %v", err) + } +} diff --git a/internal/auth/token.go b/internal/auth/token.go index 62c0eb9..4ae21ab 100644 --- a/internal/auth/token.go +++ b/internal/auth/token.go @@ -12,15 +12,15 @@ const tokenIssuerName = "sonda" // Claims is what a valid access token tells us about the caller. type Claims struct { - UserID int64 - Username string + UserID int64 + Email string // IssuedAt is when the token was signed. An account created after that moment // cannot be the one the token was issued for. IssuedAt time.Time } type tokenClaims struct { - Username string `json:"username"` + Email string `json:"email"` jwt.RegisteredClaims } @@ -40,7 +40,7 @@ func NewTokenIssuer(secret string, ttl time.Duration) *TokenIssuer { func (i *TokenIssuer) Issue(user User) (string, time.Time, error) { now := i.now() exp := now.Add(i.ttl) - claims := tokenClaims{Username: user.Username, + claims := tokenClaims{Email: user.Email, Issuer: tokenIssuerName, Subject: strconv.FormatInt(user.ID, 10), IssuedAt: jwt.NewNumericDate(now), @@ -74,5 +74,5 @@ func (i *TokenIssuer) Parse(token string) (Claims, error) { if tc.IssuedAt != nil { issued = tc.IssuedAt.Time } - return Claims{UserID: id, Username: tc.Username, IssuedAt: issued}, nil + return Claims{UserID: id, Email: tc.Email, IssuedAt: issued}, nil } diff --git a/internal/storage/auth_test.go b/internal/storage/auth_test.go index 86e8171..af57602 100644 --- a/internal/storage/auth_test.go +++ b/internal/storage/auth_test.go @@ -31,12 +31,12 @@ func TestUserRepoRolesAndLookup(t *testing.T) { t.Errorf("CountAdmins = %d, want 1", n) } got, hash, err := repo.UserByID(ctx, bob.ID) - if err != nil || got.Username != "bob" || hash != "h2" || got.IsAdmin { + if err != nil || got.Email != "bob" || hash != "h2" || got.IsAdmin { t.Errorf("UserByID = %+v %q err=%v", got, hash, err) } - byName, _, _ := repo.UserByUsername(ctx, "ALICE") + byName, _, _ := repo.UserByEmail(ctx, "ALICE") if !byName.IsAdmin { - t.Error("UserByUsername lost the admin flag") + t.Error("UserByEmail lost the admin flag") } list, err := repo.ListUsers(ctx) diff --git a/internal/storage/repos_test.go b/internal/storage/repos_test.go index dbcd62a..7e13817 100644 --- a/internal/storage/repos_test.go +++ b/internal/storage/repos_test.go @@ -26,12 +26,12 @@ func TestUserRepo(t *testing.T) { if err != nil { t.Fatal(err) } - if u.ID <= 0 || u.Username != "Alice" || u.CreatedAt.IsZero() { + if u.ID <= 0 || u.Email != "Alice" || u.CreatedAt.IsZero() { t.Errorf("user = %+v", u) } // Lookup is case-insensitive and returns the stored hash. - got, hash, err := repo.UserByUsername(ctx, "alice") + got, hash, err := repo.UserByEmail(ctx, "alice") if err != nil { t.Fatal(err) } @@ -40,11 +40,11 @@ func TestUserRepo(t *testing.T) { } // Same name in another case is a duplicate. - if _, err := repo.CreateUser(ctx, "ALICE", "hash2", false); !errors.Is(err, auth.ErrUsernameTaken) { - t.Errorf("duplicate: err = %v, want ErrUsernameTaken", err) + if _, err := repo.CreateUser(ctx, "ALICE", "hash2", false); !errors.Is(err, auth.ErrEmailTaken) { + t.Errorf("duplicate: err = %v, want ErrEmailTaken", err) } - if _, _, err := repo.UserByUsername(ctx, "nobody"); !errors.Is(err, auth.ErrUserNotFound) { + if _, _, err := repo.UserByEmail(ctx, "nobody"); !errors.Is(err, auth.ErrUserNotFound) { t.Errorf("missing: err = %v, want ErrUserNotFound", err) } diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index 70c3366..56858d2 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) { if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil { t.Fatal(err) } - if applied != 17 { - t.Errorf("applied migrations = %d, want 17", applied) + if applied != 18 { + t.Errorf("applied migrations = %d, want 18", applied) } }) } diff --git a/internal/storage/users.go b/internal/storage/users.go index 256afc9..3dda79b 100644 --- a/internal/storage/users.go +++ b/internal/storage/users.go @@ -21,14 +21,14 @@ type userRow struct { bun.BaseModel `bun:"table:users"` ID int64 `bun:"id,pk,autoincrement"` - Username string `bun:"username,notnull"` + Email string `bun:"email,notnull"` PasswordHash string `bun:"password_hash,notnull"` IsAdmin bool `bun:"is_admin,notnull"` CreatedAt int64 `bun:"created_at,notnull"` } func (r userRow) toUser() auth.User { - return auth.User{ID: r.ID, Username: r.Username, IsAdmin: r.IsAdmin, CreatedAt: time.Unix(r.CreatedAt, 0)} + return auth.User{ID: r.ID, Email: r.Email, IsAdmin: r.IsAdmin, CreatedAt: time.Unix(r.CreatedAt, 0)} } // UserRepo stores users. It implements auth.UserStore. @@ -49,22 +49,22 @@ func (r *UserRepo) CountAdmins(ctx context.Context) (int, error) { return int(n), err } -// CreateUser inserts a user. Usernames are unique case-insensitively. -func (r *UserRepo) CreateUser(ctx context.Context, username, passwordHash string, isAdmin bool) (auth.User, error) { - row := &userRow{Username: username, PasswordHash: passwordHash, IsAdmin: isAdmin, CreatedAt: time.Now().Unix()} +// CreateUser inserts a user. Emails are unique case-insensitively. +func (r *UserRepo) CreateUser(ctx context.Context, email, passwordHash string, isAdmin bool) (auth.User, error) { + row := &userRow{Email: email, PasswordHash: passwordHash, IsAdmin: isAdmin, CreatedAt: time.Now().Unix()} if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil { if isUniqueViolation(err) { - return auth.User{}, auth.ErrUsernameTaken + return auth.User{}, auth.ErrEmailTaken } return auth.User{}, fmt.Errorf("insert user: %w", err) } return row.toUser(), nil } -// UserByUsername finds a user (case-insensitive) and returns their password hash. -func (r *UserRepo) UserByUsername(ctx context.Context, username string) (auth.User, string, error) { +// UserByEmail finds a user (case-insensitive) and returns their password hash. +func (r *UserRepo) UserByEmail(ctx context.Context, email string) (auth.User, string, error) { var row userRow - err := r.db.NewSelect().Model(&row).Where("lower(username) = lower(?)", username).Limit(1).Scan(ctx) + err := r.db.NewSelect().Model(&row).Where("lower(email) = lower(?)", email).Limit(1).Scan(ctx) if errors.Is(err, sql.ErrNoRows) { return auth.User{}, "", auth.ErrUserNotFound } diff --git a/migrations/postgres/0018_users_email.sql b/migrations/postgres/0018_users_email.sql new file mode 100644 index 0000000..1d8b08c --- /dev/null +++ b/migrations/postgres/0018_users_email.sql @@ -0,0 +1,5 @@ +-- An account is identified by an email address. PostgreSQL flavour of sqlite/0018_users_email.sql: +-- the column keeps its values, so an account made before addresses were asked for keeps its name. + +ALTER TABLE users RENAME COLUMN username TO email; +ALTER INDEX users_username_lower RENAME TO users_email_lower; diff --git a/migrations/sqlite/0018_users_email.sql b/migrations/sqlite/0018_users_email.sql new file mode 100644 index 0000000..18ecbf1 --- /dev/null +++ b/migrations/sqlite/0018_users_email.sql @@ -0,0 +1,5 @@ +-- An account is identified by an email address. The column keeps its values: an account made +-- before addresses were asked for keeps the name it has, and logs in with it. Its uniqueness +-- (NOCASE) goes with the column. + +ALTER TABLE users RENAME COLUMN username TO email; diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts index 12ef72d..5fb589f 100644 --- a/web/src/api/client.test.ts +++ b/web/src/api/client.test.ts @@ -61,7 +61,7 @@ test('a 401 with nothing to renew signs out without a retry', async () => { test('a call that does not need a session sends no token and never renews', async () => { const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => apiError(401, 'invalid_credentials') }) - await expect(api.post('/auth/login', { username: 'a', password: 'b' }, { auth: false })).rejects.toMatchObject({ + await expect(api.post('/auth/login', { email: 'a@example.org', password: 'b' }, { auth: false })).rejects.toMatchObject({ code: 'invalid_credentials', }) expect(hooks.getAccessToken).not.toHaveBeenCalled() diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index fceae48..61da045 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -634,6 +634,11 @@ export interface paths { * is still used, so the list can be empty. With every seed's data stored and fresh the status is `ok` * whether Last.fm is on or not. It is `error` when Last.fm failed for some seed (the * rest is still returned) and `ok` otherwise. Show `attribution` where you show the data. + * + * **How many at once.** One Discover at a time for each listener (a second one answers 429 + * `discover_busy`), and at most three at the same time on the server: a request that finds them + * busy waits for its turn (at most 30 seconds, then it answers 429 as well), and leaves without + * doing any work if the client gives up. A request that waits for its turn counts as running. */ get: operations["discover"]; put?: never; @@ -818,6 +823,46 @@ export interface paths { patch: operations["updateMySettings"]; trace?: never; }; + "/artists/{id}/lidarr": { + parameters: { + query?: never; + header?: never; + path: { + id: components["parameters"]["Id"]; + }; + cookie?: never; + }; + /** + * Whether Lidarr has an artist + * @description Asks your own Lidarr, by the artist's MusicBrainz id and never by name, whether it has the artist and + * whether it monitors it. Like the descriptions, whatever stops the answer is a status and not an error: + * `disabled` when the `lidarr` provider is off (nobody is asked), `no_id` when the artist has no MusicBrainz id, + * `not_configured` when Lidarr has no address or key, `error` when it could not be asked now. Only the id and + * the API key go out, to the address an admin set. + */ + get: operations["getArtistInLidarr"]; + put?: never; + /** + * Send an artist to Lidarr + * @description Admin only. Adds the artist to your own Lidarr, which then looks for and downloads the music by itself: + * Sonda downloads nothing, and does this only when an admin asks, for one artist, never by itself. It works + * for any artist that has a MusicBrainz id, also one that Sonda only learned of from a list of similar + * artists, which is the point: asking for music you do not have. It never looks an id up by name. + * + * It uses what an admin set in `PUT /providers/lidarr`: the quality profile, the metadata profile, the root + * folder, which of the albums to monitor and whether Lidarr starts searching at once. It needs the provider + * switched on and those chosen. An artist that Lidarr already has is not an error (`already_added`, nothing + * changes), so the call can be repeated. If Lidarr does not answer in time, the artist may have been added + * all the same: read it with `GET /artists/{id}/lidarr`. Only the MusicBrainz id and the API key go out, + * to the address an admin set. + */ + post: operations["sendArtistToLidarr"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/artists/{id}/description": { parameters: { query?: never; @@ -1097,7 +1142,7 @@ export interface paths { }; /** * List the external providers - * @description Admin only. Every provider Sonda knows (Last.fm, MusicBrainz), with whether it is on and + * @description Admin only. Every provider Sonda knows (Last.fm, MusicBrainz, Wikipedia, Commons, the Cover Art Archive and Lidarr), with whether it is on and * what it would send. Providers are off by default: nothing leaves the server until an admin * enables one. The API key is never returned; `has_api_key` says whether one is stored. */ @@ -1110,19 +1155,42 @@ export interface paths { patch?: never; trace?: never; }; + "/providers/lidarr/options": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * What Lidarr offers to choose from + * @description Admin only. Reads Lidarr's quality profiles, metadata profiles and root folders, so an admin can pick + * the ones to send artists with (`PUT /providers/lidarr`, field `lidarr`). It works whether Lidarr is + * switched on or not, since it is needed to finish setting it up, and it sends nothing but the API key, + * to the address set for Lidarr, which is your own server. + */ + get: operations["getLidarrOptions"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/providers/{name}": { parameters: { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; get?: never; /** * Set up a provider - * @description Admin only. Send any of `enabled`, `api_key` and `contact`; fields you leave out are kept. + * @description Admin only. Send any of `enabled`, `api_key`, `contact`, `url` and `lidarr`; fields you leave out are kept. * * The key is write-only: it is never returned and never logged. Sending an empty `api_key` * clears it, and turns a provider that needs a key (Last.fm) off; a provider that needs none @@ -1142,7 +1210,7 @@ export interface paths { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; @@ -1171,7 +1239,7 @@ export interface paths { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; @@ -1251,7 +1319,11 @@ export interface components { }; }; Credentials: { - username: string; + /** + * @description An address like `name@example.org`, with no display name. It is trimmed and lowercased, + * and it is unique. Sonda sends no mail and does not check that the address exists. + */ + email: string; /** * Format: password * @description 8 to 256 bytes (UTF-8). @@ -1259,7 +1331,11 @@ export interface components { password: string; }; LoginRequest: { - username: string; + /** + * @description The address of the account, in any case. An account made before addresses were asked + * for logs in with the plain name it has. + */ + email: string; /** Format: password */ password: string; }; @@ -1270,7 +1346,7 @@ export interface components { User: { /** Format: int64 */ id: number; - username: string; + email: string; is_admin: boolean; }; Session: { @@ -1434,14 +1510,19 @@ export interface components { }; Provider: { /** @enum {string} */ - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; /** @description Whether Sonda may contact this provider. */ enabled: boolean; needs_api_key: boolean; + /** @description Whether the provider is a server of your own that needs an address (only Lidarr). */ + needs_url: boolean; /** @description Whether a key is stored. The key itself is never returned. */ has_api_key: boolean; /** @description Contact in the User-Agent; empty means the project address. */ contact: string; + /** @description Where your own server is, without a closing slash. Empty for the providers that have none. */ + url: string; + lidarr?: components["schemas"]["LidarrOptions"]; /** @description Plain statement of what is sent to the provider, and what never is. */ sends: string; /** @description Terms of use and attribution that apply to the provider's data. */ @@ -1452,16 +1533,74 @@ export interface components { */ updated_at: string | null; }; + /** + * @description Only for `lidarr`: what is sent to Lidarr when an artist is added, chosen once by an admin from + * `GET /providers/lidarr/options`. Until they are saved, `monitor` is `all`, `search_missing` is + * true and the rest is empty or 0, which is not enough to add an artist. + */ + LidarrOptions: { + /** @description Lidarr's quality profile; 0 when none is chosen. */ + quality_profile_id: number; + /** @description Lidarr's metadata profile; 0 when none is chosen. */ + metadata_profile_id: number; + /** @description One of Lidarr's root folders; empty when none is chosen. */ + root_folder_path: string; + /** + * @description Which of the artist's albums Lidarr monitors when it is added. `none` also stops new albums from being monitored. + * @enum {string} + */ + monitor: "all" | "future" | "missing" | "existing" | "latest" | "first" | "none"; + /** @description Whether Lidarr starts looking for the albums as soon as the artist is added. */ + search_missing: boolean; + }; + LidarrOffers: { + quality_profiles: components["schemas"]["LidarrProfile"][]; + metadata_profiles: components["schemas"]["LidarrProfile"][]; + root_folders: { + path: string; + /** @description Whether Lidarr can use the folder now. */ + accessible: boolean; + }[]; + }; + ArtistInLidarr: { + /** + * @description `ok` when Lidarr was asked (and `in_lidarr` is its answer); the others say why it was not. + * @enum {string} + */ + provider_status: "ok" | "disabled" | "no_id" | "not_configured" | "error"; + in_lidarr: boolean; + /** @description Whether Lidarr monitors the artist; false when it does not have it. */ + monitored: boolean; + }; + LidarrProfile: { + id: number; + name: string; + }; ProviderUpdate: { enabled?: boolean; /** * Format: password - * @description A Last.fm key is 32 hexadecimal characters. Empty clears it. + * @description A Last.fm or Lidarr key is 32 hexadecimal characters. Empty clears it. */ api_key?: string; + /** + * @description Only for Lidarr: where your own server is, `http://` or `https://`, with a port and a path if it + * has them, and without user and password, query or fragment. A closing slash is dropped. Empty + * clears it, and turns Lidarr off. Lidarr cannot be enabled without an address and a key. + */ + url?: string; + /** @description Only for Lidarr. Replaces all its options at once: what is left out is the default (`monitor` all, `search_missing` true, the rest empty or 0). */ + lidarr?: { + quality_profile_id?: number; + metadata_profile_id?: number; + root_folder_path?: string; + /** @enum {string} */ + monitor?: "all" | "future" | "missing" | "existing" | "latest" | "first" | "none"; + search_missing?: boolean; + }; /** @description A URL or e-mail address, without parentheses. Empty restores the default. */ contact?: string; - } | unknown | unknown | unknown; + } | unknown | unknown | unknown | unknown | unknown; ArtistDescription: { /** @enum {string} */ provider: "wikipedia"; @@ -1532,11 +1671,11 @@ export interface components { ProviderTest: { ok: boolean; /** - * @description `no_api_key`: none is stored, so nobody was asked. `key_refused`: the provider does not accept + * @description `no_api_key`: none is stored, so nobody was asked. `no_address`: Lidarr has no address yet, so nobody was asked. `key_refused`: the provider does not accept * it. `rate_limited`: try again later. `unreachable`: the provider did not answer. `error`: anything else. * @enum {string} */ - status: "ok" | "no_api_key" | "key_refused" | "rate_limited" | "unreachable" | "error"; + status: "ok" | "no_api_key" | "no_address" | "key_refused" | "rate_limited" | "unreachable" | "error"; }; ArtistTags: { sources: { @@ -1946,7 +2085,7 @@ export interface operations { "application/json": components["schemas"]["Error"]; }; }; - /** @description The username is taken (`username_taken`). */ + /** @description The email is already registered (`email_taken`). */ 409: { headers: { [name: string]: unknown; @@ -1980,7 +2119,7 @@ export interface operations { }; }; 400: components["responses"]["InvalidInput"]; - /** @description Wrong username or password (`invalid_credentials`). */ + /** @description Wrong email or password (`invalid_credentials`). */ 401: { headers: { [name: string]: unknown; @@ -2151,7 +2290,7 @@ export interface operations { 400: components["responses"]["InvalidInput"]; 401: components["responses"]["Unauthorized"]; 403: components["responses"]["AdminRequired"]; - /** @description The username is taken (`username_taken`). */ + /** @description The email is already registered (`email_taken`). */ 409: { headers: { [name: string]: unknown; @@ -2942,6 +3081,17 @@ export interface operations { }; }; 401: components["responses"]["Unauthorized"]; + /** @description You already have a Discover running or waiting for its turn, or the server was too busy to give it one in 30 seconds (`discover_busy`). Ask again after `Retry-After` seconds. */ + 429: { + headers: { + /** @description Seconds to wait before asking again. */ + "Retry-After"?: number; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; }; }; listDismissed: { @@ -3192,6 +3342,106 @@ export interface operations { 401: components["responses"]["Unauthorized"]; }; }; + getArtistInLidarr: { + parameters: { + query?: never; + header?: never; + path: { + id: components["parameters"]["Id"]; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Whether Lidarr has the artist. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ArtistInLidarr"]; + }; + }; + 400: components["responses"]["InvalidInput"]; + 401: components["responses"]["Unauthorized"]; + /** @description No such artist (`artist_not_found`). */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + sendArtistToLidarr: { + parameters: { + query?: never; + header?: never; + path: { + id: components["parameters"]["Id"]; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The artist is in Lidarr. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** + * @description `added` now, or `already_added` when Lidarr had it. + * @enum {string} + */ + status: "added" | "already_added"; + }; + }; + }; + 400: components["responses"]["InvalidInput"]; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["AdminRequired"]; + /** @description No such artist (`artist_not_found`). */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description The provider is switched off (`lidarr_disabled`), or has no address or key, or the profiles and the folder were not chosen (`lidarr_not_configured`). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description The artist has no MusicBrainz id (`no_musicbrainz_id`), Lidarr does not know the id (`lidarr_unknown_artist`), or it refused the artist (`lidarr_rejected`, with its reason). */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Lidarr refused the key (`lidarr_key_refused`), or could not be asked or did not answer in time (`lidarr_unavailable`; the artist may have been added). */ + 502: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; getArtistDescription: { parameters: { query?: never; @@ -3836,12 +4086,52 @@ export interface operations { 403: components["responses"]["AdminRequired"]; }; }; + getLidarrOptions: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description What Lidarr offers. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["LidarrOffers"]; + }; + }; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["AdminRequired"]; + /** @description Lidarr has no address or no API key yet (`lidarr_not_configured`). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Lidarr refused the key (`lidarr_key_refused`), or could not be asked or answered something unexpected (`lidarr_unavailable`). */ + 502: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; updateProvider: { parameters: { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; @@ -3879,7 +4169,7 @@ export interface operations { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; @@ -3913,7 +4203,7 @@ export interface operations { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; diff --git a/web/src/auth/LoginPage.test.tsx b/web/src/auth/LoginPage.test.tsx index 4af1071..2a45ac0 100644 --- a/web/src/auth/LoginPage.test.tsx +++ b/web/src/auth/LoginPage.test.tsx @@ -7,7 +7,7 @@ import AuthGate from './AuthGate' import LoginPage from './LoginPage' import { sessionStore } from './session' -const user = { id: 1, username: 'tom', is_admin: true } +const user = { id: 1, email: 'tom@example.org', is_admin: true } const session = { access_token: 'a1', access_expires_at: new Date(Date.now() + 900_000).toISOString(), @@ -22,33 +22,33 @@ beforeEach(async () => { sessionStore.setState({ status: 'anonymous', user: null, accessToken: null, accessExpiresAt: 0, refreshToken: null }) }) -async function fill(username: string, password: string) { - await userEvent.type(screen.getByLabelText('Username'), username) +async function fill(email: string, password: string) { + await userEvent.type(screen.getByLabelText('Email'), email) await userEvent.type(screen.getByLabelText('Password'), password) } test('a wrong password shows the translated message', async () => { mockFetch({ 'POST /api/v1/auth/login': () => apiError(401, 'invalid_credentials') }) render() - await fill('tom', 'wrong-password') + await fill('tom@example.org', 'wrong-password') await userEvent.click(screen.getByRole('button', { name: 'Sign in' })) - expect(await screen.findByRole('alert')).toHaveTextContent('Wrong username or password.') + expect(await screen.findByRole('alert')).toHaveTextContent('Wrong email or password.') }) test('signing in sends what was typed', async () => { const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session }) render() - await fill('tom', 'secret123') + await fill('tom@example.org', 'secret123') await userEvent.click(screen.getByRole('button', { name: 'Sign in' })) await vi.waitFor(() => expect(sessionStore.getState().status).toBe('authenticated')) - expect(JSON.parse(calls[0].init.body as string)).toEqual({ username: 'tom', password: 'secret123' }) + expect(JSON.parse(calls[0].init.body as string)).toEqual({ email: 'tom@example.org', password: 'secret123' }) }) test('the first-account link switches to registration and says when one already exists', async () => { mockFetch({ 'POST /api/v1/auth/register': () => apiError(403, 'registration_closed') }) render() await userEvent.click(screen.getByRole('button', { name: 'This is a new server: create the first account' })) - await fill('tom', 'secret123') + await fill('tom@example.org', 'secret123') await userEvent.click(screen.getByRole('button', { name: 'Create account' })) expect(await screen.findByRole('alert')).toHaveTextContent('An account already exists.') }) @@ -61,7 +61,7 @@ test('an unreachable server is reported as such', async () => { }), ) render() - await fill('tom', 'secret123') + await fill('tom@example.org', 'secret123') await userEvent.click(screen.getByRole('button', { name: 'Sign in' })) expect(await screen.findByRole('alert')).toHaveTextContent('Cannot reach the server.') }) @@ -74,7 +74,7 @@ test('AuthGate shows nothing while loading, the form when signed out, the app wh , ) expect(screen.queryByText('the app')).not.toBeInTheDocument() - expect(screen.queryByLabelText('Username')).not.toBeInTheDocument() + expect(screen.queryByLabelText('Email')).not.toBeInTheDocument() sessionStore.setState({ status: 'anonymous' }) rerender( @@ -82,7 +82,7 @@ test('AuthGate shows nothing while loading, the form when signed out, the app wh

the app

, ) - expect(screen.getByLabelText('Username')).toBeInTheDocument() + expect(screen.getByLabelText('Email')).toBeInTheDocument() sessionStore.setState({ status: 'authenticated', user }) rerender( diff --git a/web/src/auth/LoginPage.tsx b/web/src/auth/LoginPage.tsx index cf24bc6..a25ded9 100644 --- a/web/src/auth/LoginPage.tsx +++ b/web/src/auth/LoginPage.tsx @@ -11,7 +11,7 @@ import { login, register } from './session' export default function LoginPage() { const { t } = useTranslation() const [creating, setCreating] = useState(false) - const [username, setUsername] = useState('') + const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [error, setError] = useState(null) const [busy, setBusy] = useState(false) @@ -21,7 +21,7 @@ export default function LoginPage() { setBusy(true) setError(null) try { - await (creating ? register : login)(username, password) + await (creating ? register : login)(email, password) } catch (e) { setError(t(errorMessageKey(e instanceof ApiError ? e.code : 'unknown'))) } finally { @@ -43,12 +43,13 @@ export default function LoginPage() {

{creating ? t('auth.registerTitle') : t('auth.signInTitle')}

- + setUsername(e.target.value)} - autoComplete="username" + id="email" + type="email" + value={email} + onChange={(e) => setEmail(e.target.value)} + autoComplete="email" required />
diff --git a/web/src/auth/session.test.ts b/web/src/auth/session.test.ts index 0fbf830..9baacf3 100644 --- a/web/src/auth/session.test.ts +++ b/web/src/auth/session.test.ts @@ -11,7 +11,7 @@ import { sessionStore, } from './session' -const user = { id: 1, username: 'tom', is_admin: true } +const user = { id: 1, email: 'tom@example.org', is_admin: true } function session(opts: { access?: string; refresh?: string; expiresInSeconds?: number } = {}) { const { access = 'a1', refresh = 'r1', expiresInSeconds = 900 } = opts @@ -50,12 +50,12 @@ afterEach(() => { test('login keeps the session and opens it', async () => { const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session() }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') expect(sessionStore.getState().status).toBe('authenticated') expect(sessionStore.getState().user).toEqual(user) expect(stored().access_token).toBe('a1') expect(stored().refresh_token).toBe('r1') - expect(JSON.parse(calls[0].init.body as string)).toEqual({ username: 'tom', password: 'secret123' }) + expect(JSON.parse(calls[0].init.body as string)).toEqual({ email: 'tom@example.org', password: 'secret123' }) expect((calls[0].init.headers as Record).Authorization).toBeUndefined() }) @@ -64,14 +64,14 @@ test('register creates the account and then signs in', async () => { 'POST /api/v1/auth/register': () => new Response(JSON.stringify(user), { status: 201 }), 'POST /api/v1/auth/login': () => session(), }) - await register('tom', 'secret123') + await register('tom@example.org', 'secret123') expect(calls.map((c) => c.key)).toEqual(['POST /api/v1/auth/register', 'POST /api/v1/auth/login']) expect(sessionStore.getState().status).toBe('authenticated') }) test('a token with time left is returned without any request', async () => { const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 600 }) }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await expect(getAccessToken()).resolves.toBe('a1') expect(calls).toHaveLength(1) }) @@ -81,7 +81,7 @@ test('five calls at once with 30 seconds left send a single refresh', async () = 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30 }), 'POST /api/v1/auth/refresh': () => session({ access: 'a2', refresh: 'r2' }), }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') const tokens = await Promise.all([1, 2, 3, 4, 5].map(() => getAccessToken())) expect(tokens).toEqual(['a2', 'a2', 'a2', 'a2', 'a2']) const calls = (fetch as ReturnType).mock.calls.filter(([url]) => String(url).endsWith('/auth/refresh')) @@ -94,7 +94,7 @@ test('a refresh sends the stored refresh token', async () => { 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30, refresh: 'r1' }), 'POST /api/v1/auth/refresh': () => session({ access: 'a2', refresh: 'r2' }), }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await getAccessToken() const refresh = calls.find((c) => c.key === 'POST /api/v1/auth/refresh')! expect(JSON.parse(refresh.init.body as string)).toEqual({ refresh_token: 'r1' }) @@ -102,7 +102,7 @@ test('a refresh sends the stored refresh token', async () => { test('a second tab that already renewed the session is adopted, not renewed again', async () => { const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30 }) }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') // The lock is where tab B gets in first: by the time this tab holds it, B has written a fresh session. Object.defineProperty(navigator, 'locks', { configurable: true, @@ -123,7 +123,7 @@ test('a refresh token the server refuses signs out once and stops asking', async 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30 }), 'POST /api/v1/auth/refresh': () => apiError(401, 'invalid_refresh_token'), }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await expect(getAccessToken()).resolves.toBeNull() expect(sessionStore.getState().status).toBe('anonymous') expect(localStorage.getItem('sonda.session')).toBeNull() @@ -139,7 +139,7 @@ test('a network failure while renewing keeps the session', async () => { throw new TypeError('Failed to fetch') }, }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await expect(getAccessToken()).resolves.toBe('a1') expect(sessionStore.getState().status).toBe('authenticated') expect(stored()).not.toBeNull() @@ -150,14 +150,14 @@ test('login works for the page lifetime when storage is blocked', async () => { throw new Error('blocked') }) mockFetch({ 'POST /api/v1/auth/login': () => session() }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') expect(sessionStore.getState().status).toBe('authenticated') await expect(getAccessToken()).resolves.toBe('a1') }) test('mediaUrl adds the token to a path of the API', async () => { mockFetch({ 'POST /api/v1/auth/login': () => session({ access: 'tok' }) }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') expect(mediaUrl('/tracks/3/stream')).toBe('/api/v1/tracks/3/stream?access_token=tok') }) @@ -172,7 +172,7 @@ test('listeners hear about a new token until they unsubscribe', async () => { }) const heard: string[] = [] const off = onTokenChange((t) => heard.push(t)) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await getAccessToken() off() sessionStore.setState({ accessExpiresAt: Date.now() + 10_000 }) @@ -189,7 +189,7 @@ test('a session about to run out is renewed in the background, before anyone ask 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 900 }), 'POST /api/v1/auth/refresh': () => session({ access: 'a2', refresh: 'r2' }), }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') const heard: string[] = [] onTokenChange((t) => heard.push(t)) @@ -211,7 +211,7 @@ test('signing out stops the renewal in the background', async () => { 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 900 }), 'POST /api/v1/auth/logout': () => new Response(null, { status: 204 }), }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await logout() await vi.advanceTimersByTimeAsync(20 * 60_000) expect(refreshRequests(calls)).toHaveLength(0) @@ -223,7 +223,7 @@ test('a renewal the server refuses in the background signs out and is not tried 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 900 }), 'POST /api/v1/auth/refresh': () => apiError(401, 'invalid_refresh_token'), }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await vi.advanceTimersByTimeAsync(13 * 60_000) expect(sessionStore.getState().status).toBe('anonymous') await vi.advanceTimersByTimeAsync(10 * 60_000) @@ -235,7 +235,7 @@ test('logout revokes the refresh token and forgets the session', async () => { 'POST /api/v1/auth/login': () => session(), 'POST /api/v1/auth/logout': () => new Response(null, { status: 204 }), }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await logout() const call = calls.find((c) => c.key === 'POST /api/v1/auth/logout')! expect(JSON.parse(call.init.body as string)).toEqual({ refresh_token: 'r1' }) @@ -250,7 +250,7 @@ test('logout forgets the session even when the server cannot be reached', async throw new TypeError('Failed to fetch') }, }) - await login('tom', 'secret123') + await login('tom@example.org', 'secret123') await logout() expect(sessionStore.getState().status).toBe('anonymous') }) diff --git a/web/src/auth/session.ts b/web/src/auth/session.ts index c78ce66..326a0d0 100644 --- a/web/src/auth/session.ts +++ b/web/src/auth/session.ts @@ -136,14 +136,14 @@ export function signOut(): void { // --- public operations --------------------------------------------------------------------------- -export async function login(username: string, password: string): Promise { - const session = await api.post('/auth/login', { username, password }, { auth: false }) +export async function login(email: string, password: string): Promise { + const session = await api.post('/auth/login', { email, password }, { auth: false }) open(session, true) } -export async function register(username: string, password: string): Promise { - await api.post('/auth/register', { username, password }, { auth: false }) - await login(username, password) +export async function register(email: string, password: string): Promise { + await api.post('/auth/register', { email, password }, { auth: false }) + await login(email, password) } export async function logout(): Promise { diff --git a/web/src/components/layout/Player.test.tsx b/web/src/components/layout/Player.test.tsx index 16c2fc2..2fa5d13 100644 --- a/web/src/components/layout/Player.test.tsx +++ b/web/src/components/layout/Player.test.tsx @@ -31,7 +31,7 @@ const [a, b, c, d, e] = [1, 2, 3, 4, 5].map((n) => track(n)) beforeEach(async () => { vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') await initI18n() - sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } }) + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: false } }) usePlayer.setState({ queue: [], original: [], diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 300707c..347fd04 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -131,7 +131,7 @@ "auth": { "signInTitle": "Sign in", "registerTitle": "Create the first account", - "username": "Username", + "email": "Email", "password": "Password", "signIn": "Sign in", "createAccount": "Create account", @@ -139,9 +139,9 @@ "haveAccount": "I already have an account" }, "error": { - "invalid_credentials": "Wrong username or password.", + "invalid_credentials": "Wrong email or password.", "registration_closed": "An account already exists. Ask an admin to create yours.", - "username_taken": "That username is taken.", + "email_taken": "That email is already registered.", "invalid_input": "Check what you typed and try again.", "unauthorized": "Your session has ended. Sign in again.", "network": "Cannot reach the server. Check your connection and try again.", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 86c7c62..3d881f2 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -131,7 +131,7 @@ "auth": { "signInTitle": "Accedi", "registerTitle": "Crea il primo account", - "username": "Nome utente", + "email": "Email", "password": "Password", "signIn": "Accedi", "createAccount": "Crea account", @@ -139,9 +139,9 @@ "haveAccount": "Ho già un account" }, "error": { - "invalid_credentials": "Nome utente o password sbagliati.", + "invalid_credentials": "Email o password sbagliate.", "registration_closed": "Esiste già un account. Chiedi a un admin di creare il tuo.", - "username_taken": "Questo nome utente è già preso.", + "email_taken": "Questa email è già registrata.", "invalid_input": "Controlla quello che hai scritto e riprova.", "unauthorized": "La sessione è terminata. Accedi di nuovo.", "network": "Il server non risponde. Controlla la connessione e riprova.", diff --git a/web/src/pages/HomePage.test.tsx b/web/src/pages/HomePage.test.tsx index 96fd9de..ff67379 100644 --- a/web/src/pages/HomePage.test.tsx +++ b/web/src/pages/HomePage.test.tsx @@ -57,7 +57,7 @@ function renderHome() { beforeEach(async () => { vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') await initI18n() - sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } }) + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: false } }) usePlayer.setState({ queue: [], original: [], index: 0, playing: false, positionMs: 0 }) }) diff --git a/web/src/pages/SearchPage.test.tsx b/web/src/pages/SearchPage.test.tsx index 31e16b1..70ae2aa 100644 --- a/web/src/pages/SearchPage.test.tsx +++ b/web/src/pages/SearchPage.test.tsx @@ -57,7 +57,7 @@ const box = () => screen.getByRole('searchbox', { name: 'Search your library' }) beforeEach(async () => { vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') await initI18n() - sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } }) + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: false } }) usePlayer.setState({ queue: [], original: [], index: 0, playing: false, positionMs: 0 }) }) diff --git a/web/src/pages/SettingsPage.test.tsx b/web/src/pages/SettingsPage.test.tsx index db500ab..e5d4f28 100644 --- a/web/src/pages/SettingsPage.test.tsx +++ b/web/src/pages/SettingsPage.test.tsx @@ -25,7 +25,7 @@ beforeEach(async () => { initTheme() sessionStore.setState({ status: 'authenticated', - user: { id: 1, username: 'tom', is_admin: true }, + user: { id: 1, email: 'tom@example.org', is_admin: true }, accessToken: 'a1', accessExpiresAt: Date.now() + 600_000, refreshToken: 'r1', @@ -40,14 +40,14 @@ async function changePassword(current: string, next: string) { test('the page says who is signed in', () => { renderSettings() - expect(screen.getByText('tom')).toBeInTheDocument() + expect(screen.getByText('tom@example.org')).toBeInTheDocument() expect(screen.getByText('Admin')).toBeInTheDocument() }) test('a user who is not an admin is not called one', () => { - sessionStore.setState({ user: { id: 2, username: 'ann', is_admin: false } }) + sessionStore.setState({ user: { id: 2, email: 'ann@example.org', is_admin: false } }) renderSettings() - expect(screen.getByText('ann')).toBeInTheDocument() + expect(screen.getByText('ann@example.org')).toBeInTheDocument() expect(screen.queryByText('Admin')).not.toBeInTheDocument() }) diff --git a/web/src/pages/SettingsPage.tsx b/web/src/pages/SettingsPage.tsx index 00f355e..bdd68bc 100644 --- a/web/src/pages/SettingsPage.tsx +++ b/web/src/pages/SettingsPage.tsx @@ -108,7 +108,7 @@ export default function SettingsPage() {
-

{user?.username}

+

{user?.email}

{user?.is_admin && ( {t('settings.admin')} )} diff --git a/web/src/pages/pages.test.tsx b/web/src/pages/pages.test.tsx index 6f987d2..88d511f 100644 --- a/web/src/pages/pages.test.tsx +++ b/web/src/pages/pages.test.tsx @@ -112,7 +112,7 @@ function renderPage(element: ReactElement, path: string, routePath = path) { beforeEach(async () => { vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') await initI18n() - sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } }) + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: false } }) usePlayer.setState({ queue: [], original: [], diff --git a/web/src/player/engine.test.ts b/web/src/player/engine.test.ts index c970fcc..b7ed7c4 100644 --- a/web/src/player/engine.test.ts +++ b/web/src/player/engine.test.ts @@ -67,7 +67,7 @@ function session(access: string) { access_expires_at: new Date(Date.now() + 900_000).toISOString(), refresh_token: `r-${access}`, refresh_expires_at: new Date(Date.now() + 86_400_000).toISOString(), - user: { id: 1, username: 'tom', is_admin: false }, + user: { id: 1, email: 'tom@example.org', is_admin: false }, } } diff --git a/web/src/player/usePlayer.test.tsx b/web/src/player/usePlayer.test.tsx index 6b45fca..d56a645 100644 --- a/web/src/player/usePlayer.test.tsx +++ b/web/src/player/usePlayer.test.tsx @@ -56,7 +56,7 @@ beforeEach(() => { }) sessionStore.setState({ status: 'authenticated', - user: { id: 1, username: 'tom', is_admin: false }, + user: { id: 1, email: 'tom@example.org', is_admin: false }, accessToken: 'tok', accessExpiresAt: Date.now() + 600_000, refreshToken: 'r', diff --git a/web/src/smoke.test.tsx b/web/src/smoke.test.tsx index a98ac42..276de6d 100644 --- a/web/src/smoke.test.tsx +++ b/web/src/smoke.test.tsx @@ -10,7 +10,7 @@ beforeEach(async () => { }) test('a signed-in user sees the app', () => { - sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: true } }) + sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } }) render() expect(screen.getByText('Sonda')).toBeInTheDocument() }) @@ -18,5 +18,5 @@ test('a signed-in user sees the app', () => { test('a signed-out user sees the sign-in form instead', () => { sessionStore.setState({ status: 'anonymous', user: null }) render() - expect(screen.getByLabelText('Username')).toBeInTheDocument() + expect(screen.getByLabelText('Email')).toBeInTheDocument() })