diff --git a/modules/setting/oauth2.go b/modules/setting/oauth2.go index d3c4d5c387..f054bad9ed 100644 --- a/modules/setting/oauth2.go +++ b/modules/setting/oauth2.go @@ -22,11 +22,13 @@ const ( OAuth2UsernameNickname OAuth2UsernameType = "nickname" // OAuth2UsernameEmail username of oauth2 email field will be used as gitea name OAuth2UsernameEmail OAuth2UsernameType = "email" + // @OAuth2UsernamePreferredUsername oauth2 preferred_username field will be used as gitea name + OAuth2UsernamePreferredUsername OAuth2UsernameType = "username" ) func (username OAuth2UsernameType) isValid() bool { switch username { - case OAuth2UsernameUserid, OAuth2UsernameNickname, OAuth2UsernameEmail: + case OAuth2UsernameUserid, OAuth2UsernameNickname, OAuth2UsernameEmail, OAuth2UsernamePreferredUsername: return true } return false diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index 2a8f5c05d7..72c4574729 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -387,7 +387,20 @@ func handleSignInFull(ctx *context.Context, u *user_model.User, remember, obeyRe } func getUserName(gothUser *goth.User) (string, error) { - return user_model.NormalizeUserName(strings.Split(gothUser.RawData["preferred_username"].(string), "@")[0]) + switch setting.OAuth2Client.Username { + case setting.OAuth2UsernamePreferredUsername: + username := gothUser.RawData["preferred_username"].(string) + if strings.containsAny(username, "@") { + return user_model.NormalizeUserName(strings.Split(username, "@")[0]) + } + return user_model.NormalizeUserName(username) + case setting.OAuth2UsernameEmail: + return user_model.NormalizeUserName(strings.Split(gothUser.Email, "@")[0]) + case setting.OAuth2UsernameNickname: + return user_model.NormalizeUserName(gothUser.NickName) + default: // OAuth2UsernameUserid + return gothUser.UserID, nil + } } // HandleSignOut resets the session and sets the cookies diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index f5ca0bda5e..bdd8168a0c 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -959,6 +959,8 @@ func SignInOAuthCallback(ctx *context.Context) { } if setting.OAuth2Client.Username == setting.OAuth2UsernameNickname && gothUser.NickName == "" { missingFields = append(missingFields, "nickname") + } else if setting.OAuth2Client.Username == setting.OAuth2UsernamePreferredUsername && gothUser.RawData["preferred_username"].(string) == "" { + missingFields = append(missingFields, "preferred_nickname") } if len(missingFields) > 0 { // we don't have enough information to create an account automatically,