fix(auth): allow admins to change any username including their own
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m6s
ci / ts / ts (packages + web) (push) Successful in 2m59s
ci / api / api (push) Successful in 49s
ci / db / db (push) Successful in 1m17s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m25s

This commit is contained in:
mrleo1nid committed 2026-10-21 17:33:19 +03:00
1 parent b0cbd0f149
commit c34272d508
16 files changed
+431 -266

No files matched your search

+18 -1
View File
@@ -150,13 +150,14 @@ func displayName(s string) (*string, error) {
// UserPatch — изменения пользователя из админки. nil — не менять.
type UserPatch struct {
Username *string
DisplayName *string
Role *Role
IsBlocked *bool
ReviewsUploads *bool
}
// UpdateUser меняет имя, роль и блокировку с проверкой прав по каждому изменению.
// UpdateUser меняет логин, имя, роль и блокировку с проверкой прав по каждому изменению.
func (s *Service) UpdateUser(ctx context.Context, p Principal, id uuid.UUID, patch UserPatch) (User, error) {
if patch.Role != nil && !patch.Role.Valid() {
return User{}, apperr.Validation("role", CodeRoleInvalid, "unknown role", nil)
@@ -178,6 +179,19 @@ func (s *Service) UpdateUser(ctx context.Context, p Principal, id uuid.UUID, pat
})
}
if patch.Username != nil {
if p.Role != RoleAdmin {
return forbidden()
}
username := NormalizeUsername(*patch.Username)
if err := ValidateUsername("username", username); err != nil {
return err
}
if username != target.Username {
upd.Username = &username
audit("user.username_change", map[string]any{"from": target.Username, "to": username})
}
}
if patch.DisplayName != nil {
if !CanManageUser(actor, tgt, UserEdit) {
return forbidden()
@@ -247,6 +261,9 @@ func (s *Service) UpdateUser(ctx context.Context, p Principal, id uuid.UUID, pat
}
return nil
})
if errors.Is(err, ErrUsernameTaken) {
return User{}, apperr.Validation("username", CodeUsernameTaken, "username is taken", nil)
}
return out, err
}
+1 -1
View File
@@ -63,7 +63,7 @@ func (h *Handler) UpdateUser(ctx context.Context, req gen.UpdateUserRequestObjec
if err != nil {
return nil, err
}
patch := UserPatch{DisplayName: req.Body.DisplayName, IsBlocked: req.Body.IsBlocked, ReviewsUploads: req.Body.ReviewsUploads}
patch := UserPatch{Username: req.Body.Username, DisplayName: req.Body.DisplayName, IsBlocked: req.Body.IsBlocked, ReviewsUploads: req.Body.ReviewsUploads}
if req.Body.Role != nil {
r := Role(*req.Body.Role)
patch.Role = &r
+28
View File
@@ -76,6 +76,34 @@ func TestAdminCreatesModeratorWhoCreatesUser(t *testing.T) {
assert.Equal(t, auth.CodeForbidden, e.createUser(listener, "another", "user").code())
}
func TestAdminChangesUsername(t *testing.T) {
e := newEnv(t)
root := e.addUser("root", "root-password-1", auth.RoleAdmin)
listener := e.addUser("listener", "listener-password-1", auth.RoleUser)
mod := e.addUser("mod", "mod-password-1", auth.RoleModerator)
tok := e.signIn("root", "root-password-1")
patch := func(token string, id uuid.UUID, username string) resp {
return e.do(http.MethodPatch, "/api/v1/admin/users/"+id.String(), map[string]any{"username": username}, bearer(token))
}
for _, target := range []auth.User{listener, mod, root} {
r := patch(tok, target.ID, " NEW."+target.Username+" ")
require.Equal(t, http.StatusOK, r.Code, r.Body.String())
assert.Equal(t, "new."+target.Username, r.body["username"])
assert.Equal(t, "user.username_change", e.store.Audit[len(e.store.Audit)-1].Action)
assert.Equal(t, http.StatusOK, e.login("new."+target.Username, map[uuid.UUID]string{
root.ID: "root-password-1", listener.ID: "listener-password-1", mod.ID: "mod-password-1",
}[target.ID], "web").Code)
}
assert.Equal(t, http.StatusOK, e.do(http.MethodGet, "/api/v1/me", nil, bearer(tok)).Code, "own rename preserves session")
assert.Equal(t, auth.CodeUsernameTaken, patch(tok, listener.ID, "NEW.ROOT").code())
assert.Equal(t, auth.CodeUsernameInvalid, patch(tok, listener.ID, "invalid space").code())
assert.Equal(t, auth.CodeUsernameInvalid, patch(tok, listener.ID, "").code())
assert.Equal(t, "new.listener", e.store.Users[listener.ID].Username)
modTok := e.signIn("new.mod", "mod-password-1")
assert.Equal(t, auth.CodeForbidden, patch(modTok, listener.ID, "forbidden").code())
assert.Equal(t, auth.CodeForbidden, patch(modTok, mod.ID, "forbidden").code())
}
func TestCreateUserValidation(t *testing.T) {
e := newEnv(t)
e.addUser("root", "root-password-1", auth.RoleAdmin)
@@ -293,7 +293,18 @@ func (s *MemStore) LockActiveAdmins(ctx context.Context) (int, error) { return s
// UpdateUser реализует auth.Store.
func (s *MemStore) UpdateUser(ctx context.Context, id uuid.UUID, upd auth.UserUpdate) (auth.User, error) {
if upd.Username != nil {
unlock := s.lock()
taken := s.usernameTaken(*upd.Username, id)
unlock()
if taken {
return auth.User{}, auth.ErrUsernameTaken
}
}
err := s.update(id, func(u *auth.User) {
if upd.Username != nil {
u.Username = *upd.Username
}
if upd.DisplayName != nil {
u.DisplayName = *upd.DisplayName
}
+7 -2
View File
@@ -340,8 +340,9 @@ func (s *PgStore) UpdateUser(ctx context.Context, id uuid.UUID, upd UserUpdate)
r := string(*upd.Role)
role = &r
}
return scanUser(s.q.QueryRow(ctx, `
u, err := scanUser(s.q.QueryRow(ctx, `
UPDATE users SET
username = COALESCE($8, username),
display_name = CASE WHEN $2 THEN $3 ELSE display_name END,
role = COALESCE($4::user_role, role),
is_blocked = COALESCE($5, is_blocked),
@@ -349,7 +350,11 @@ func (s *PgStore) UpdateUser(ctx context.Context, id uuid.UUID, upd UserUpdate)
token_version = token_version + CASE WHEN $6 THEN 1 ELSE 0 END,
updated_at = now()
WHERE id = $1
RETURNING `+userColumns, id, setName, name, role, upd.IsBlocked, upd.RevokeTokens, upd.ReviewsUploads))
RETURNING `+userColumns, id, setName, name, role, upd.IsBlocked, upd.RevokeTokens, upd.ReviewsUploads, upd.Username))
if isUniqueViolation(err) {
return User{}, ErrUsernameTaken
}
return u, err
}
// ResetPassword реализует Store.
+1
View File
@@ -31,6 +31,7 @@ type UserFilter struct {
// UserUpdate — изменения из админки. nil — не менять.
type UserUpdate struct {
Username *string
DisplayName **string
Role *Role
IsBlocked *bool