feat: add option to allow non-local users to change usernames (#8714)

Add a new config option for OAuth2 authentication sources: allow users to change their username.

In the case where OAuth2 is more like a social OAuth2 login there's no need to not allow users to change their username. The information how the user is linked to the authentication source is stored in different fields.

Resolves forgejo/forgejo#687

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/8714
Reviewed-by: 0ko <0ko@noreply.codeberg.org>
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Co-authored-by: Gusted <postmaster@gusted.xyz>
Co-committed-by: Gusted <postmaster@gusted.xyz>
This commit is contained in:
Gusted 2025-08-06 20:25:13 +02:00 committed by 0ko
commit b51f97e97d
13 changed files with 119 additions and 17 deletions

View file

@ -13,6 +13,7 @@ import (
"forgejo.org/models"
asymkey_model "forgejo.org/models/asymkey"
"forgejo.org/models/auth"
"forgejo.org/models/db"
"forgejo.org/models/organization"
packages_model "forgejo.org/models/packages"
@ -25,6 +26,7 @@ import (
"forgejo.org/modules/storage"
"forgejo.org/modules/util"
"forgejo.org/services/agit"
"forgejo.org/services/auth/source/oauth2"
org_service "forgejo.org/services/org"
"forgejo.org/services/packages"
container_service "forgejo.org/services/packages/container"
@ -49,9 +51,26 @@ func renameUser(ctx context.Context, u *user_model.User, newUserName string, doe
// Non-local users are not allowed to change their username.
// If the doer is an admin, then allow the rename - they know better.
if !doerIsAdmin && !u.IsOrganization() && !u.IsLocal() {
return user_model.ErrUserIsNotLocal{
UID: u.ID,
Name: u.Name,
// If the user's authentication source is OAuth2 and that source allows for
// username changes then don't make a fuzz about it.
if !u.IsOAuth2() {
return user_model.ErrUserIsNotLocal{
UID: u.ID,
Name: u.Name,
}
}
source, err := auth.GetSourceByID(ctx, u.LoginSource)
if err != nil {
return err
}
sourceCfg := source.Cfg.(*oauth2.Source)
if !sourceCfg.AllowUsernameChange {
return user_model.ErrUserIsNotLocal{
UID: u.ID,
Name: u.Name,
}
}
}