diff options
author | Lunny Xiao <xiaolunwen@gmail.com> | 2022-01-02 21:12:35 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-02 21:12:35 +0800 |
commit | de8e3948a5e38f7eaf82d3c0cfd10e995bf68e92 (patch) | |
tree | bbcb011d264e0d614d49c734856b446360c5a4a3 /routers/web | |
parent | e61b390d545919244141b699b28e3fbc42adc66f (diff) | |
download | gitea-de8e3948a5e38f7eaf82d3c0cfd10e995bf68e92.tar.gz gitea-de8e3948a5e38f7eaf82d3c0cfd10e995bf68e92.zip |
Refactor auth package (#17962)
Diffstat (limited to 'routers/web')
23 files changed, 2355 insertions, 2228 deletions
diff --git a/routers/web/admin/auths.go b/routers/web/admin/auths.go index b288273871..338a54c5dd 100644 --- a/routers/web/admin/auths.go +++ b/routers/web/admin/auths.go @@ -13,7 +13,7 @@ import ( "strconv" "strings" - "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/auth/pam" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -24,7 +24,7 @@ import ( auth_service "code.gitea.io/gitea/services/auth" "code.gitea.io/gitea/services/auth/source/ldap" "code.gitea.io/gitea/services/auth/source/oauth2" - pamService "code.gitea.io/gitea/services/auth/source/pam" + pam_service "code.gitea.io/gitea/services/auth/source/pam" "code.gitea.io/gitea/services/auth/source/smtp" "code.gitea.io/gitea/services/auth/source/sspi" "code.gitea.io/gitea/services/forms" @@ -50,13 +50,13 @@ func Authentications(ctx *context.Context) { ctx.Data["PageIsAdminAuthentications"] = true var err error - ctx.Data["Sources"], err = login.Sources() + ctx.Data["Sources"], err = auth.Sources() if err != nil { - ctx.ServerError("login.Sources", err) + ctx.ServerError("auth.Sources", err) return } - ctx.Data["Total"] = login.CountSources() + ctx.Data["Total"] = auth.CountSources() ctx.HTML(http.StatusOK, tplAuths) } @@ -68,14 +68,14 @@ type dropdownItem struct { var ( authSources = func() []dropdownItem { items := []dropdownItem{ - {login.LDAP.String(), login.LDAP}, - {login.DLDAP.String(), login.DLDAP}, - {login.SMTP.String(), login.SMTP}, - {login.OAuth2.String(), login.OAuth2}, - {login.SSPI.String(), login.SSPI}, + {auth.LDAP.String(), auth.LDAP}, + {auth.DLDAP.String(), auth.DLDAP}, + {auth.SMTP.String(), auth.SMTP}, + {auth.OAuth2.String(), auth.OAuth2}, + {auth.SSPI.String(), auth.SSPI}, } if pam.Supported { - items = append(items, dropdownItem{login.Names[login.PAM], login.PAM}) + items = append(items, dropdownItem{auth.Names[auth.PAM], auth.PAM}) } return items }() @@ -93,8 +93,8 @@ func NewAuthSource(ctx *context.Context) { ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminAuthentications"] = true - ctx.Data["type"] = login.LDAP - ctx.Data["CurrentTypeName"] = login.Names[login.LDAP] + ctx.Data["type"] = auth.LDAP + ctx.Data["CurrentTypeName"] = auth.Names[auth.LDAP] ctx.Data["CurrentSecurityProtocol"] = ldap.SecurityProtocolNames[ldap.SecurityProtocolUnencrypted] ctx.Data["smtp_auth"] = "PLAIN" ctx.Data["is_active"] = true @@ -226,7 +226,7 @@ func NewAuthSourcePost(ctx *context.Context) { ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdminAuthentications"] = true - ctx.Data["CurrentTypeName"] = login.Type(form.Type).String() + ctx.Data["CurrentTypeName"] = auth.Type(form.Type).String() ctx.Data["CurrentSecurityProtocol"] = ldap.SecurityProtocolNames[ldap.SecurityProtocol(form.SecurityProtocol)] ctx.Data["AuthSources"] = authSources ctx.Data["SecurityProtocols"] = securityProtocols @@ -242,29 +242,29 @@ func NewAuthSourcePost(ctx *context.Context) { hasTLS := false var config convert.Conversion - switch login.Type(form.Type) { - case login.LDAP, login.DLDAP: + switch auth.Type(form.Type) { + case auth.LDAP, auth.DLDAP: config = parseLDAPConfig(form) hasTLS = ldap.SecurityProtocol(form.SecurityProtocol) > ldap.SecurityProtocolUnencrypted - case login.SMTP: + case auth.SMTP: config = parseSMTPConfig(form) hasTLS = true - case login.PAM: - config = &pamService.Source{ + case auth.PAM: + config = &pam_service.Source{ ServiceName: form.PAMServiceName, EmailDomain: form.PAMEmailDomain, SkipLocalTwoFA: form.SkipLocalTwoFA, } - case login.OAuth2: + case auth.OAuth2: config = parseOAuth2Config(form) - case login.SSPI: + case auth.SSPI: var err error config, err = parseSSPIConfig(ctx, form) if err != nil { ctx.RenderWithErr(err.Error(), tplAuthNew, form) return } - existing, err := login.SourcesByType(login.SSPI) + existing, err := auth.SourcesByType(auth.SSPI) if err != nil || len(existing) > 0 { ctx.Data["Err_Type"] = true ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_of_type_exist"), tplAuthNew, form) @@ -281,18 +281,18 @@ func NewAuthSourcePost(ctx *context.Context) { return } - if err := login.CreateSource(&login.Source{ - Type: login.Type(form.Type), + if err := auth.CreateSource(&auth.Source{ + Type: auth.Type(form.Type), Name: form.Name, IsActive: form.IsActive, IsSyncEnabled: form.IsSyncEnabled, Cfg: config, }); err != nil { - if login.IsErrSourceAlreadyExist(err) { + if auth.IsErrSourceAlreadyExist(err) { ctx.Data["Err_Name"] = true - ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(login.ErrSourceAlreadyExist).Name), tplAuthNew, form) + ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(auth.ErrSourceAlreadyExist).Name), tplAuthNew, form) } else { - ctx.ServerError("login.CreateSource", err) + ctx.ServerError("auth.CreateSource", err) } return } @@ -314,9 +314,9 @@ func EditAuthSource(ctx *context.Context) { oauth2providers := oauth2.GetOAuth2Providers() ctx.Data["OAuth2Providers"] = oauth2providers - source, err := login.GetSourceByID(ctx.ParamsInt64(":authid")) + source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid")) if err != nil { - ctx.ServerError("login.GetSourceByID", err) + ctx.ServerError("auth.GetSourceByID", err) return } ctx.Data["Source"] = source @@ -349,9 +349,9 @@ func EditAuthSourcePost(ctx *context.Context) { oauth2providers := oauth2.GetOAuth2Providers() ctx.Data["OAuth2Providers"] = oauth2providers - source, err := login.GetSourceByID(ctx.ParamsInt64(":authid")) + source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid")) if err != nil { - ctx.ServerError("login.GetSourceByID", err) + ctx.ServerError("auth.GetSourceByID", err) return } ctx.Data["Source"] = source @@ -363,19 +363,19 @@ func EditAuthSourcePost(ctx *context.Context) { } var config convert.Conversion - switch login.Type(form.Type) { - case login.LDAP, login.DLDAP: + switch auth.Type(form.Type) { + case auth.LDAP, auth.DLDAP: config = parseLDAPConfig(form) - case login.SMTP: + case auth.SMTP: config = parseSMTPConfig(form) - case login.PAM: - config = &pamService.Source{ + case auth.PAM: + config = &pam_service.Source{ ServiceName: form.PAMServiceName, EmailDomain: form.PAMEmailDomain, } - case login.OAuth2: + case auth.OAuth2: config = parseOAuth2Config(form) - case login.SSPI: + case auth.SSPI: config, err = parseSSPIConfig(ctx, form) if err != nil { ctx.RenderWithErr(err.Error(), tplAuthEdit, form) @@ -390,7 +390,7 @@ func EditAuthSourcePost(ctx *context.Context) { source.IsActive = form.IsActive source.IsSyncEnabled = form.IsSyncEnabled source.Cfg = config - if err := login.UpdateSource(source); err != nil { + if err := auth.UpdateSource(source); err != nil { if oauth2.IsErrOpenIDConnectInitialize(err) { ctx.Flash.Error(err.Error(), true) ctx.HTML(http.StatusOK, tplAuthEdit) @@ -407,17 +407,17 @@ func EditAuthSourcePost(ctx *context.Context) { // DeleteAuthSource response for deleting an auth source func DeleteAuthSource(ctx *context.Context) { - source, err := login.GetSourceByID(ctx.ParamsInt64(":authid")) + source, err := auth.GetSourceByID(ctx.ParamsInt64(":authid")) if err != nil { - ctx.ServerError("login.GetSourceByID", err) + ctx.ServerError("auth.GetSourceByID", err) return } - if err = auth_service.DeleteLoginSource(source); err != nil { - if login.IsErrSourceInUse(err) { + if err = auth_service.DeleteSource(source); err != nil { + if auth.IsErrSourceInUse(err) { ctx.Flash.Error(ctx.Tr("admin.auths.still_in_used")) } else { - ctx.Flash.Error(fmt.Sprintf("DeleteLoginSource: %v", err)) + ctx.Flash.Error(fmt.Sprintf("auth_service.DeleteSource: %v", err)) } ctx.JSON(http.StatusOK, map[string]interface{}{ "redirect": setting.AppSubURL + "/admin/auths/" + url.PathEscape(ctx.Params(":authid")), diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index 044efa0099..5cb25d8672 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -12,8 +12,8 @@ import ( "strings" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" - "code.gitea.io/gitea/models/login" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -81,9 +81,9 @@ func NewUser(ctx *context.Context) { ctx.Data["login_type"] = "0-0" - sources, err := login.Sources() + sources, err := auth.Sources() if err != nil { - ctx.ServerError("login.Sources", err) + ctx.ServerError("auth.Sources", err) return } ctx.Data["Sources"] = sources @@ -100,9 +100,9 @@ func NewUserPost(ctx *context.Context) { ctx.Data["PageIsAdminUsers"] = true ctx.Data["DefaultUserVisibilityMode"] = setting.Service.DefaultUserVisibilityMode - sources, err := login.Sources() + sources, err := auth.Sources() if err != nil { - ctx.ServerError("login.Sources", err) + ctx.ServerError("auth.Sources", err) return } ctx.Data["Sources"] = sources @@ -119,19 +119,19 @@ func NewUserPost(ctx *context.Context) { Email: form.Email, Passwd: form.Password, IsActive: true, - LoginType: login.Plain, + LoginType: auth.Plain, } if len(form.LoginType) > 0 { fields := strings.Split(form.LoginType, "-") if len(fields) == 2 { lType, _ := strconv.ParseInt(fields[0], 10, 0) - u.LoginType = login.Type(lType) + u.LoginType = auth.Type(lType) u.LoginSource, _ = strconv.ParseInt(fields[1], 10, 64) u.LoginName = form.LoginName } } - if u.LoginType == login.NoType || u.LoginType == login.Plain { + if u.LoginType == auth.NoType || u.LoginType == auth.Plain { if len(form.Password) < setting.MinPasswordLength { ctx.Data["Err_Password"] = true ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplUserNew, &form) @@ -201,26 +201,26 @@ func prepareUserInfo(ctx *context.Context) *user_model.User { ctx.Data["User"] = u if u.LoginSource > 0 { - ctx.Data["LoginSource"], err = login.GetSourceByID(u.LoginSource) + ctx.Data["LoginSource"], err = auth.GetSourceByID(u.LoginSource) if err != nil { - ctx.ServerError("login.GetSourceByID", err) + ctx.ServerError("auth.GetSourceByID", err) return nil } } else { - ctx.Data["LoginSource"] = &login.Source{} + ctx.Data["LoginSource"] = &auth.Source{} } - sources, err := login.Sources() + sources, err := auth.Sources() if err != nil { - ctx.ServerError("login.Sources", err) + ctx.ServerError("auth.Sources", err) return nil } ctx.Data["Sources"] = sources ctx.Data["TwoFactorEnabled"] = true - _, err = login.GetTwoFactorByUID(u.ID) + _, err = auth.GetTwoFactorByUID(u.ID) if err != nil { - if !login.IsErrTwoFactorNotEnrolled(err) { + if !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("IsErrTwoFactorNotEnrolled", err) return nil } @@ -268,11 +268,11 @@ func EditUserPost(ctx *context.Context) { fields := strings.Split(form.LoginType, "-") if len(fields) == 2 { loginType, _ := strconv.ParseInt(fields[0], 10, 0) - loginSource, _ := strconv.ParseInt(fields[1], 10, 64) + authSource, _ := strconv.ParseInt(fields[1], 10, 64) - if u.LoginSource != loginSource { - u.LoginSource = loginSource - u.LoginType = login.Type(loginType) + if u.LoginSource != authSource { + u.LoginSource = authSource + u.LoginType = auth.Type(loginType) } } @@ -325,13 +325,13 @@ func EditUserPost(ctx *context.Context) { } if form.Reset2FA { - tf, err := login.GetTwoFactorByUID(u.ID) - if err != nil && !login.IsErrTwoFactorNotEnrolled(err) { + tf, err := auth.GetTwoFactorByUID(u.ID) + if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("GetTwoFactorByUID", err) return } - if err = login.DeleteTwoFactorByID(tf.ID, u.ID); err != nil { + if err = auth.DeleteTwoFactorByID(tf.ID, u.ID); err != nil { ctx.ServerError("DeleteTwoFactorByID", err) return } diff --git a/routers/web/auth/2fa.go b/routers/web/auth/2fa.go new file mode 100644 index 0000000000..c61922cd9d --- /dev/null +++ b/routers/web/auth/2fa.go @@ -0,0 +1,166 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "errors" + "net/http" + + "code.gitea.io/gitea/models/auth" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/services/externalaccount" + "code.gitea.io/gitea/services/forms" +) + +var ( + tplTwofa base.TplName = "user/auth/twofa" + tplTwofaScratch base.TplName = "user/auth/twofa_scratch" +) + +// TwoFactor shows the user a two-factor authentication page. +func TwoFactor(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("twofa") + + // Check auto-login. + if checkAutoLogin(ctx) { + return + } + + // Ensure user is in a 2FA session. + if ctx.Session.Get("twofaUid") == nil { + ctx.ServerError("UserSignIn", errors.New("not in 2FA session")) + return + } + + ctx.HTML(http.StatusOK, tplTwofa) +} + +// TwoFactorPost validates a user's two-factor authentication token. +func TwoFactorPost(ctx *context.Context) { + form := web.GetForm(ctx).(*forms.TwoFactorAuthForm) + ctx.Data["Title"] = ctx.Tr("twofa") + + // Ensure user is in a 2FA session. + idSess := ctx.Session.Get("twofaUid") + if idSess == nil { + ctx.ServerError("UserSignIn", errors.New("not in 2FA session")) + return + } + + id := idSess.(int64) + twofa, err := auth.GetTwoFactorByUID(id) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + // Validate the passcode with the stored TOTP secret. + ok, err := twofa.ValidateTOTP(form.Passcode) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + if ok && twofa.LastUsedPasscode != form.Passcode { + remember := ctx.Session.Get("twofaRemember").(bool) + u, err := user_model.GetUserByID(id) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + if ctx.Session.Get("linkAccount") != nil { + err = externalaccount.LinkAccountFromStore(ctx.Session, u) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + } + + twofa.LastUsedPasscode = form.Passcode + if err = auth.UpdateTwoFactor(twofa); err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + handleSignIn(ctx, u, remember) + return + } + + ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, forms.TwoFactorAuthForm{}) +} + +// TwoFactorScratch shows the scratch code form for two-factor authentication. +func TwoFactorScratch(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("twofa_scratch") + + // Check auto-login. + if checkAutoLogin(ctx) { + return + } + + // Ensure user is in a 2FA session. + if ctx.Session.Get("twofaUid") == nil { + ctx.ServerError("UserSignIn", errors.New("not in 2FA session")) + return + } + + ctx.HTML(http.StatusOK, tplTwofaScratch) +} + +// TwoFactorScratchPost validates and invalidates a user's two-factor scratch token. +func TwoFactorScratchPost(ctx *context.Context) { + form := web.GetForm(ctx).(*forms.TwoFactorScratchAuthForm) + ctx.Data["Title"] = ctx.Tr("twofa_scratch") + + // Ensure user is in a 2FA session. + idSess := ctx.Session.Get("twofaUid") + if idSess == nil { + ctx.ServerError("UserSignIn", errors.New("not in 2FA session")) + return + } + + id := idSess.(int64) + twofa, err := auth.GetTwoFactorByUID(id) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + // Validate the passcode with the stored TOTP secret. + if twofa.VerifyScratchToken(form.Token) { + // Invalidate the scratch token. + _, err = twofa.GenerateScratchToken() + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + if err = auth.UpdateTwoFactor(twofa); err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + remember := ctx.Session.Get("twofaRemember").(bool) + u, err := user_model.GetUserByID(id) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + handleSignInFull(ctx, u, remember, false) + if ctx.Written() { + return + } + ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used")) + ctx.Redirect(setting.AppSubURL + "/user/settings/security") + return + } + + ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, forms.TwoFactorScratchAuthForm{}) +} diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go new file mode 100644 index 0000000000..b9765abfb5 --- /dev/null +++ b/routers/web/auth/auth.go @@ -0,0 +1,795 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Copyright 2018 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "fmt" + "net/http" + "strings" + + "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/eventsource" + "code.gitea.io/gitea/modules/hcaptcha" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/password" + "code.gitea.io/gitea/modules/recaptcha" + "code.gitea.io/gitea/modules/session" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/modules/web/middleware" + "code.gitea.io/gitea/routers/utils" + auth_service "code.gitea.io/gitea/services/auth" + "code.gitea.io/gitea/services/auth/source/oauth2" + "code.gitea.io/gitea/services/externalaccount" + "code.gitea.io/gitea/services/forms" + "code.gitea.io/gitea/services/mailer" + + "github.com/markbates/goth" +) + +const ( + // tplSignIn template for sign in page + tplSignIn base.TplName = "user/auth/signin" + // tplSignUp template path for sign up page + tplSignUp base.TplName = "user/auth/signup" + // TplActivate template path for activate user + TplActivate base.TplName = "user/auth/activate" +) + +// AutoSignIn reads cookie and try to auto-login. +func AutoSignIn(ctx *context.Context) (bool, error) { + if !db.HasEngine { + return false, nil + } + + uname := ctx.GetCookie(setting.CookieUserName) + if len(uname) == 0 { + return false, nil + } + + isSucceed := false + defer func() { + if !isSucceed { + log.Trace("auto-login cookie cleared: %s", uname) + ctx.DeleteCookie(setting.CookieUserName) + ctx.DeleteCookie(setting.CookieRememberName) + } + }() + + u, err := user_model.GetUserByName(uname) + if err != nil { + if !user_model.IsErrUserNotExist(err) { + return false, fmt.Errorf("GetUserByName: %v", err) + } + return false, nil + } + + if val, ok := ctx.GetSuperSecureCookie( + base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); !ok || val != u.Name { + return false, nil + } + + isSucceed = true + + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + return false, fmt.Errorf("unable to RegenerateSession: Error: %w", err) + } + + // Set session IDs + if err := ctx.Session.Set("uid", u.ID); err != nil { + return false, err + } + if err := ctx.Session.Set("uname", u.Name); err != nil { + return false, err + } + if err := ctx.Session.Release(); err != nil { + return false, err + } + + if err := resetLocale(ctx, u); err != nil { + return false, err + } + + middleware.DeleteCSRFCookie(ctx.Resp) + return true, nil +} + +func resetLocale(ctx *context.Context, u *user_model.User) error { + // Language setting of the user overwrites the one previously set + // If the user does not have a locale set, we save the current one. + if len(u.Language) == 0 { + u.Language = ctx.Locale.Language() + if err := user_model.UpdateUserCols(db.DefaultContext, u, "language"); err != nil { + return err + } + } + + middleware.SetLocaleCookie(ctx.Resp, u.Language, 0) + + if ctx.Locale.Language() != u.Language { + ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req) + } + + return nil +} + +func checkAutoLogin(ctx *context.Context) bool { + // Check auto-login + isSucceed, err := AutoSignIn(ctx) + if err != nil { + ctx.ServerError("AutoSignIn", err) + return true + } + + redirectTo := ctx.FormString("redirect_to") + if len(redirectTo) > 0 { + middleware.SetRedirectToCookie(ctx.Resp, redirectTo) + } else { + redirectTo = ctx.GetCookie("redirect_to") + } + + if isSucceed { + middleware.DeleteRedirectToCookie(ctx.Resp) + ctx.RedirectToFirst(redirectTo, setting.AppSubURL+string(setting.LandingPageURL)) + return true + } + + return false +} + +// SignIn render sign in page +func SignIn(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("sign_in") + + // Check auto-login + if checkAutoLogin(ctx) { + return + } + + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names + ctx.Data["OAuth2Providers"] = oauth2Providers + ctx.Data["Title"] = ctx.Tr("sign_in") + ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login" + ctx.Data["PageIsSignIn"] = true + ctx.Data["PageIsLogin"] = true + ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled() + + ctx.HTML(http.StatusOK, tplSignIn) +} + +// SignInPost response for sign in request +func SignInPost(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("sign_in") + + orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names + ctx.Data["OAuth2Providers"] = oauth2Providers + ctx.Data["Title"] = ctx.Tr("sign_in") + ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login" + ctx.Data["PageIsSignIn"] = true + ctx.Data["PageIsLogin"] = true + ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled() + + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplSignIn) + return + } + + form := web.GetForm(ctx).(*forms.SignInForm) + u, source, err := auth_service.UserSignIn(form.UserName, form.Password) + if err != nil { + if user_model.IsErrUserNotExist(err) { + ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form) + log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) + } else if user_model.IsErrEmailAlreadyUsed(err) { + ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignIn, &form) + log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) + } else if user_model.IsErrUserProhibitLogin(err) { + log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) + ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") + ctx.HTML(http.StatusOK, "user/auth/prohibit_login") + } else if user_model.IsErrUserInactive(err) { + if setting.Service.RegisterEmailConfirm { + ctx.Data["Title"] = ctx.Tr("auth.active_your_account") + ctx.HTML(http.StatusOK, TplActivate) + } else { + log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) + ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") + ctx.HTML(http.StatusOK, "user/auth/prohibit_login") + } + } else { + ctx.ServerError("UserSignIn", err) + } + return + } + + // Now handle 2FA: + + // First of all if the source can skip local two fa we're done + if skipper, ok := source.Cfg.(auth_service.LocalTwoFASkipper); ok && skipper.IsSkipLocalTwoFA() { + handleSignIn(ctx, u, form.Remember) + return + } + + // If this user is enrolled in 2FA TOTP, we can't sign the user in just yet. + // Instead, redirect them to the 2FA authentication page. + hasTOTPtwofa, err := auth.HasTwoFactorByUID(u.ID) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + // Check if the user has u2f registration + hasU2Ftwofa, err := auth.HasU2FRegistrationsByUID(u.ID) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + if !hasTOTPtwofa && !hasU2Ftwofa { + // No two factor auth configured we can sign in the user + handleSignIn(ctx, u, form.Remember) + return + } + + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + ctx.ServerError("UserSignIn: Unable to set regenerate session", err) + return + } + + // User will need to use 2FA TOTP or U2F, save data + if err := ctx.Session.Set("twofaUid", u.ID); err != nil { + ctx.ServerError("UserSignIn: Unable to set twofaUid in session", err) + return + } + + if err := ctx.Session.Set("twofaRemember", form.Remember); err != nil { + ctx.ServerError("UserSignIn: Unable to set twofaRemember in session", err) + return + } + + if hasTOTPtwofa { + // User will need to use U2F, save data + if err := ctx.Session.Set("totpEnrolled", u.ID); err != nil { + ctx.ServerError("UserSignIn: Unable to set u2fEnrolled in session", err) + return + } + } + + if err := ctx.Session.Release(); err != nil { + ctx.ServerError("UserSignIn: Unable to save session", err) + return + } + + // If we have U2F redirect there first + if hasU2Ftwofa { + ctx.Redirect(setting.AppSubURL + "/user/u2f") + return + } + + // Fallback to 2FA + ctx.Redirect(setting.AppSubURL + "/user/two_factor") +} + +// This handles the final part of the sign-in process of the user. +func handleSignIn(ctx *context.Context, u *user_model.User, remember bool) { + redirect := handleSignInFull(ctx, u, remember, true) + if ctx.Written() { + return + } + ctx.Redirect(redirect) +} + +func handleSignInFull(ctx *context.Context, u *user_model.User, remember bool, obeyRedirect bool) string { + if remember { + days := 86400 * setting.LogInRememberDays + ctx.SetCookie(setting.CookieUserName, u.Name, days) + ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd), + setting.CookieRememberName, u.Name, days) + } + + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + ctx.ServerError("RegenerateSession", err) + return setting.AppSubURL + "/" + } + + // Delete the openid, 2fa and linkaccount data + _ = ctx.Session.Delete("openid_verified_uri") + _ = ctx.Session.Delete("openid_signin_remember") + _ = ctx.Session.Delete("openid_determined_email") + _ = ctx.Session.Delete("openid_determined_username") + _ = ctx.Session.Delete("twofaUid") + _ = ctx.Session.Delete("twofaRemember") + _ = ctx.Session.Delete("u2fChallenge") + _ = ctx.Session.Delete("linkAccount") + if err := ctx.Session.Set("uid", u.ID); err != nil { + log.Error("Error setting uid %d in session: %v", u.ID, err) + } + if err := ctx.Session.Set("uname", u.Name); err != nil { + log.Error("Error setting uname %s session: %v", u.Name, err) + } + if err := ctx.Session.Release(); err != nil { + log.Error("Unable to store session: %v", err) + } + + // Language setting of the user overwrites the one previously set + // If the user does not have a locale set, we save the current one. + if len(u.Language) == 0 { + u.Language = ctx.Locale.Language() + if err := user_model.UpdateUserCols(db.DefaultContext, u, "language"); err != nil { + ctx.ServerError("UpdateUserCols Language", fmt.Errorf("Error updating user language [user: %d, locale: %s]", u.ID, u.Language)) + return setting.AppSubURL + "/" + } + } + + middleware.SetLocaleCookie(ctx.Resp, u.Language, 0) + + if ctx.Locale.Language() != u.Language { + ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req) + } + + // Clear whatever CSRF has right now, force to generate a new one + middleware.DeleteCSRFCookie(ctx.Resp) + + // Register last login + u.SetLastLogin() + if err := user_model.UpdateUserCols(db.DefaultContext, u, "last_login_unix"); err != nil { + ctx.ServerError("UpdateUserCols", err) + return setting.AppSubURL + "/" + } + + if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 && !utils.IsExternalURL(redirectTo) { + middleware.DeleteRedirectToCookie(ctx.Resp) + if obeyRedirect { + ctx.RedirectToFirst(redirectTo) + } + return redirectTo + } + + if obeyRedirect { + ctx.Redirect(setting.AppSubURL + "/") + } + return setting.AppSubURL + "/" +} + +func getUserName(gothUser *goth.User) string { + switch setting.OAuth2Client.Username { + case setting.OAuth2UsernameEmail: + return strings.Split(gothUser.Email, "@")[0] + case setting.OAuth2UsernameNickname: + return gothUser.NickName + default: // OAuth2UsernameUserid + return gothUser.UserID + } +} + +// HandleSignOut resets the session and sets the cookies +func HandleSignOut(ctx *context.Context) { + _ = ctx.Session.Flush() + _ = ctx.Session.Destroy(ctx.Resp, ctx.Req) + ctx.DeleteCookie(setting.CookieUserName) + ctx.DeleteCookie(setting.CookieRememberName) + middleware.DeleteCSRFCookie(ctx.Resp) + middleware.DeleteLocaleCookie(ctx.Resp) + middleware.DeleteRedirectToCookie(ctx.Resp) +} + +// SignOut sign out from login status +func SignOut(ctx *context.Context) { + if ctx.User != nil { + eventsource.GetManager().SendMessageBlocking(ctx.User.ID, &eventsource.Event{ + Name: "logout", + Data: ctx.Session.ID(), + }) + } + HandleSignOut(ctx) + ctx.Redirect(setting.AppSubURL + "/") +} + +// SignUp render the register page +func SignUp(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("sign_up") + + ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" + + ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha + ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL + ctx.Data["Captcha"] = context.GetImageCaptcha() + ctx.Data["CaptchaType"] = setting.Service.CaptchaType + ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey + ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey + ctx.Data["PageIsSignUp"] = true + + //Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true + ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration + + ctx.HTML(http.StatusOK, tplSignUp) +} + +// SignUpPost response for sign up information submission +func SignUpPost(ctx *context.Context) { + form := web.GetForm(ctx).(*forms.RegisterForm) + ctx.Data["Title"] = ctx.Tr("sign_up") + + ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" + + ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha + ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL + ctx.Data["Captcha"] = context.GetImageCaptcha() + ctx.Data["CaptchaType"] = setting.Service.CaptchaType + ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey + ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey + ctx.Data["PageIsSignUp"] = true + + //Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true + if setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration { + ctx.Error(http.StatusForbidden) + return + } + + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplSignUp) + return + } + + if setting.Service.EnableCaptcha { + var valid bool + var err error + switch setting.Service.CaptchaType { + case setting.ImageCaptcha: + valid = context.GetImageCaptcha().VerifyReq(ctx.Req) + case setting.ReCaptcha: + valid, err = recaptcha.Verify(ctx, form.GRecaptchaResponse) + case setting.HCaptcha: + valid, err = hcaptcha.Verify(ctx, form.HcaptchaResponse) + default: + ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType)) + return + } + if err != nil { + log.Debug("%s", err.Error()) + } + + if !valid { + ctx.Data["Err_Captcha"] = true + ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form) + return + } + } + + if !form.IsEmailDomainAllowed() { + ctx.RenderWithErr(ctx.Tr("auth.email_domain_blacklisted"), tplSignUp, &form) + return + } + + if form.Password != form.Retype { + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form) + return + } + if len(form.Password) < setting.MinPasswordLength { + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form) + return + } + if !password.IsComplexEnough(form.Password) { + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(password.BuildComplexityError(ctx), tplSignUp, &form) + return + } + pwned, err := password.IsPwned(ctx, form.Password) + if pwned { + errMsg := ctx.Tr("auth.password_pwned") + if err != nil { + log.Error(err.Error()) + errMsg = ctx.Tr("auth.password_pwned_err") + } + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(errMsg, tplSignUp, &form) + return + } + + u := &user_model.User{ + Name: form.UserName, + Email: form.Email, + Passwd: form.Password, + IsActive: !(setting.Service.RegisterEmailConfirm || setting.Service.RegisterManualConfirm), + IsRestricted: setting.Service.DefaultUserIsRestricted, + } + + if !createAndHandleCreatedUser(ctx, tplSignUp, form, u, nil, false) { + // error already handled + return + } + + ctx.Flash.Success(ctx.Tr("auth.sign_up_successful")) + handleSignIn(ctx, u, false) +} + +// createAndHandleCreatedUser calls createUserInContext and +// then handleUserCreated. +func createAndHandleCreatedUser(ctx *context.Context, tpl base.TplName, form interface{}, u *user_model.User, gothUser *goth.User, allowLink bool) bool { + if !createUserInContext(ctx, tpl, form, u, gothUser, allowLink) { + return false + } + return handleUserCreated(ctx, u, gothUser) +} + +// createUserInContext creates a user and handles errors within a given context. +// Optionally a template can be specified. +func createUserInContext(ctx *context.Context, tpl base.TplName, form interface{}, u *user_model.User, gothUser *goth.User, allowLink bool) (ok bool) { + if err := user_model.CreateUser(u); err != nil { + if allowLink && (user_model.IsErrUserAlreadyExist(err) || user_model.IsErrEmailAlreadyUsed(err)) { + if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingAuto { + var user *user_model.User + user = &user_model.User{Name: u.Name} + hasUser, err := user_model.GetUser(user) + if !hasUser || err != nil { + user = &user_model.User{Email: u.Email} + hasUser, err = user_model.GetUser(user) + if !hasUser || err != nil { + ctx.ServerError("UserLinkAccount", err) + return + } + } + + // TODO: probably we should respect 'remember' user's choice... + linkAccount(ctx, user, *gothUser, true) + return // user is already created here, all redirects are handled + } else if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingLogin { + showLinkingLogin(ctx, *gothUser) + return // user will be created only after linking login + } + } + + // handle error without template + if len(tpl) == 0 { + ctx.ServerError("CreateUser", err) + return + } + + // handle error with template + switch { + case user_model.IsErrUserAlreadyExist(err): + ctx.Data["Err_UserName"] = true + ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tpl, form) + case user_model.IsErrEmailAlreadyUsed(err): + ctx.Data["Err_Email"] = true + ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tpl, form) + case user_model.IsErrEmailInvalid(err): + ctx.Data["Err_Email"] = true + ctx.RenderWithErr(ctx.Tr("form.email_invalid"), tpl, form) + case db.IsErrNameReserved(err): + ctx.Data["Err_UserName"] = true + ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(db.ErrNameReserved).Name), tpl, form) + case db.IsErrNamePatternNotAllowed(err): + ctx.Data["Err_UserName"] = true + ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(db.ErrNamePatternNotAllowed).Pattern), tpl, form) + case db.IsErrNameCharsNotAllowed(err): + ctx.Data["Err_UserName"] = true + ctx.RenderWithErr(ctx.Tr("user.form.name_chars_not_allowed", err.(db.ErrNameCharsNotAllowed).Name), tpl, form) + default: + ctx.ServerError("CreateUser", err) + } + return + } + log.Trace("Account created: %s", u.Name) + return true +} + +// handleUserCreated does additional steps after a new user is created. +// It auto-sets admin for the only user, updates the optional external user and +// sends a confirmation email if required. +func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth.User) (ok bool) { + // Auto-set admin for the only user. + if user_model.CountUsers() == 1 { + u.IsAdmin = true + u.IsActive = true + u.SetLastLogin() + if err := user_model.UpdateUserCols(db.DefaultContext, u, "is_admin", "is_active", "last_login_unix"); err != nil { + ctx.ServerError("UpdateUser", err) + return + } + } + + // update external user information + if gothUser != nil { + if err := externalaccount.UpdateExternalUser(u, *gothUser); err != nil { + log.Error("UpdateExternalUser failed: %v", err) + } + } + + // Send confirmation email + if !u.IsActive && u.ID > 1 { + mailer.SendActivateAccountMail(ctx.Locale, u) + + ctx.Data["IsSendRegisterMail"] = true + ctx.Data["Email"] = u.Email + ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) + ctx.HTML(http.StatusOK, TplActivate) + + if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) + } + return + } + + return true +} + +// Activate render activate user page +func Activate(ctx *context.Context) { + code := ctx.FormString("code") + + if len(code) == 0 { + ctx.Data["IsActivatePage"] = true + if ctx.User == nil || ctx.User.IsActive { + ctx.NotFound("invalid user", nil) + return + } + // Resend confirmation email. + if setting.Service.RegisterEmailConfirm { + if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) { + ctx.Data["ResendLimited"] = true + } else { + ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) + mailer.SendActivateAccountMail(ctx.Locale, ctx.User) + + if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) + } + } + } else { + ctx.Data["ServiceNotEnabled"] = true + } + ctx.HTML(http.StatusOK, TplActivate) + return + } + + user := user_model.VerifyUserActiveCode(code) + // if code is wrong + if user == nil { + ctx.Data["IsActivateFailed"] = true + ctx.HTML(http.StatusOK, TplActivate) + return + } + + // if account is local account, verify password + if user.LoginSource == 0 { + ctx.Data["Code"] = code + ctx.Data["NeedsPassword"] = true + ctx.HTML(http.StatusOK, TplActivate) + return + } + + handleAccountActivation(ctx, user) +} + +// ActivatePost handles account activation with password check +func ActivatePost(ctx *context.Context) { + code := ctx.FormString("code") + if len(code) == 0 { + ctx.Redirect(setting.AppSubURL + "/user/activate") + return + } + + user := user_model.VerifyUserActiveCode(code) + // if code is wrong + if user == nil { + ctx.Data["IsActivateFailed"] = true + ctx.HTML(http.StatusOK, TplActivate) + return + } + + // if account is local account, verify password + if user.LoginSource == 0 { + password := ctx.FormString("password") + if len(password) == 0 { + ctx.Data["Code"] = code + ctx.Data["NeedsPassword"] = true + ctx.HTML(http.StatusOK, TplActivate) + return + } + if !user.ValidatePassword(password) { + ctx.Data["IsActivateFailed"] = true + ctx.HTML(http.StatusOK, TplActivate) + return + } + } + + handleAccountActivation(ctx, user) +} + +func handleAccountActivation(ctx *context.Context, user *user_model.User) { + user.IsActive = true + var err error + if user.Rands, err = user_model.GetUserSalt(); err != nil { + ctx.ServerError("UpdateUser", err) + return + } + if err := user_model.UpdateUserCols(db.DefaultContext, user, "is_active", "rands"); err != nil { + if user_model.IsErrUserNotExist(err) { + ctx.NotFound("UpdateUserCols", err) + } else { + ctx.ServerError("UpdateUser", err) + } + return + } + + if err := user_model.ActivateUserEmail(user.ID, user.Email, true); err != nil { + log.Error("Unable to activate email for user: %-v with email: %s: %v", user, user.Email, err) + ctx.ServerError("ActivateUserEmail", err) + return + } + + log.Trace("User activated: %s", user.Name) + + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + log.Error("Unable to regenerate session for user: %-v with email: %s: %v", user, user.Email, err) + ctx.ServerError("ActivateUserEmail", err) + return + } + + if err := ctx.Session.Set("uid", user.ID); err != nil { + log.Error("Error setting uid in session[%s]: %v", ctx.Session.ID(), err) + } + if err := ctx.Session.Set("uname", user.Name); err != nil { + log.Error("Error setting uname in session[%s]: %v", ctx.Session.ID(), err) + } + if err := ctx.Session.Release(); err != nil { + log.Error("Error storing session[%s]: %v", ctx.Session.ID(), err) + } + + if err := resetLocale(ctx, user); err != nil { + ctx.ServerError("resetLocale", err) + return + } + + ctx.Flash.Success(ctx.Tr("auth.account_activated")) + ctx.Redirect(setting.AppSubURL + "/") +} + +// ActivateEmail render the activate email page +func ActivateEmail(ctx *context.Context) { + code := ctx.FormString("code") + emailStr := ctx.FormString("email") + + // Verify code. + if email := user_model.VerifyActiveEmailCode(code, emailStr); email != nil { + if err := user_model.ActivateEmail(email); err != nil { + ctx.ServerError("ActivateEmail", err) + } + + log.Trace("Email activated: %s", email.Email) + ctx.Flash.Success(ctx.Tr("settings.add_email_success")) + + if u, err := user_model.GetUserByID(email.UID); err != nil { + log.Warn("GetUserByID: %d", email.UID) + } else { + // Allow user to validate more emails + _ = ctx.Cache.Delete("MailResendLimit_" + u.LowerName) + } + } + + // FIXME: e-mail verification does not require the user to be logged in, + // so this could be redirecting to the login page. + // Should users be logged in automatically here? (consider 2FA requirements, etc.) + ctx.Redirect(setting.AppSubURL + "/user/settings/account") +} diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go new file mode 100644 index 0000000000..9d5a6eb3f8 --- /dev/null +++ b/routers/web/auth/linkaccount.go @@ -0,0 +1,300 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "errors" + "fmt" + "net/http" + "strings" + + "code.gitea.io/gitea/models/auth" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/hcaptcha" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/recaptcha" + "code.gitea.io/gitea/modules/session" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/web" + auth_service "code.gitea.io/gitea/services/auth" + "code.gitea.io/gitea/services/externalaccount" + "code.gitea.io/gitea/services/forms" + + "github.com/markbates/goth" +) + +var ( + tplLinkAccount base.TplName = "user/auth/link_account" +) + +// LinkAccount shows the page where the user can decide to login or create a new account +func LinkAccount(ctx *context.Context) { + ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration + ctx.Data["Title"] = ctx.Tr("link_account") + ctx.Data["LinkAccountMode"] = true + ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha + ctx.Data["Captcha"] = context.GetImageCaptcha() + ctx.Data["CaptchaType"] = setting.Service.CaptchaType + ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL + ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey + ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey + ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration + ctx.Data["AllowOnlyInternalRegistration"] = setting.Service.AllowOnlyInternalRegistration + ctx.Data["ShowRegistrationButton"] = false + + // use this to set the right link into the signIn and signUp templates in the link_account template + ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin" + ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup" + + gothUser := ctx.Session.Get("linkAccountGothUser") + if gothUser == nil { + ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session")) + return + } + + gu, _ := gothUser.(goth.User) + uname := getUserName(&gu) + email := gu.Email + ctx.Data["user_name"] = uname + ctx.Data["email"] = email + + if len(email) != 0 { + u, err := user_model.GetUserByEmail(email) + if err != nil && !user_model.IsErrUserNotExist(err) { + ctx.ServerError("UserSignIn", err) + return + } + if u != nil { + ctx.Data["user_exists"] = true + } + } else if len(uname) != 0 { + u, err := user_model.GetUserByName(uname) + if err != nil && !user_model.IsErrUserNotExist(err) { + ctx.ServerError("UserSignIn", err) + return + } + if u != nil { + ctx.Data["user_exists"] = true + } + } + + ctx.HTML(http.StatusOK, tplLinkAccount) +} + +// LinkAccountPostSignIn handle the coupling of external account with another account using signIn +func LinkAccountPostSignIn(ctx *context.Context) { + signInForm := web.GetForm(ctx).(*forms.SignInForm) + ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration + ctx.Data["Title"] = ctx.Tr("link_account") + ctx.Data["LinkAccountMode"] = true + ctx.Data["LinkAccountModeSignIn"] = true + ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha + ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL + ctx.Data["Captcha"] = context.GetImageCaptcha() + ctx.Data["CaptchaType"] = setting.Service.CaptchaType + ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey + ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey + ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration + ctx.Data["ShowRegistrationButton"] = false + + // use this to set the right link into the signIn and signUp templates in the link_account template + ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin" + ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup" + + gothUser := ctx.Session.Get("linkAccountGothUser") + if gothUser == nil { + ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session")) + return + } + + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplLinkAccount) + return + } + + u, _, err := auth_service.UserSignIn(signInForm.UserName, signInForm.Password) + if err != nil { + if user_model.IsErrUserNotExist(err) { + ctx.Data["user_exists"] = true + ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplLinkAccount, &signInForm) + } else { + ctx.ServerError("UserLinkAccount", err) + } + return + } + + linkAccount(ctx, u, gothUser.(goth.User), signInForm.Remember) +} + +func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, remember bool) { + updateAvatarIfNeed(gothUser.AvatarURL, u) + + // If this user is enrolled in 2FA, we can't sign the user in just yet. + // Instead, redirect them to the 2FA authentication page. + // We deliberately ignore the skip local 2fa setting here because we are linking to a previous user here + _, err := auth.GetTwoFactorByUID(u.ID) + if err != nil { + if !auth.IsErrTwoFactorNotEnrolled(err) { + ctx.ServerError("UserLinkAccount", err) + return + } + + err = externalaccount.LinkAccountToUser(u, gothUser) + if err != nil { + ctx.ServerError("UserLinkAccount", err) + return + } + + handleSignIn(ctx, u, remember) + return + } + + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + ctx.ServerError("RegenerateSession", err) + return + } + + // User needs to use 2FA, save data and redirect to 2FA page. + if err := ctx.Session.Set("twofaUid", u.ID); err != nil { + log.Error("Error setting twofaUid in session: %v", err) + } + if err := ctx.Session.Set("twofaRemember", remember); err != nil { + log.Error("Error setting twofaRemember in session: %v", err) + } + if err := ctx.Session.Set("linkAccount", true); err != nil { + log.Error("Error setting linkAccount in session: %v", err) + } + if err := ctx.Session.Release(); err != nil { + log.Error("Error storing session: %v", err) + } + + // If U2F is enrolled -> Redirect to U2F instead + regs, err := auth.GetU2FRegistrationsByUID(u.ID) + if err == nil && len(regs) > 0 { + ctx.Redirect(setting.AppSubURL + "/user/u2f") + return + } + + ctx.Redirect(setting.AppSubURL + "/user/two_factor") +} + +// LinkAccountPostRegister handle the creation of a new account for an external account using signUp +func LinkAccountPostRegister(ctx *context.Context) { + form := web.GetForm(ctx).(*forms.RegisterForm) + // TODO Make insecure passwords optional for local accounts also, + // once email-based Second-Factor Auth is available + ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration + ctx.Data["Title"] = ctx.Tr("link_account") + ctx.Data["LinkAccountMode"] = true + ctx.Data["LinkAccountModeRegister"] = true + ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha + ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL + ctx.Data["Captcha"] = context.GetImageCaptcha() + ctx.Data["CaptchaType"] = setting.Service.CaptchaType + ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey + ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey + ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration + ctx.Data["ShowRegistrationButton"] = false + + // use this to set the right link into the signIn and signUp templates in the link_account template + ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin" + ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup" + + gothUserInterface := ctx.Session.Get("linkAccountGothUser") + if gothUserInterface == nil { + ctx.ServerError("UserSignUp", errors.New("not in LinkAccount session")) + return + } + gothUser, ok := gothUserInterface.(goth.User) + if !ok { + ctx.ServerError("UserSignUp", fmt.Errorf("session linkAccountGothUser type is %t but not goth.User", gothUserInterface)) + return + } + + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplLinkAccount) + return + } + + if setting.Service.DisableRegistration || setting.Service.AllowOnlyInternalRegistration { + ctx.Error(http.StatusForbidden) + return + } + + if setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha { + var valid bool + var err error + switch setting.Service.CaptchaType { + case setting.ImageCaptcha: + valid = context.GetImageCaptcha().VerifyReq(ctx.Req) + case setting.ReCaptcha: + valid, err = recaptcha.Verify(ctx, form.GRecaptchaResponse) + case setting.HCaptcha: + valid, err = hcaptcha.Verify(ctx, form.HcaptchaResponse) + default: + ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType)) + return + } + if err != nil { + log.Debug("%s", err.Error()) + } + + if !valid { + ctx.Data["Err_Captcha"] = true + ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form) + return + } + } + + if !form.IsEmailDomainAllowed() { + ctx.RenderWithErr(ctx.Tr("auth.email_domain_blacklisted"), tplLinkAccount, &form) + return + } + + if setting.Service.AllowOnlyExternalRegistration || !setting.Service.RequireExternalRegistrationPassword { + // In user_model.User an empty password is classed as not set, so we set form.Password to empty. + // Eventually the database should be changed to indicate "Second Factor"-enabled accounts + // (accounts that do not introduce the security vulnerabilities of a password). + // If a user decides to circumvent second-factor security, and purposefully create a password, + // they can still do so using the "Recover Account" option. + form.Password = "" + } else { + if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype { + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form) + return + } + if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength { + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form) + return + } + } + + authSource, err := auth.GetActiveOAuth2SourceByName(gothUser.Provider) + if err != nil { + ctx.ServerError("CreateUser", err) + return + } + + u := &user_model.User{ + Name: form.UserName, + Email: form.Email, + Passwd: form.Password, + IsActive: !(setting.Service.RegisterEmailConfirm || setting.Service.RegisterManualConfirm), + LoginType: auth.OAuth2, + LoginSource: authSource.ID, + LoginName: gothUser.UserID, + } + + if !createAndHandleCreatedUser(ctx, tplLinkAccount, form, u, &gothUser, false) { + // error already handled + return + } + + handleSignIn(ctx, u, false) +} diff --git a/routers/web/auth/main_test.go b/routers/web/auth/main_test.go new file mode 100644 index 0000000000..2b16f3c405 --- /dev/null +++ b/routers/web/auth/main_test.go @@ -0,0 +1,16 @@ +// Copyright 2018 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "path/filepath" + "testing" + + "code.gitea.io/gitea/models/unittest" +) + +func TestMain(m *testing.M) { + unittest.MainTest(m, filepath.Join("..", "..", "..")) +} diff --git a/routers/web/user/oauth.go b/routers/web/auth/oauth.go index 166420221d..9b22773d2f 100644 --- a/routers/web/user/oauth.go +++ b/routers/web/auth/oauth.go @@ -2,32 +2,40 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package user +package auth import ( "encoding/base64" + "errors" "fmt" "html" + "io" "net/http" "net/url" "strings" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/session" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/web" - "code.gitea.io/gitea/services/auth" + "code.gitea.io/gitea/modules/web/middleware" + auth_service "code.gitea.io/gitea/services/auth" "code.gitea.io/gitea/services/auth/source/oauth2" + "code.gitea.io/gitea/services/externalaccount" "code.gitea.io/gitea/services/forms" + user_service "code.gitea.io/gitea/services/user" "gitea.com/go-chi/binding" "github.com/golang-jwt/jwt" + "github.com/markbates/goth" ) const ( @@ -117,7 +125,7 @@ type AccessTokenResponse struct { IDToken string `json:"id_token,omitempty"` } -func newAccessTokenResponse(grant *login.OAuth2Grant, serverKey, clientKey oauth2.JWTSigningKey) (*AccessTokenResponse, *AccessTokenError) { +func newAccessTokenResponse(grant *auth.OAuth2Grant, serverKey, clientKey oauth2.JWTSigningKey) (*AccessTokenResponse, *AccessTokenError) { if setting.OAuth2.InvalidateRefreshTokens { if err := grant.IncreaseCounter(); err != nil { return nil, &AccessTokenError{ @@ -164,7 +172,7 @@ func newAccessTokenResponse(grant *login.OAuth2Grant, serverKey, clientKey oauth // generate OpenID Connect id_token signedIDToken := "" if grant.ScopeContains("openid") { - app, err := login.GetOAuth2ApplicationByID(grant.ApplicationID) + app, err := auth.GetOAuth2ApplicationByID(grant.ApplicationID) if err != nil { return nil, &AccessTokenError{ ErrorCode: AccessTokenErrorCodeInvalidRequest, @@ -249,7 +257,7 @@ type userInfoResponse struct { // InfoOAuth manages request for userinfo endpoint func InfoOAuth(ctx *context.Context) { - if ctx.User == nil || ctx.Data["AuthedMethod"] != (&auth.OAuth2{}).Name() { + if ctx.User == nil || ctx.Data["AuthedMethod"] != (&auth_service.OAuth2{}).Name() { ctx.Resp.Header().Set("WWW-Authenticate", `Bearer realm=""`) ctx.PlainText(http.StatusUnauthorized, "no valid authorization") return @@ -315,9 +323,9 @@ func IntrospectOAuth(ctx *context.Context) { token, err := oauth2.ParseToken(form.Token, oauth2.DefaultSigningKey) if err == nil { if token.Valid() == nil { - grant, err := login.GetOAuth2GrantByID(token.GrantID) + grant, err := auth.GetOAuth2GrantByID(token.GrantID) if err == nil && grant != nil { - app, err := login.GetOAuth2ApplicationByID(grant.ApplicationID) + app, err := auth.GetOAuth2ApplicationByID(grant.ApplicationID) if err == nil && app != nil { response.Active = true response.Scope = grant.Scope @@ -346,9 +354,9 @@ func AuthorizeOAuth(ctx *context.Context) { return } - app, err := login.GetOAuth2ApplicationByClientID(form.ClientID) + app, err := auth.GetOAuth2ApplicationByClientID(form.ClientID) if err != nil { - if login.IsErrOauthClientIDInvalid(err) { + if auth.IsErrOauthClientIDInvalid(err) { handleAuthorizeError(ctx, AuthorizeError{ ErrorCode: ErrorCodeUnauthorizedClient, ErrorDescription: "Client ID not registered", @@ -492,7 +500,7 @@ func GrantApplicationOAuth(ctx *context.Context) { ctx.Error(http.StatusBadRequest) return } - app, err := login.GetOAuth2ApplicationByClientID(form.ClientID) + app, err := auth.GetOAuth2ApplicationByClientID(form.ClientID) if err != nil { ctx.ServerError("GetOAuth2ApplicationByClientID", err) return @@ -630,7 +638,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server return } // get grant before increasing counter - grant, err := login.GetOAuth2GrantByID(token.GrantID) + grant, err := auth.GetOAuth2GrantByID(token.GrantID) if err != nil || grant == nil { handleAccessTokenError(ctx, AccessTokenError{ ErrorCode: AccessTokenErrorCodeInvalidGrant, @@ -657,7 +665,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server } func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, serverKey, clientKey oauth2.JWTSigningKey) { - app, err := login.GetOAuth2ApplicationByClientID(form.ClientID) + app, err := auth.GetOAuth2ApplicationByClientID(form.ClientID) if err != nil { handleAccessTokenError(ctx, AccessTokenError{ ErrorCode: AccessTokenErrorCodeInvalidClient, @@ -679,7 +687,7 @@ func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, s }) return } - authorizationCode, err := login.GetOAuth2AuthorizationByCode(form.Code) + authorizationCode, err := auth.GetOAuth2AuthorizationByCode(form.Code) if err != nil || authorizationCode == nil { handleAccessTokenError(ctx, AccessTokenError{ ErrorCode: AccessTokenErrorCodeUnauthorizedClient, @@ -750,3 +758,367 @@ func handleAuthorizeError(ctx *context.Context, authErr AuthorizeError, redirect redirect.RawQuery = q.Encode() ctx.Redirect(redirect.String(), 302) } + +// SignInOAuth handles the OAuth2 login buttons +func SignInOAuth(ctx *context.Context) { + provider := ctx.Params(":provider") + + authSource, err := auth.GetActiveOAuth2SourceByName(provider) + if err != nil { + ctx.ServerError("SignIn", err) + return + } + + // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user + user, gothUser, err := oAuth2UserLoginCallback(authSource, ctx.Req, ctx.Resp) + if err == nil && user != nil { + // we got the user without going through the whole OAuth2 authentication flow again + handleOAuth2SignIn(ctx, authSource, user, gothUser) + return + } + + if err = authSource.Cfg.(*oauth2.Source).Callout(ctx.Req, ctx.Resp); err != nil { + if strings.Contains(err.Error(), "no provider for ") { + if err = oauth2.ResetOAuth2(); err != nil { + ctx.ServerError("SignIn", err) + return + } + if err = authSource.Cfg.(*oauth2.Source).Callout(ctx.Req, ctx.Resp); err != nil { + ctx.ServerError("SignIn", err) + } + return + } + ctx.ServerError("SignIn", err) + } + // redirect is done in oauth2.Auth +} + +// SignInOAuthCallback handles the callback from the given provider +func SignInOAuthCallback(ctx *context.Context) { + provider := ctx.Params(":provider") + + // first look if the provider is still active + authSource, err := auth.GetActiveOAuth2SourceByName(provider) + if err != nil { + ctx.ServerError("SignIn", err) + return + } + + if authSource == nil { + ctx.ServerError("SignIn", errors.New("No valid provider found, check configured callback url in provider")) + return + } + + u, gothUser, err := oAuth2UserLoginCallback(authSource, ctx.Req, ctx.Resp) + + if err != nil { + if user_model.IsErrUserProhibitLogin(err) { + uplerr := err.(*user_model.ErrUserProhibitLogin) + log.Info("Failed authentication attempt for %s from %s: %v", uplerr.Name, ctx.RemoteAddr(), err) + ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") + ctx.HTML(http.StatusOK, "user/auth/prohibit_login") + return + } + ctx.ServerError("UserSignIn", err) + return + } + + if u == nil { + if !setting.Service.AllowOnlyInternalRegistration && setting.OAuth2Client.EnableAutoRegistration { + // create new user with details from oauth2 provider + var missingFields []string + if gothUser.UserID == "" { + missingFields = append(missingFields, "sub") + } + if gothUser.Email == "" { + missingFields = append(missingFields, "email") + } + if setting.OAuth2Client.Username == setting.OAuth2UsernameNickname && gothUser.NickName == "" { + missingFields = append(missingFields, "nickname") + } + if len(missingFields) > 0 { + log.Error("OAuth2 Provider %s returned empty or missing fields: %s", authSource.Name, missingFields) + if authSource.IsOAuth2() && authSource.Cfg.(*oauth2.Source).Provider == "openidConnect" { + log.Error("You may need to change the 'OPENID_CONNECT_SCOPES' setting to request all required fields") + } + err = fmt.Errorf("OAuth2 Provider %s returned empty or missing fields: %s", authSource.Name, missingFields) + ctx.ServerError("CreateUser", err) + return + } + u = &user_model.User{ + Name: getUserName(&gothUser), + FullName: gothUser.Name, + Email: gothUser.Email, + IsActive: !setting.OAuth2Client.RegisterEmailConfirm, + LoginType: auth.OAuth2, + LoginSource: authSource.ID, + LoginName: gothUser.UserID, + IsRestricted: setting.Service.DefaultUserIsRestricted, + } + + setUserGroupClaims(authSource, u, &gothUser) + + if !createAndHandleCreatedUser(ctx, base.TplName(""), nil, u, &gothUser, setting.OAuth2Client.AccountLinking != setting.OAuth2AccountLinkingDisabled) { + // error already handled + return + } + } else { + // no existing user is found, request attach or new account + showLinkingLogin(ctx, gothUser) + return + } + } + + handleOAuth2SignIn(ctx, authSource, u, gothUser) +} + +func claimValueToStringSlice(claimValue interface{}) []string { + var groups []string + + switch rawGroup := claimValue.(type) { + case []string: + groups = rawGroup + default: + str := fmt.Sprintf("%s", rawGroup) + groups = strings.Split(str, ",") + } + return groups +} + +func setUserGroupClaims(loginSource *auth.Source, u *user_model.User, gothUser *goth.User) bool { + source := loginSource.Cfg.(*oauth2.Source) + if source.GroupClaimName == "" || (source.AdminGroup == "" && source.RestrictedGroup == "") { + return false + } + + groupClaims, has := gothUser.RawData[source.GroupClaimName] + if !has { + return false + } + + groups := claimValueToStringSlice(groupClaims) + + wasAdmin, wasRestricted := u.IsAdmin, u.IsRestricted + + if source.AdminGroup != "" { + u.IsAdmin = false + } + if source.RestrictedGroup != "" { + u.IsRestricted = false + } + + for _, g := range groups { + if source.AdminGroup != "" && g == source.AdminGroup { + u.IsAdmin = true + } else if source.RestrictedGroup != "" && g == source.RestrictedGroup { + u.IsRestricted = true + } + } + + return wasAdmin != u.IsAdmin || wasRestricted != u.IsRestricted +} + +func showLinkingLogin(ctx *context.Context, gothUser goth.User) { + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + ctx.ServerError("RegenerateSession", err) + return + } + + if err := ctx.Session.Set("linkAccountGothUser", gothUser); err != nil { + log.Error("Error setting linkAccountGothUser in session: %v", err) + } + if err := ctx.Session.Release(); err != nil { + log.Error("Error storing session: %v", err) + } + ctx.Redirect(setting.AppSubURL + "/user/link_account") +} + +func updateAvatarIfNeed(url string, u *user_model.User) { + if setting.OAuth2Client.UpdateAvatar && len(url) > 0 { + resp, err := http.Get(url) + if err == nil { + defer func() { + _ = resp.Body.Close() + }() + } + // ignore any error + if err == nil && resp.StatusCode == http.StatusOK { + data, err := io.ReadAll(io.LimitReader(resp.Body, setting.Avatar.MaxFileSize+1)) + if err == nil && int64(len(data)) <= setting.Avatar.MaxFileSize { + _ = user_service.UploadAvatar(u, data) + } + } + } +} + +func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model.User, gothUser goth.User) { + updateAvatarIfNeed(gothUser.AvatarURL, u) + + needs2FA := false + if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA { + _, err := auth.GetTwoFactorByUID(u.ID) + if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { + ctx.ServerError("UserSignIn", err) + return + } + needs2FA = err == nil + } + + // If this user is enrolled in 2FA and this source doesn't override it, + // we can't sign the user in just yet. Instead, redirect them to the 2FA authentication page. + if !needs2FA { + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + ctx.ServerError("RegenerateSession", err) + return + } + + if err := ctx.Session.Set("uid", u.ID); err != nil { + log.Error("Error setting uid in session: %v", err) + } + if err := ctx.Session.Set("uname", u.Name); err != nil { + log.Error("Error setting uname in session: %v", err) + } + if err := ctx.Session.Release(); err != nil { + log.Error("Error storing session: %v", err) + } + + // Clear whatever CSRF has right now, force to generate a new one + middleware.DeleteCSRFCookie(ctx.Resp) + + // Register last login + u.SetLastLogin() + + // Update GroupClaims + changed := setUserGroupClaims(source, u, &gothUser) + cols := []string{"last_login_unix"} + if changed { + cols = append(cols, "is_admin", "is_restricted") + } + + if err := user_model.UpdateUserCols(db.DefaultContext, u, cols...); err != nil { + ctx.ServerError("UpdateUserCols", err) + return + } + + // update external user information + if err := externalaccount.UpdateExternalUser(u, gothUser); err != nil { + log.Error("UpdateExternalUser failed: %v", err) + } + + if err := resetLocale(ctx, u); err != nil { + ctx.ServerError("resetLocale", err) + return + } + + if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 { + middleware.DeleteRedirectToCookie(ctx.Resp) + ctx.RedirectToFirst(redirectTo) + return + } + + ctx.Redirect(setting.AppSubURL + "/") + return + } + + changed := setUserGroupClaims(source, u, &gothUser) + if changed { + if err := user_model.UpdateUserCols(db.DefaultContext, u, "is_admin", "is_restricted"); err != nil { + ctx.ServerError("UpdateUserCols", err) + return + } + } + + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + ctx.ServerError("RegenerateSession", err) + return + } + + // User needs to use 2FA, save data and redirect to 2FA page. + if err := ctx.Session.Set("twofaUid", u.ID); err != nil { + log.Error("Error setting twofaUid in session: %v", err) + } + if err := ctx.Session.Set("twofaRemember", false); err != nil { + log.Error("Error setting twofaRemember in session: %v", err) + } + if err := ctx.Session.Release(); err != nil { + log.Error("Error storing session: %v", err) + } + + // If U2F is enrolled -> Redirect to U2F instead + regs, err := auth.GetU2FRegistrationsByUID(u.ID) + if err == nil && len(regs) > 0 { + ctx.Redirect(setting.AppSubURL + "/user/u2f") + return + } + + ctx.Redirect(setting.AppSubURL + "/user/two_factor") +} + +// OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful +// login the user +func oAuth2UserLoginCallback(authSource *auth.Source, request *http.Request, response http.ResponseWriter) (*user_model.User, goth.User, error) { + oauth2Source := authSource.Cfg.(*oauth2.Source) + + gothUser, err := oauth2Source.Callback(request, response) + if err != nil { + if err.Error() == "securecookie: the value is too long" || strings.Contains(err.Error(), "Data too long") { + log.Error("OAuth2 Provider %s returned too long a token. Current max: %d. Either increase the [OAuth2] MAX_TOKEN_LENGTH or reduce the information returned from the OAuth2 provider", authSource.Name, setting.OAuth2.MaxTokenLength) + err = fmt.Errorf("OAuth2 Provider %s returned too long a token. Current max: %d. Either increase the [OAuth2] MAX_TOKEN_LENGTH or reduce the information returned from the OAuth2 provider", authSource.Name, setting.OAuth2.MaxTokenLength) + } + return nil, goth.User{}, err + } + + if oauth2Source.RequiredClaimName != "" { + claimInterface, has := gothUser.RawData[oauth2Source.RequiredClaimName] + if !has { + return nil, goth.User{}, user_model.ErrUserProhibitLogin{Name: gothUser.UserID} + } + + if oauth2Source.RequiredClaimValue != "" { + groups := claimValueToStringSlice(claimInterface) + found := false + for _, group := range groups { + if group == oauth2Source.RequiredClaimValue { + found = true + break + } + } + if !found { + return nil, goth.User{}, user_model.ErrUserProhibitLogin{Name: gothUser.UserID} + } + } + } + + user := &user_model.User{ + LoginName: gothUser.UserID, + LoginType: auth.OAuth2, + LoginSource: authSource.ID, + } + + hasUser, err := user_model.GetUser(user) + if err != nil { + return nil, goth.User{}, err + } + + if hasUser { + return user, gothUser, nil + } + + // search in external linked users + externalLoginUser := &user_model.ExternalLoginUser{ + ExternalID: gothUser.UserID, + LoginSourceID: authSource.ID, + } + hasUser, err = user_model.GetExternalLogin(externalLoginUser) + if err != nil { + return nil, goth.User{}, err + } + if hasUser { + user, err = user_model.GetUserByID(externalLoginUser.UserID) + return user, gothUser, err + } + + // no user found to login + return nil, gothUser, nil + +} diff --git a/routers/web/user/oauth_test.go b/routers/web/auth/oauth_test.go index e26a42b2fc..c652d901f3 100644 --- a/routers/web/user/oauth_test.go +++ b/routers/web/auth/oauth_test.go @@ -2,12 +2,12 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package user +package auth import ( "testing" - "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/services/auth/source/oauth2" @@ -16,7 +16,7 @@ import ( "github.com/stretchr/testify/assert" ) -func createAndParseToken(t *testing.T, grant *login.OAuth2Grant) *oauth2.OIDCToken { +func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2.OIDCToken { signingKey, err := oauth2.CreateJWTSigningKey("HS256", make([]byte, 32)) assert.NoError(t, err) assert.NotNil(t, signingKey) @@ -43,7 +43,7 @@ func createAndParseToken(t *testing.T, grant *login.OAuth2Grant) *oauth2.OIDCTok func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - grants, err := login.GetOAuth2GrantsByUserID(3) + grants, err := auth.GetOAuth2GrantsByUserID(3) assert.NoError(t, err) assert.Len(t, grants, 1) @@ -59,7 +59,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { assert.False(t, oidcToken.EmailVerified) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}).(*user_model.User) - grants, err = login.GetOAuth2GrantsByUserID(user.ID) + grants, err = auth.GetOAuth2GrantsByUserID(user.ID) assert.NoError(t, err) assert.Len(t, grants, 1) diff --git a/routers/web/user/auth_openid.go b/routers/web/auth/openid.go index 55dd8f8d09..4395641795 100644 --- a/routers/web/user/auth_openid.go +++ b/routers/web/auth/openid.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package user +package auth import ( "fmt" diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go new file mode 100644 index 0000000000..65d5c55976 --- /dev/null +++ b/routers/web/auth/password.go @@ -0,0 +1,346 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "errors" + "net/http" + + "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/password" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/modules/web/middleware" + "code.gitea.io/gitea/routers/utils" + "code.gitea.io/gitea/services/forms" + "code.gitea.io/gitea/services/mailer" +) + +var ( + // tplMustChangePassword template for updating a user's password + tplMustChangePassword base.TplName = "user/auth/change_passwd" + tplForgotPassword base.TplName = "user/auth/forgot_passwd" + tplResetPassword base.TplName = "user/auth/reset_passwd" +) + +// ForgotPasswd render the forget password page +func ForgotPasswd(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title") + + if setting.MailService == nil { + log.Warn(ctx.Tr("auth.disable_forgot_password_mail_admin")) + ctx.Data["IsResetDisable"] = true + ctx.HTML(http.StatusOK, tplForgotPassword) + return + } + + ctx.Data["Email"] = ctx.FormString("email") + + ctx.Data["IsResetRequest"] = true + ctx.HTML(http.StatusOK, tplForgotPassword) +} + +// ForgotPasswdPost response for forget password request +func ForgotPasswdPost(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title") + + if setting.MailService == nil { + ctx.NotFound("ForgotPasswdPost", nil) + return + } + ctx.Data["IsResetRequest"] = true + + email := ctx.FormString("email") + ctx.Data["Email"] = email + + u, err := user_model.GetUserByEmail(email) + if err != nil { + if user_model.IsErrUserNotExist(err) { + ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) + ctx.Data["IsResetSent"] = true + ctx.HTML(http.StatusOK, tplForgotPassword) + return + } + + ctx.ServerError("user.ResetPasswd(check existence)", err) + return + } + + if !u.IsLocal() && !u.IsOAuth2() { + ctx.Data["Err_Email"] = true + ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil) + return + } + + if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) { + ctx.Data["ResendLimited"] = true + ctx.HTML(http.StatusOK, tplForgotPassword) + return + } + + mailer.SendResetPasswordMail(u) + + if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) + } + + ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) + ctx.Data["IsResetSent"] = true + ctx.HTML(http.StatusOK, tplForgotPassword) +} + +func commonResetPassword(ctx *context.Context) (*user_model.User, *auth.TwoFactor) { + code := ctx.FormString("code") + + ctx.Data["Title"] = ctx.Tr("auth.reset_password") + ctx.Data["Code"] = code + + if nil != ctx.User { + ctx.Data["user_signed_in"] = true + } + + if len(code) == 0 { + ctx.Flash.Error(ctx.Tr("auth.invalid_code")) + return nil, nil + } + + // Fail early, don't frustrate the user + u := user_model.VerifyUserActiveCode(code) + if u == nil { + ctx.Flash.Error(ctx.Tr("auth.invalid_code")) + return nil, nil + } + + twofa, err := auth.GetTwoFactorByUID(u.ID) + if err != nil { + if !auth.IsErrTwoFactorNotEnrolled(err) { + ctx.Error(http.StatusInternalServerError, "CommonResetPassword", err.Error()) + return nil, nil + } + } else { + ctx.Data["has_two_factor"] = true + ctx.Data["scratch_code"] = ctx.FormBool("scratch_code") + } + + // Show the user that they are affecting the account that they intended to + ctx.Data["user_email"] = u.Email + + if nil != ctx.User && u.ID != ctx.User.ID { + ctx.Flash.Error(ctx.Tr("auth.reset_password_wrong_user", ctx.User.Email, u.Email)) + return nil, nil + } + + return u, twofa +} + +// ResetPasswd render the account recovery page +func ResetPasswd(ctx *context.Context) { + ctx.Data["IsResetForm"] = true + + commonResetPassword(ctx) + if ctx.Written() { + return + } + + ctx.HTML(http.StatusOK, tplResetPassword) +} + +// ResetPasswdPost response from account recovery request +func ResetPasswdPost(ctx *context.Context) { + u, twofa := commonResetPassword(ctx) + if ctx.Written() { + return + } + + if u == nil { + // Flash error has been set + ctx.HTML(http.StatusOK, tplResetPassword) + return + } + + // Validate password length. + passwd := ctx.FormString("password") + if len(passwd) < setting.MinPasswordLength { + ctx.Data["IsResetForm"] = true + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil) + return + } else if !password.IsComplexEnough(passwd) { + ctx.Data["IsResetForm"] = true + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(password.BuildComplexityError(ctx), tplResetPassword, nil) + return + } else if pwned, err := password.IsPwned(ctx, passwd); pwned || err != nil { + errMsg := ctx.Tr("auth.password_pwned") + if err != nil { + log.Error(err.Error()) + errMsg = ctx.Tr("auth.password_pwned_err") + } + ctx.Data["IsResetForm"] = true + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(errMsg, tplResetPassword, nil) + return + } + + // Handle two-factor + regenerateScratchToken := false + if twofa != nil { + if ctx.FormBool("scratch_code") { + if !twofa.VerifyScratchToken(ctx.FormString("token")) { + ctx.Data["IsResetForm"] = true + ctx.Data["Err_Token"] = true + ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplResetPassword, nil) + return + } + regenerateScratchToken = true + } else { + passcode := ctx.FormString("passcode") + ok, err := twofa.ValidateTOTP(passcode) + if err != nil { + ctx.Error(http.StatusInternalServerError, "ValidateTOTP", err.Error()) + return + } + if !ok || twofa.LastUsedPasscode == passcode { + ctx.Data["IsResetForm"] = true + ctx.Data["Err_Passcode"] = true + ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplResetPassword, nil) + return + } + + twofa.LastUsedPasscode = passcode + if err = auth.UpdateTwoFactor(twofa); err != nil { + ctx.ServerError("ResetPasswdPost: UpdateTwoFactor", err) + return + } + } + } + var err error + if u.Rands, err = user_model.GetUserSalt(); err != nil { + ctx.ServerError("UpdateUser", err) + return + } + if err = u.SetPassword(passwd); err != nil { + ctx.ServerError("UpdateUser", err) + return + } + u.MustChangePassword = false + if err := user_model.UpdateUserCols(db.DefaultContext, u, "must_change_password", "passwd", "passwd_hash_algo", "rands", "salt"); err != nil { + ctx.ServerError("UpdateUser", err) + return + } + + log.Trace("User password reset: %s", u.Name) + ctx.Data["IsResetFailed"] = true + remember := len(ctx.FormString("remember")) != 0 + + if regenerateScratchToken { + // Invalidate the scratch token. + _, err = twofa.GenerateScratchToken() + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + if err = auth.UpdateTwoFactor(twofa); err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + handleSignInFull(ctx, u, remember, false) + if ctx.Written() { + return + } + ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used")) + ctx.Redirect(setting.AppSubURL + "/user/settings/security") + return + } + + handleSignIn(ctx, u, remember) +} + +// MustChangePassword renders the page to change a user's password +func MustChangePassword(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("auth.must_change_password") + ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password" + ctx.Data["MustChangePassword"] = true + ctx.HTML(http.StatusOK, tplMustChangePassword) +} + +// MustChangePasswordPost response for updating a user's password after his/her +// account was created by an admin +func MustChangePasswordPost(ctx *context.Context) { + form := web.GetForm(ctx).(*forms.MustChangePasswordForm) + ctx.Data["Title"] = ctx.Tr("auth.must_change_password") + ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password" + if ctx.HasError() { + ctx.HTML(http.StatusOK, tplMustChangePassword) + return + } + u := ctx.User + // Make sure only requests for users who are eligible to change their password via + // this method passes through + if !u.MustChangePassword { + ctx.ServerError("MustUpdatePassword", errors.New("cannot update password.. Please visit the settings page")) + return + } + + if form.Password != form.Retype { + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplMustChangePassword, &form) + return + } + + if len(form.Password) < setting.MinPasswordLength { + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplMustChangePassword, &form) + return + } + + if !password.IsComplexEnough(form.Password) { + ctx.Data["Err_Password"] = true + ctx.RenderWithErr(password.BuildComplexityError(ctx), tplMustChangePassword, &form) + return + } + pwned, err := password.IsPwned(ctx, form.Password) + if pwned { + ctx.Data["Err_Password"] = true + errMsg := ctx.Tr("auth.password_pwned") + if err != nil { + log.Error(err.Error()) + errMsg = ctx.Tr("auth.password_pwned_err") + } + ctx.RenderWithErr(errMsg, tplMustChangePassword, &form) + return + } + + if err = u.SetPassword(form.Password); err != nil { + ctx.ServerError("UpdateUser", err) + return + } + + u.MustChangePassword = false + + if err := user_model.UpdateUserCols(db.DefaultContext, u, "must_change_password", "passwd", "passwd_hash_algo", "salt"); err != nil { + ctx.ServerError("UpdateUser", err) + return + } + + ctx.Flash.Success(ctx.Tr("settings.change_password_success")) + + log.Trace("User updated password: %s", u.Name) + + if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 && !utils.IsExternalURL(redirectTo) { + middleware.DeleteRedirectToCookie(ctx.Resp) + ctx.RedirectToFirst(redirectTo) + return + } + + ctx.Redirect(setting.AppSubURL + "/") +} diff --git a/routers/web/auth/u2f.go b/routers/web/auth/u2f.go new file mode 100644 index 0000000000..915671cd1e --- /dev/null +++ b/routers/web/auth/u2f.go @@ -0,0 +1,136 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "errors" + "net/http" + + "code.gitea.io/gitea/models/auth" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/services/externalaccount" + + "github.com/tstranex/u2f" +) + +var tplU2F base.TplName = "user/auth/u2f" + +// U2F shows the U2F login page +func U2F(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("twofa") + ctx.Data["RequireU2F"] = true + // Check auto-login. + if checkAutoLogin(ctx) { + return + } + + // Ensure user is in a 2FA session. + if ctx.Session.Get("twofaUid") == nil { + ctx.ServerError("UserSignIn", errors.New("not in U2F session")) + return + } + + // See whether TOTP is also available. + if ctx.Session.Get("totpEnrolled") != nil { + ctx.Data["TOTPEnrolled"] = true + } + + ctx.HTML(http.StatusOK, tplU2F) +} + +// U2FChallenge submits a sign challenge to the browser +func U2FChallenge(ctx *context.Context) { + // Ensure user is in a U2F session. + idSess := ctx.Session.Get("twofaUid") + if idSess == nil { + ctx.ServerError("UserSignIn", errors.New("not in U2F session")) + return + } + id := idSess.(int64) + regs, err := auth.GetU2FRegistrationsByUID(id) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + if len(regs) == 0 { + ctx.ServerError("UserSignIn", errors.New("no device registered")) + return + } + challenge, err := u2f.NewChallenge(setting.U2F.AppID, setting.U2F.TrustedFacets) + if err != nil { + ctx.ServerError("u2f.NewChallenge", err) + return + } + if err := ctx.Session.Set("u2fChallenge", challenge); err != nil { + ctx.ServerError("UserSignIn: unable to set u2fChallenge in session", err) + return + } + if err := ctx.Session.Release(); err != nil { + ctx.ServerError("UserSignIn: unable to store session", err) + } + + ctx.JSON(http.StatusOK, challenge.SignRequest(regs.ToRegistrations())) +} + +// U2FSign authenticates the user by signResp +func U2FSign(ctx *context.Context) { + signResp := web.GetForm(ctx).(*u2f.SignResponse) + challSess := ctx.Session.Get("u2fChallenge") + idSess := ctx.Session.Get("twofaUid") + if challSess == nil || idSess == nil { + ctx.ServerError("UserSignIn", errors.New("not in U2F session")) + return + } + challenge := challSess.(*u2f.Challenge) + id := idSess.(int64) + regs, err := auth.GetU2FRegistrationsByUID(id) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + for _, reg := range regs { + r, err := reg.Parse() + if err != nil { + log.Error("parsing u2f registration: %v", err) + continue + } + newCounter, authErr := r.Authenticate(*signResp, *challenge, reg.Counter) + if authErr == nil { + reg.Counter = newCounter + user, err := user_model.GetUserByID(id) + if err != nil { + ctx.ServerError("UserSignIn", err) + return + } + remember := ctx.Session.Get("twofaRemember").(bool) + if err := reg.UpdateCounter(); err != nil { + ctx.ServerError("UserSignIn", err) + return + } + + if ctx.Session.Get("linkAccount") != nil { + if err := externalaccount.LinkAccountFromStore(ctx.Session, user); err != nil { + ctx.ServerError("UserSignIn", err) + return + } + } + redirect := handleSignInFull(ctx, user, remember, false) + if ctx.Written() { + return + } + if redirect == "" { + redirect = setting.AppSubURL + "/" + } + ctx.PlainText(http.StatusOK, redirect) + return + } + } + ctx.Error(http.StatusUnauthorized) +} diff --git a/routers/web/events/events.go b/routers/web/events/events.go index 974aa755d1..41f52375c3 100644 --- a/routers/web/events/events.go +++ b/routers/web/events/events.go @@ -17,7 +17,7 @@ import ( "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/routers/web/user" + "code.gitea.io/gitea/routers/web/auth" ) // Events listens for events @@ -133,7 +133,7 @@ loop: }).WriteTo(ctx.Resp) ctx.Resp.Flush() go unregister() - user.HandleSignOut(ctx) + auth.HandleSignOut(ctx) break loop } // Replace the event - we don't want to expose the session ID to the user diff --git a/routers/web/home.go b/routers/web/home.go index f50197691f..ed81d84c7f 100644 --- a/routers/web/home.go +++ b/routers/web/home.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/web/middleware" + "code.gitea.io/gitea/routers/web/auth" "code.gitea.io/gitea/routers/web/user" ) @@ -26,7 +27,7 @@ func Home(ctx *context.Context) { if ctx.IsSigned { if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { ctx.Data["Title"] = ctx.Tr("auth.active_your_account") - ctx.HTML(http.StatusOK, user.TplActivate) + ctx.HTML(http.StatusOK, auth.TplActivate) } else if !ctx.User.IsActive || ctx.User.ProhibitLogin { log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr()) ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index 64e617dc4a..6ebf6a789a 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -20,8 +20,8 @@ import ( "time" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" - "code.gitea.io/gitea/models/login" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" @@ -179,12 +179,12 @@ func httpBase(ctx *context.Context) (h *serviceHandler) { } if ctx.IsBasicAuth && ctx.Data["IsApiToken"] != true { - _, err = login.GetTwoFactorByUID(ctx.User.ID) + _, err = auth.GetTwoFactorByUID(ctx.User.ID) if err == nil { // TODO: This response should be changed to "invalid credentials" for security reasons once the expectation behind it (creating an app token to authenticate) is properly documented ctx.PlainText(http.StatusUnauthorized, "Users with two-factor authentication enabled cannot perform HTTP/HTTPS operations via plain username and password. Please create and use a personal access token on the user settings page") return - } else if !login.IsErrTwoFactorNotEnrolled(err) { + } else if !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("IsErrTwoFactorNotEnrolled", err) return } diff --git a/routers/web/user/auth.go b/routers/web/user/auth.go deleted file mode 100644 index 356a907859..0000000000 --- a/routers/web/user/auth.go +++ /dev/null @@ -1,2006 +0,0 @@ -// Copyright 2014 The Gogs Authors. All rights reserved. -// Copyright 2018 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package user - -import ( - "errors" - "fmt" - "io" - "net/http" - "strings" - - "code.gitea.io/gitea/models/db" - "code.gitea.io/gitea/models/login" - user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/base" - "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/eventsource" - "code.gitea.io/gitea/modules/hcaptcha" - "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/password" - "code.gitea.io/gitea/modules/recaptcha" - "code.gitea.io/gitea/modules/session" - "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/timeutil" - "code.gitea.io/gitea/modules/web" - "code.gitea.io/gitea/modules/web/middleware" - "code.gitea.io/gitea/routers/utils" - "code.gitea.io/gitea/services/auth" - "code.gitea.io/gitea/services/auth/source/oauth2" - "code.gitea.io/gitea/services/externalaccount" - "code.gitea.io/gitea/services/forms" - "code.gitea.io/gitea/services/mailer" - user_service "code.gitea.io/gitea/services/user" - - "github.com/markbates/goth" - "github.com/tstranex/u2f" -) - -const ( - // tplMustChangePassword template for updating a user's password - tplMustChangePassword = "user/auth/change_passwd" - // tplSignIn template for sign in page - tplSignIn base.TplName = "user/auth/signin" - // tplSignUp template path for sign up page - tplSignUp base.TplName = "user/auth/signup" - // TplActivate template path for activate user - TplActivate base.TplName = "user/auth/activate" - tplForgotPassword base.TplName = "user/auth/forgot_passwd" - tplResetPassword base.TplName = "user/auth/reset_passwd" - tplTwofa base.TplName = "user/auth/twofa" - tplTwofaScratch base.TplName = "user/auth/twofa_scratch" - tplLinkAccount base.TplName = "user/auth/link_account" - tplU2F base.TplName = "user/auth/u2f" -) - -// AutoSignIn reads cookie and try to auto-login. -func AutoSignIn(ctx *context.Context) (bool, error) { - if !db.HasEngine { - return false, nil - } - - uname := ctx.GetCookie(setting.CookieUserName) - if len(uname) == 0 { - return false, nil - } - - isSucceed := false - defer func() { - if !isSucceed { - log.Trace("auto-login cookie cleared: %s", uname) - ctx.DeleteCookie(setting.CookieUserName) - ctx.DeleteCookie(setting.CookieRememberName) - } - }() - - u, err := user_model.GetUserByName(uname) - if err != nil { - if !user_model.IsErrUserNotExist(err) { - return false, fmt.Errorf("GetUserByName: %v", err) - } - return false, nil - } - - if val, ok := ctx.GetSuperSecureCookie( - base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); !ok || val != u.Name { - return false, nil - } - - isSucceed = true - - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - return false, fmt.Errorf("unable to RegenerateSession: Error: %w", err) - } - - // Set session IDs - if err := ctx.Session.Set("uid", u.ID); err != nil { - return false, err - } - if err := ctx.Session.Set("uname", u.Name); err != nil { - return false, err - } - if err := ctx.Session.Release(); err != nil { - return false, err - } - - if err := resetLocale(ctx, u); err != nil { - return false, err - } - - middleware.DeleteCSRFCookie(ctx.Resp) - return true, nil -} - -func resetLocale(ctx *context.Context, u *user_model.User) error { - // Language setting of the user overwrites the one previously set - // If the user does not have a locale set, we save the current one. - if len(u.Language) == 0 { - u.Language = ctx.Locale.Language() - if err := user_model.UpdateUserCols(db.DefaultContext, u, "language"); err != nil { - return err - } - } - - middleware.SetLocaleCookie(ctx.Resp, u.Language, 0) - - if ctx.Locale.Language() != u.Language { - ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req) - } - - return nil -} - -func checkAutoLogin(ctx *context.Context) bool { - // Check auto-login. - isSucceed, err := AutoSignIn(ctx) - if err != nil { - ctx.ServerError("AutoSignIn", err) - return true - } - - redirectTo := ctx.FormString("redirect_to") - if len(redirectTo) > 0 { - middleware.SetRedirectToCookie(ctx.Resp, redirectTo) - } else { - redirectTo = ctx.GetCookie("redirect_to") - } - - if isSucceed { - middleware.DeleteRedirectToCookie(ctx.Resp) - ctx.RedirectToFirst(redirectTo, setting.AppSubURL+string(setting.LandingPageURL)) - return true - } - - return false -} - -// SignIn render sign in page -func SignIn(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("sign_in") - - // Check auto-login. - if checkAutoLogin(ctx) { - return - } - - orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names - ctx.Data["OAuth2Providers"] = oauth2Providers - ctx.Data["Title"] = ctx.Tr("sign_in") - ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login" - ctx.Data["PageIsSignIn"] = true - ctx.Data["PageIsLogin"] = true - ctx.Data["EnableSSPI"] = login.IsSSPIEnabled() - - ctx.HTML(http.StatusOK, tplSignIn) -} - -// SignInPost response for sign in request -func SignInPost(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("sign_in") - - orderedOAuth2Names, oauth2Providers, err := oauth2.GetActiveOAuth2Providers() - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names - ctx.Data["OAuth2Providers"] = oauth2Providers - ctx.Data["Title"] = ctx.Tr("sign_in") - ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login" - ctx.Data["PageIsSignIn"] = true - ctx.Data["PageIsLogin"] = true - ctx.Data["EnableSSPI"] = login.IsSSPIEnabled() - - if ctx.HasError() { - ctx.HTML(http.StatusOK, tplSignIn) - return - } - - form := web.GetForm(ctx).(*forms.SignInForm) - u, source, err := auth.UserSignIn(form.UserName, form.Password) - if err != nil { - if user_model.IsErrUserNotExist(err) { - ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form) - log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) - } else if user_model.IsErrEmailAlreadyUsed(err) { - ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignIn, &form) - log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) - } else if user_model.IsErrUserProhibitLogin(err) { - log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) - ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") - ctx.HTML(http.StatusOK, "user/auth/prohibit_login") - } else if user_model.IsErrUserInactive(err) { - if setting.Service.RegisterEmailConfirm { - ctx.Data["Title"] = ctx.Tr("auth.active_your_account") - ctx.HTML(http.StatusOK, TplActivate) - } else { - log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err) - ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") - ctx.HTML(http.StatusOK, "user/auth/prohibit_login") - } - } else { - ctx.ServerError("UserSignIn", err) - } - return - } - - // Now handle 2FA: - - // First of all if the source can skip local two fa we're done - if skipper, ok := source.Cfg.(auth.LocalTwoFASkipper); ok && skipper.IsSkipLocalTwoFA() { - handleSignIn(ctx, u, form.Remember) - return - } - - // If this user is enrolled in 2FA TOTP, we can't sign the user in just yet. - // Instead, redirect them to the 2FA authentication page. - hasTOTPtwofa, err := login.HasTwoFactorByUID(u.ID) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - // Check if the user has u2f registration - hasU2Ftwofa, err := login.HasU2FRegistrationsByUID(u.ID) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - if !hasTOTPtwofa && !hasU2Ftwofa { - // No two factor auth configured we can sign in the user - handleSignIn(ctx, u, form.Remember) - return - } - - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("UserSignIn: Unable to set regenerate session", err) - return - } - - // User will need to use 2FA TOTP or U2F, save data - if err := ctx.Session.Set("twofaUid", u.ID); err != nil { - ctx.ServerError("UserSignIn: Unable to set twofaUid in session", err) - return - } - - if err := ctx.Session.Set("twofaRemember", form.Remember); err != nil { - ctx.ServerError("UserSignIn: Unable to set twofaRemember in session", err) - return - } - - if hasTOTPtwofa { - // User will need to use U2F, save data - if err := ctx.Session.Set("totpEnrolled", u.ID); err != nil { - ctx.ServerError("UserSignIn: Unable to set u2fEnrolled in session", err) - return - } - } - - if err := ctx.Session.Release(); err != nil { - ctx.ServerError("UserSignIn: Unable to save session", err) - return - } - - // If we have U2F redirect there first - if hasU2Ftwofa { - ctx.Redirect(setting.AppSubURL + "/user/u2f") - return - } - - // Fallback to 2FA - ctx.Redirect(setting.AppSubURL + "/user/two_factor") -} - -// TwoFactor shows the user a two-factor authentication page. -func TwoFactor(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("twofa") - - // Check auto-login. - if checkAutoLogin(ctx) { - return - } - - // Ensure user is in a 2FA session. - if ctx.Session.Get("twofaUid") == nil { - ctx.ServerError("UserSignIn", errors.New("not in 2FA session")) - return - } - - ctx.HTML(http.StatusOK, tplTwofa) -} - -// TwoFactorPost validates a user's two-factor authentication token. -func TwoFactorPost(ctx *context.Context) { - form := web.GetForm(ctx).(*forms.TwoFactorAuthForm) - ctx.Data["Title"] = ctx.Tr("twofa") - - // Ensure user is in a 2FA session. - idSess := ctx.Session.Get("twofaUid") - if idSess == nil { - ctx.ServerError("UserSignIn", errors.New("not in 2FA session")) - return - } - - id := idSess.(int64) - twofa, err := login.GetTwoFactorByUID(id) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - // Validate the passcode with the stored TOTP secret. - ok, err := twofa.ValidateTOTP(form.Passcode) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - if ok && twofa.LastUsedPasscode != form.Passcode { - remember := ctx.Session.Get("twofaRemember").(bool) - u, err := user_model.GetUserByID(id) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - if ctx.Session.Get("linkAccount") != nil { - if err := externalaccount.LinkAccountFromStore(ctx.Session, u); err != nil { - ctx.ServerError("UserSignIn", err) - } - } - - twofa.LastUsedPasscode = form.Passcode - if err = login.UpdateTwoFactor(twofa); err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - handleSignIn(ctx, u, remember) - return - } - - ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, forms.TwoFactorAuthForm{}) -} - -// TwoFactorScratch shows the scratch code form for two-factor authentication. -func TwoFactorScratch(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("twofa_scratch") - - // Check auto-login. - if checkAutoLogin(ctx) { - return - } - - // Ensure user is in a 2FA session. - if ctx.Session.Get("twofaUid") == nil { - ctx.ServerError("UserSignIn", errors.New("not in 2FA session")) - return - } - - ctx.HTML(http.StatusOK, tplTwofaScratch) -} - -// TwoFactorScratchPost validates and invalidates a user's two-factor scratch token. -func TwoFactorScratchPost(ctx *context.Context) { - form := web.GetForm(ctx).(*forms.TwoFactorScratchAuthForm) - ctx.Data["Title"] = ctx.Tr("twofa_scratch") - - // Ensure user is in a 2FA session. - idSess := ctx.Session.Get("twofaUid") - if idSess == nil { - ctx.ServerError("UserSignIn", errors.New("not in 2FA session")) - return - } - - id := idSess.(int64) - twofa, err := login.GetTwoFactorByUID(id) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - // Validate the passcode with the stored TOTP secret. - if twofa.VerifyScratchToken(form.Token) { - // Invalidate the scratch token. - _, err = twofa.GenerateScratchToken() - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - if err = login.UpdateTwoFactor(twofa); err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - remember := ctx.Session.Get("twofaRemember").(bool) - u, err := user_model.GetUserByID(id) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - handleSignInFull(ctx, u, remember, false) - if ctx.Written() { - return - } - ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used")) - ctx.Redirect(setting.AppSubURL + "/user/settings/security") - return - } - - ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, forms.TwoFactorScratchAuthForm{}) -} - -// U2F shows the U2F login page -func U2F(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("twofa") - ctx.Data["RequireU2F"] = true - // Check auto-login. - if checkAutoLogin(ctx) { - return - } - - // Ensure user is in a 2FA session. - if ctx.Session.Get("twofaUid") == nil { - ctx.ServerError("UserSignIn", errors.New("not in U2F session")) - return - } - - // See whether TOTP is also available. - if ctx.Session.Get("totpEnrolled") != nil { - ctx.Data["TOTPEnrolled"] = true - } - - ctx.HTML(http.StatusOK, tplU2F) -} - -// U2FChallenge submits a sign challenge to the browser -func U2FChallenge(ctx *context.Context) { - // Ensure user is in a U2F session. - idSess := ctx.Session.Get("twofaUid") - if idSess == nil { - ctx.ServerError("UserSignIn", errors.New("not in U2F session")) - return - } - id := idSess.(int64) - regs, err := login.GetU2FRegistrationsByUID(id) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - if len(regs) == 0 { - ctx.ServerError("UserSignIn", errors.New("no device registered")) - return - } - challenge, err := u2f.NewChallenge(setting.U2F.AppID, setting.U2F.TrustedFacets) - if err != nil { - ctx.ServerError("u2f.NewChallenge", err) - return - } - if err := ctx.Session.Set("u2fChallenge", challenge); err != nil { - ctx.ServerError("UserSignIn: unable to set u2fChallenge in session", err) - return - } - if err := ctx.Session.Release(); err != nil { - ctx.ServerError("UserSignIn: unable to store session", err) - } - - ctx.JSON(http.StatusOK, challenge.SignRequest(regs.ToRegistrations())) -} - -// U2FSign authenticates the user by signResp -func U2FSign(ctx *context.Context) { - signResp := web.GetForm(ctx).(*u2f.SignResponse) - challSess := ctx.Session.Get("u2fChallenge") - idSess := ctx.Session.Get("twofaUid") - if challSess == nil || idSess == nil { - ctx.ServerError("UserSignIn", errors.New("not in U2F session")) - return - } - challenge := challSess.(*u2f.Challenge) - id := idSess.(int64) - regs, err := login.GetU2FRegistrationsByUID(id) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - for _, reg := range regs { - r, err := reg.Parse() - if err != nil { - log.Error("parsing u2f registration: %v", err) - continue - } - newCounter, authErr := r.Authenticate(*signResp, *challenge, reg.Counter) - if authErr == nil { - reg.Counter = newCounter - user, err := user_model.GetUserByID(id) - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - remember := ctx.Session.Get("twofaRemember").(bool) - if err := reg.UpdateCounter(); err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - if ctx.Session.Get("linkAccount") != nil { - if err := externalaccount.LinkAccountFromStore(ctx.Session, user); err != nil { - ctx.ServerError("UserSignIn", err) - } - } - redirect := handleSignInFull(ctx, user, remember, false) - if ctx.Written() { - return - } - if redirect == "" { - redirect = setting.AppSubURL + "/" - } - ctx.PlainText(http.StatusOK, redirect) - return - } - } - ctx.Error(http.StatusUnauthorized) -} - -// This handles the final part of the sign-in process of the user. -func handleSignIn(ctx *context.Context, u *user_model.User, remember bool) { - redirect := handleSignInFull(ctx, u, remember, true) - if ctx.Written() { - return - } - ctx.Redirect(redirect) -} - -func handleSignInFull(ctx *context.Context, u *user_model.User, remember, obeyRedirect bool) string { - if remember { - days := 86400 * setting.LogInRememberDays - ctx.SetCookie(setting.CookieUserName, u.Name, days) - ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd), - setting.CookieRememberName, u.Name, days) - } - - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) - return setting.AppSubURL + "/" - } - - // Delete the openid, 2fa and linkaccount data - _ = ctx.Session.Delete("openid_verified_uri") - _ = ctx.Session.Delete("openid_signin_remember") - _ = ctx.Session.Delete("openid_determined_email") - _ = ctx.Session.Delete("openid_determined_username") - _ = ctx.Session.Delete("twofaUid") - _ = ctx.Session.Delete("twofaRemember") - _ = ctx.Session.Delete("u2fChallenge") - _ = ctx.Session.Delete("linkAccount") - if err := ctx.Session.Set("uid", u.ID); err != nil { - log.Error("Error setting uid %d in session: %v", u.ID, err) - } - if err := ctx.Session.Set("uname", u.Name); err != nil { - log.Error("Error setting uname %s session: %v", u.Name, err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Unable to store session: %v", err) - } - - // Language setting of the user overwrites the one previously set - // If the user does not have a locale set, we save the current one. - if len(u.Language) == 0 { - u.Language = ctx.Locale.Language() - if err := user_model.UpdateUserCols(db.DefaultContext, u, "language"); err != nil { - ctx.ServerError("UpdateUserCols Language", fmt.Errorf("Error updating user language [user: %d, locale: %s]", u.ID, u.Language)) - return setting.AppSubURL + "/" - } - } - - middleware.SetLocaleCookie(ctx.Resp, u.Language, 0) - - if ctx.Locale.Language() != u.Language { - ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req) - } - - // Clear whatever CSRF has right now, force to generate a new one - middleware.DeleteCSRFCookie(ctx.Resp) - - // Register last login - u.SetLastLogin() - if err := user_model.UpdateUserCols(db.DefaultContext, u, "last_login_unix"); err != nil { - ctx.ServerError("UpdateUserCols", err) - return setting.AppSubURL + "/" - } - - if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 && !utils.IsExternalURL(redirectTo) { - middleware.DeleteRedirectToCookie(ctx.Resp) - if obeyRedirect { - ctx.RedirectToFirst(redirectTo) - } - return redirectTo - } - - if obeyRedirect { - ctx.Redirect(setting.AppSubURL + "/") - } - return setting.AppSubURL + "/" -} - -// SignInOAuth handles the OAuth2 login buttons -func SignInOAuth(ctx *context.Context) { - provider := ctx.Params(":provider") - - loginSource, err := login.GetActiveOAuth2LoginSourceByName(provider) - if err != nil { - ctx.ServerError("SignIn", err) - return - } - - // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user - user, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req, ctx.Resp) - if err == nil && user != nil { - // we got the user without going through the whole OAuth2 authentication flow again - handleOAuth2SignIn(ctx, loginSource, user, gothUser) - return - } - - if err = loginSource.Cfg.(*oauth2.Source).Callout(ctx.Req, ctx.Resp); err != nil { - if strings.Contains(err.Error(), "no provider for ") { - if err = oauth2.ResetOAuth2(); err != nil { - ctx.ServerError("SignIn", err) - return - } - if err = loginSource.Cfg.(*oauth2.Source).Callout(ctx.Req, ctx.Resp); err != nil { - ctx.ServerError("SignIn", err) - } - return - } - ctx.ServerError("SignIn", err) - } - // redirect is done in oauth2.Auth -} - -// SignInOAuthCallback handles the callback from the given provider -func SignInOAuthCallback(ctx *context.Context) { - provider := ctx.Params(":provider") - - // first look if the provider is still active - loginSource, err := login.GetActiveOAuth2LoginSourceByName(provider) - if err != nil { - ctx.ServerError("SignIn", err) - return - } - - if loginSource == nil { - ctx.ServerError("SignIn", errors.New("No valid provider found, check configured callback url in provider")) - return - } - - u, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req, ctx.Resp) - - if err != nil { - if user_model.IsErrUserProhibitLogin(err) { - uplerr := err.(*user_model.ErrUserProhibitLogin) - log.Info("Failed authentication attempt for %s from %s: %v", uplerr.Name, ctx.RemoteAddr(), err) - ctx.Data["Title"] = ctx.Tr("auth.prohibit_login") - ctx.HTML(http.StatusOK, "user/auth/prohibit_login") - return - } - ctx.ServerError("UserSignIn", err) - return - } - - if u == nil { - if !setting.Service.AllowOnlyInternalRegistration && setting.OAuth2Client.EnableAutoRegistration { - // create new user with details from oauth2 provider - var missingFields []string - if gothUser.UserID == "" { - missingFields = append(missingFields, "sub") - } - if gothUser.Email == "" { - missingFields = append(missingFields, "email") - } - if setting.OAuth2Client.Username == setting.OAuth2UsernameNickname && gothUser.NickName == "" { - missingFields = append(missingFields, "nickname") - } - if len(missingFields) > 0 { - log.Error("OAuth2 Provider %s returned empty or missing fields: %s", loginSource.Name, missingFields) - if loginSource.IsOAuth2() && loginSource.Cfg.(*oauth2.Source).Provider == "openidConnect" { - log.Error("You may need to change the 'OPENID_CONNECT_SCOPES' setting to request all required fields") - } - err = fmt.Errorf("OAuth2 Provider %s returned empty or missing fields: %s", loginSource.Name, missingFields) - ctx.ServerError("CreateUser", err) - return - } - u = &user_model.User{ - Name: getUserName(&gothUser), - FullName: gothUser.Name, - Email: gothUser.Email, - IsActive: !setting.OAuth2Client.RegisterEmailConfirm, - LoginType: login.OAuth2, - LoginSource: loginSource.ID, - LoginName: gothUser.UserID, - IsRestricted: setting.Service.DefaultUserIsRestricted, - } - - setUserGroupClaims(loginSource, u, &gothUser) - - if !createAndHandleCreatedUser(ctx, base.TplName(""), nil, u, &gothUser, setting.OAuth2Client.AccountLinking != setting.OAuth2AccountLinkingDisabled) { - // error already handled - return - } - } else { - // no existing user is found, request attach or new account - showLinkingLogin(ctx, gothUser) - return - } - } - - handleOAuth2SignIn(ctx, loginSource, u, gothUser) -} - -func claimValueToStringSlice(claimValue interface{}) []string { - var groups []string - - switch rawGroup := claimValue.(type) { - case []string: - groups = rawGroup - default: - str := fmt.Sprintf("%s", rawGroup) - groups = strings.Split(str, ",") - } - return groups -} - -func setUserGroupClaims(loginSource *login.Source, u *user_model.User, gothUser *goth.User) bool { - - source := loginSource.Cfg.(*oauth2.Source) - if source.GroupClaimName == "" || (source.AdminGroup == "" && source.RestrictedGroup == "") { - return false - } - - groupClaims, has := gothUser.RawData[source.GroupClaimName] - if !has { - return false - } - - groups := claimValueToStringSlice(groupClaims) - - wasAdmin, wasRestricted := u.IsAdmin, u.IsRestricted - - if source.AdminGroup != "" { - u.IsAdmin = false - } - if source.RestrictedGroup != "" { - u.IsRestricted = false - } - - for _, g := range groups { - if source.AdminGroup != "" && g == source.AdminGroup { - u.IsAdmin = true - } else if source.RestrictedGroup != "" && g == source.RestrictedGroup { - u.IsRestricted = true - } - } - - return wasAdmin != u.IsAdmin || wasRestricted != u.IsRestricted -} - -func getUserName(gothUser *goth.User) string { - switch setting.OAuth2Client.Username { - case setting.OAuth2UsernameEmail: - return strings.Split(gothUser.Email, "@")[0] - case setting.OAuth2UsernameNickname: - return gothUser.NickName - default: // OAuth2UsernameUserid - return gothUser.UserID - } -} - -func showLinkingLogin(ctx *context.Context, gothUser goth.User) { - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) - return - } - - if err := ctx.Session.Set("linkAccountGothUser", gothUser); err != nil { - log.Error("Error setting linkAccountGothUser in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session: %v", err) - } - ctx.Redirect(setting.AppSubURL + "/user/link_account") -} - -func updateAvatarIfNeed(url string, u *user_model.User) { - if setting.OAuth2Client.UpdateAvatar && len(url) > 0 { - resp, err := http.Get(url) - if err == nil { - defer func() { - _ = resp.Body.Close() - }() - } - // ignore any error - if err == nil && resp.StatusCode == http.StatusOK { - data, err := io.ReadAll(io.LimitReader(resp.Body, setting.Avatar.MaxFileSize+1)) - if err == nil && int64(len(data)) <= setting.Avatar.MaxFileSize { - _ = user_service.UploadAvatar(u, data) - } - } - } -} - -func handleOAuth2SignIn(ctx *context.Context, source *login.Source, u *user_model.User, gothUser goth.User) { - updateAvatarIfNeed(gothUser.AvatarURL, u) - - needs2FA := false - if !source.Cfg.(*oauth2.Source).SkipLocalTwoFA { - _, err := login.GetTwoFactorByUID(u.ID) - if err != nil && !login.IsErrTwoFactorNotEnrolled(err) { - ctx.ServerError("UserSignIn", err) - return - } - needs2FA = err == nil - } - - // If this user is enrolled in 2FA and this source doesn't override it, - // we can't sign the user in just yet. Instead, redirect them to the 2FA authentication page. - if !needs2FA { - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) - return - } - - // Set session IDs - if err := ctx.Session.Set("uid", u.ID); err != nil { - log.Error("Error setting uid in session: %v", err) - } - if err := ctx.Session.Set("uname", u.Name); err != nil { - log.Error("Error setting uname in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session: %v", err) - } - - // Clear whatever CSRF has right now, force to generate a new one - middleware.DeleteCSRFCookie(ctx.Resp) - - // Register last login - u.SetLastLogin() - - // Update GroupClaims - changed := setUserGroupClaims(source, u, &gothUser) - cols := []string{"last_login_unix"} - if changed { - cols = append(cols, "is_admin", "is_restricted") - } - - if err := user_model.UpdateUserCols(db.DefaultContext, u, cols...); err != nil { - ctx.ServerError("UpdateUserCols", err) - return - } - - // update external user information - if err := externalaccount.UpdateExternalUser(u, gothUser); err != nil { - log.Error("UpdateExternalUser failed: %v", err) - } - - if err := resetLocale(ctx, u); err != nil { - ctx.ServerError("resetLocale", err) - return - } - - if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 { - middleware.DeleteRedirectToCookie(ctx.Resp) - ctx.RedirectToFirst(redirectTo) - return - } - - ctx.Redirect(setting.AppSubURL + "/") - return - } - - changed := setUserGroupClaims(source, u, &gothUser) - if changed { - if err := user_model.UpdateUserCols(db.DefaultContext, u, "is_admin", "is_restricted"); err != nil { - ctx.ServerError("UpdateUserCols", err) - return - } - } - - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) - return - } - - // User needs to use 2FA, save data and redirect to 2FA page. - if err := ctx.Session.Set("twofaUid", u.ID); err != nil { - log.Error("Error setting twofaUid in session: %v", err) - } - if err := ctx.Session.Set("twofaRemember", false); err != nil { - log.Error("Error setting twofaRemember in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session: %v", err) - } - - // If U2F is enrolled -> Redirect to U2F instead - regs, err := login.GetU2FRegistrationsByUID(u.ID) - if err == nil && len(regs) > 0 { - ctx.Redirect(setting.AppSubURL + "/user/u2f") - return - } - - ctx.Redirect(setting.AppSubURL + "/user/two_factor") -} - -// OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful -// login the user -func oAuth2UserLoginCallback(loginSource *login.Source, request *http.Request, response http.ResponseWriter) (*user_model.User, goth.User, error) { - oauth2Source := loginSource.Cfg.(*oauth2.Source) - - gothUser, err := oauth2Source.Callback(request, response) - if err != nil { - if err.Error() == "securecookie: the value is too long" || strings.Contains(err.Error(), "Data too long") { - log.Error("OAuth2 Provider %s returned too long a token. Current max: %d. Either increase the [OAuth2] MAX_TOKEN_LENGTH or reduce the information returned from the OAuth2 provider", loginSource.Name, setting.OAuth2.MaxTokenLength) - err = fmt.Errorf("OAuth2 Provider %s returned too long a token. Current max: %d. Either increase the [OAuth2] MAX_TOKEN_LENGTH or reduce the information returned from the OAuth2 provider", loginSource.Name, setting.OAuth2.MaxTokenLength) - } - return nil, goth.User{}, err - } - - if oauth2Source.RequiredClaimName != "" { - claimInterface, has := gothUser.RawData[oauth2Source.RequiredClaimName] - if !has { - return nil, goth.User{}, user_model.ErrUserProhibitLogin{Name: gothUser.UserID} - } - - if oauth2Source.RequiredClaimValue != "" { - groups := claimValueToStringSlice(claimInterface) - found := false - for _, group := range groups { - if group == oauth2Source.RequiredClaimValue { - found = true - break - } - } - if !found { - return nil, goth.User{}, user_model.ErrUserProhibitLogin{Name: gothUser.UserID} - } - } - } - - user := &user_model.User{ - LoginName: gothUser.UserID, - LoginType: login.OAuth2, - LoginSource: loginSource.ID, - } - - hasUser, err := user_model.GetUser(user) - if err != nil { - return nil, goth.User{}, err - } - - if hasUser { - return user, gothUser, nil - } - - // search in external linked users - externalLoginUser := &user_model.ExternalLoginUser{ - ExternalID: gothUser.UserID, - LoginSourceID: loginSource.ID, - } - hasUser, err = user_model.GetExternalLogin(externalLoginUser) - if err != nil { - return nil, goth.User{}, err - } - if hasUser { - user, err = user_model.GetUserByID(externalLoginUser.UserID) - return user, gothUser, err - } - - // no user found to login - return nil, gothUser, nil - -} - -// LinkAccount shows the page where the user can decide to login or create a new account -func LinkAccount(ctx *context.Context) { - ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration - ctx.Data["Title"] = ctx.Tr("link_account") - ctx.Data["LinkAccountMode"] = true - ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha - ctx.Data["Captcha"] = context.GetImageCaptcha() - ctx.Data["CaptchaType"] = setting.Service.CaptchaType - ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL - ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey - ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey - ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration - ctx.Data["AllowOnlyInternalRegistration"] = setting.Service.AllowOnlyInternalRegistration - ctx.Data["ShowRegistrationButton"] = false - - // use this to set the right link into the signIn and signUp templates in the link_account template - ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin" - ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup" - - gothUser := ctx.Session.Get("linkAccountGothUser") - if gothUser == nil { - ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session")) - return - } - - gu, _ := gothUser.(goth.User) - uname := getUserName(&gu) - email := gu.Email - ctx.Data["user_name"] = uname - ctx.Data["email"] = email - - if len(email) != 0 { - u, err := user_model.GetUserByEmail(email) - if err != nil && !user_model.IsErrUserNotExist(err) { - ctx.ServerError("UserSignIn", err) - return - } - if u != nil { - ctx.Data["user_exists"] = true - } - } else if len(uname) != 0 { - u, err := user_model.GetUserByName(uname) - if err != nil && !user_model.IsErrUserNotExist(err) { - ctx.ServerError("UserSignIn", err) - return - } - if u != nil { - ctx.Data["user_exists"] = true - } - } - - ctx.HTML(http.StatusOK, tplLinkAccount) -} - -// LinkAccountPostSignIn handle the coupling of external account with another account using signIn -func LinkAccountPostSignIn(ctx *context.Context) { - signInForm := web.GetForm(ctx).(*forms.SignInForm) - ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration - ctx.Data["Title"] = ctx.Tr("link_account") - ctx.Data["LinkAccountMode"] = true - ctx.Data["LinkAccountModeSignIn"] = true - ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha - ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL - ctx.Data["Captcha"] = context.GetImageCaptcha() - ctx.Data["CaptchaType"] = setting.Service.CaptchaType - ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey - ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey - ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration - ctx.Data["ShowRegistrationButton"] = false - - // use this to set the right link into the signIn and signUp templates in the link_account template - ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin" - ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup" - - gothUser := ctx.Session.Get("linkAccountGothUser") - if gothUser == nil { - ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session")) - return - } - - if ctx.HasError() { - ctx.HTML(http.StatusOK, tplLinkAccount) - return - } - - u, _, err := auth.UserSignIn(signInForm.UserName, signInForm.Password) - if err != nil { - if user_model.IsErrUserNotExist(err) { - ctx.Data["user_exists"] = true - ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplLinkAccount, &signInForm) - } else { - ctx.ServerError("UserLinkAccount", err) - } - return - } - - linkAccount(ctx, u, gothUser.(goth.User), signInForm.Remember) -} - -func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, remember bool) { - updateAvatarIfNeed(gothUser.AvatarURL, u) - - // If this user is enrolled in 2FA, we can't sign the user in just yet. - // Instead, redirect them to the 2FA authentication page. - // We deliberately ignore the skip local 2fa setting here because we are linking to a previous user here - _, err := login.GetTwoFactorByUID(u.ID) - if err != nil { - if !login.IsErrTwoFactorNotEnrolled(err) { - ctx.ServerError("UserLinkAccount", err) - return - } - - err = externalaccount.LinkAccountToUser(u, gothUser) - if err != nil { - ctx.ServerError("UserLinkAccount", err) - return - } - - handleSignIn(ctx, u, remember) - return - } - - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) - return - } - - // User needs to use 2FA, save data and redirect to 2FA page. - if err := ctx.Session.Set("twofaUid", u.ID); err != nil { - log.Error("Error setting twofaUid in session: %v", err) - } - if err := ctx.Session.Set("twofaRemember", remember); err != nil { - log.Error("Error setting twofaRemember in session: %v", err) - } - if err := ctx.Session.Set("linkAccount", true); err != nil { - log.Error("Error setting linkAccount in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session: %v", err) - } - - // If U2F is enrolled -> Redirect to U2F instead - regs, err := login.GetU2FRegistrationsByUID(u.ID) - if err == nil && len(regs) > 0 { - ctx.Redirect(setting.AppSubURL + "/user/u2f") - return - } - - ctx.Redirect(setting.AppSubURL + "/user/two_factor") -} - -// LinkAccountPostRegister handle the creation of a new account for an external account using signUp -func LinkAccountPostRegister(ctx *context.Context) { - form := web.GetForm(ctx).(*forms.RegisterForm) - // TODO Make insecure passwords optional for local accounts also, - // once email-based Second-Factor Auth is available - ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration - ctx.Data["Title"] = ctx.Tr("link_account") - ctx.Data["LinkAccountMode"] = true - ctx.Data["LinkAccountModeRegister"] = true - ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha - ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL - ctx.Data["Captcha"] = context.GetImageCaptcha() - ctx.Data["CaptchaType"] = setting.Service.CaptchaType - ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey - ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey - ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration - ctx.Data["ShowRegistrationButton"] = false - - // use this to set the right link into the signIn and signUp templates in the link_account template - ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin" - ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup" - - gothUserInterface := ctx.Session.Get("linkAccountGothUser") - if gothUserInterface == nil { - ctx.ServerError("UserSignUp", errors.New("not in LinkAccount session")) - return - } - gothUser, ok := gothUserInterface.(goth.User) - if !ok { - ctx.ServerError("UserSignUp", fmt.Errorf("session linkAccountGothUser type is %t but not goth.User", gothUserInterface)) - return - } - - if ctx.HasError() { - ctx.HTML(http.StatusOK, tplLinkAccount) - return - } - - if setting.Service.DisableRegistration || setting.Service.AllowOnlyInternalRegistration { - ctx.Error(http.StatusForbidden) - return - } - - if setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha { - var valid bool - var err error - switch setting.Service.CaptchaType { - case setting.ImageCaptcha: - valid = context.GetImageCaptcha().VerifyReq(ctx.Req) - case setting.ReCaptcha: - valid, err = recaptcha.Verify(ctx, form.GRecaptchaResponse) - case setting.HCaptcha: - valid, err = hcaptcha.Verify(ctx, form.HcaptchaResponse) - default: - ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType)) - return - } - if err != nil { - log.Debug("%s", err.Error()) - } - - if !valid { - ctx.Data["Err_Captcha"] = true - ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form) - return - } - } - - if !form.IsEmailDomainAllowed() { - ctx.RenderWithErr(ctx.Tr("auth.email_domain_blacklisted"), tplLinkAccount, &form) - return - } - - if setting.Service.AllowOnlyExternalRegistration || !setting.Service.RequireExternalRegistrationPassword { - // In user_model.User an empty password is classed as not set, so we set form.Password to empty. - // Eventually the database should be changed to indicate "Second Factor"-enabled accounts - // (accounts that do not introduce the security vulnerabilities of a password). - // If a user decides to circumvent second-factor security, and purposefully create a password, - // they can still do so using the "Recover Account" option. - form.Password = "" - } else { - if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype { - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form) - return - } - if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength { - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form) - return - } - } - - loginSource, err := login.GetActiveOAuth2LoginSourceByName(gothUser.Provider) - if err != nil { - ctx.ServerError("CreateUser", err) - } - - u := &user_model.User{ - Name: form.UserName, - Email: form.Email, - Passwd: form.Password, - IsActive: !(setting.Service.RegisterEmailConfirm || setting.Service.RegisterManualConfirm), - LoginType: login.OAuth2, - LoginSource: loginSource.ID, - LoginName: gothUser.UserID, - } - - if !createAndHandleCreatedUser(ctx, tplLinkAccount, form, u, &gothUser, false) { - // error already handled - return - } - - handleSignIn(ctx, u, false) -} - -// HandleSignOut resets the session and sets the cookies -func HandleSignOut(ctx *context.Context) { - _ = ctx.Session.Flush() - _ = ctx.Session.Destroy(ctx.Resp, ctx.Req) - ctx.DeleteCookie(setting.CookieUserName) - ctx.DeleteCookie(setting.CookieRememberName) - middleware.DeleteCSRFCookie(ctx.Resp) - middleware.DeleteLocaleCookie(ctx.Resp) - middleware.DeleteRedirectToCookie(ctx.Resp) -} - -// SignOut sign out from login status -func SignOut(ctx *context.Context) { - if ctx.User != nil { - eventsource.GetManager().SendMessageBlocking(ctx.User.ID, &eventsource.Event{ - Name: "logout", - Data: ctx.Session.ID(), - }) - } - HandleSignOut(ctx) - ctx.Redirect(setting.AppSubURL + "/") -} - -// SignUp render the register page -func SignUp(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("sign_up") - - ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" - - ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha - ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL - ctx.Data["Captcha"] = context.GetImageCaptcha() - ctx.Data["CaptchaType"] = setting.Service.CaptchaType - ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey - ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey - ctx.Data["PageIsSignUp"] = true - - //Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true - ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration - - ctx.HTML(http.StatusOK, tplSignUp) -} - -// SignUpPost response for sign up information submission -func SignUpPost(ctx *context.Context) { - form := web.GetForm(ctx).(*forms.RegisterForm) - ctx.Data["Title"] = ctx.Tr("sign_up") - - ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" - - ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha - ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL - ctx.Data["Captcha"] = context.GetImageCaptcha() - ctx.Data["CaptchaType"] = setting.Service.CaptchaType - ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey - ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey - ctx.Data["PageIsSignUp"] = true - - //Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true - if setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration { - ctx.Error(http.StatusForbidden) - return - } - - if ctx.HasError() { - ctx.HTML(http.StatusOK, tplSignUp) - return - } - - if setting.Service.EnableCaptcha { - var valid bool - var err error - switch setting.Service.CaptchaType { - case setting.ImageCaptcha: - valid = context.GetImageCaptcha().VerifyReq(ctx.Req) - case setting.ReCaptcha: - valid, err = recaptcha.Verify(ctx, form.GRecaptchaResponse) - case setting.HCaptcha: - valid, err = hcaptcha.Verify(ctx, form.HcaptchaResponse) - default: - ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType)) - return - } - if err != nil { - log.Debug("%s", err.Error()) - } - - if !valid { - ctx.Data["Err_Captcha"] = true - ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form) - return - } - } - - if !form.IsEmailDomainAllowed() { - ctx.RenderWithErr(ctx.Tr("auth.email_domain_blacklisted"), tplSignUp, &form) - return - } - - if form.Password != form.Retype { - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form) - return - } - if len(form.Password) < setting.MinPasswordLength { - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form) - return - } - if !password.IsComplexEnough(form.Password) { - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(password.BuildComplexityError(ctx), tplSignUp, &form) - return - } - pwned, err := password.IsPwned(ctx, form.Password) - if pwned { - errMsg := ctx.Tr("auth.password_pwned") - if err != nil { - log.Error(err.Error()) - errMsg = ctx.Tr("auth.password_pwned_err") - } - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(errMsg, tplSignUp, &form) - return - } - - u := &user_model.User{ - Name: form.UserName, - Email: form.Email, - Passwd: form.Password, - IsActive: !(setting.Service.RegisterEmailConfirm || setting.Service.RegisterManualConfirm), - IsRestricted: setting.Service.DefaultUserIsRestricted, - } - - if !createAndHandleCreatedUser(ctx, tplSignUp, form, u, nil, false) { - // error already handled - return - } - - ctx.Flash.Success(ctx.Tr("auth.sign_up_successful")) - handleSignIn(ctx, u, false) -} - -// createAndHandleCreatedUser calls createUserInContext and -// then handleUserCreated. -func createAndHandleCreatedUser(ctx *context.Context, tpl base.TplName, form interface{}, u *user_model.User, gothUser *goth.User, allowLink bool) bool { - if !createUserInContext(ctx, tpl, form, u, gothUser, allowLink) { - return false - } - return handleUserCreated(ctx, u, gothUser) -} - -// createUserInContext creates a user and handles errors within a given context. -// Optionally a template can be specified. -func createUserInContext(ctx *context.Context, tpl base.TplName, form interface{}, u *user_model.User, gothUser *goth.User, allowLink bool) (ok bool) { - if err := user_model.CreateUser(u); err != nil { - if allowLink && (user_model.IsErrUserAlreadyExist(err) || user_model.IsErrEmailAlreadyUsed(err)) { - if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingAuto { - var user *user_model.User - user = &user_model.User{Name: u.Name} - hasUser, err := user_model.GetUser(user) - if !hasUser || err != nil { - user = &user_model.User{Email: u.Email} - hasUser, err = user_model.GetUser(user) - if !hasUser || err != nil { - ctx.ServerError("UserLinkAccount", err) - return - } - } - - // TODO: probably we should respect 'remember' user's choice... - linkAccount(ctx, user, *gothUser, true) - return // user is already created here, all redirects are handled - } else if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingLogin { - showLinkingLogin(ctx, *gothUser) - return // user will be created only after linking login - } - } - - // handle error without template - if len(tpl) == 0 { - ctx.ServerError("CreateUser", err) - return - } - - // handle error with template - switch { - case user_model.IsErrUserAlreadyExist(err): - ctx.Data["Err_UserName"] = true - ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tpl, form) - case user_model.IsErrEmailAlreadyUsed(err): - ctx.Data["Err_Email"] = true - ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tpl, form) - case user_model.IsErrEmailInvalid(err): - ctx.Data["Err_Email"] = true - ctx.RenderWithErr(ctx.Tr("form.email_invalid"), tpl, form) - case db.IsErrNameReserved(err): - ctx.Data["Err_UserName"] = true - ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(db.ErrNameReserved).Name), tpl, form) - case db.IsErrNamePatternNotAllowed(err): - ctx.Data["Err_UserName"] = true - ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(db.ErrNamePatternNotAllowed).Pattern), tpl, form) - case db.IsErrNameCharsNotAllowed(err): - ctx.Data["Err_UserName"] = true - ctx.RenderWithErr(ctx.Tr("user.form.name_chars_not_allowed", err.(db.ErrNameCharsNotAllowed).Name), tpl, form) - default: - ctx.ServerError("CreateUser", err) - } - return - } - log.Trace("Account created: %s", u.Name) - return true -} - -// handleUserCreated does additional steps after a new user is created. -// It auto-sets admin for the only user, updates the optional external user and -// sends a confirmation email if required. -func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth.User) (ok bool) { - // Auto-set admin for the only user. - if user_model.CountUsers() == 1 { - u.IsAdmin = true - u.IsActive = true - u.SetLastLogin() - if err := user_model.UpdateUserCols(db.DefaultContext, u, "is_admin", "is_active", "last_login_unix"); err != nil { - ctx.ServerError("UpdateUser", err) - return - } - } - - // update external user information - if gothUser != nil { - if err := externalaccount.UpdateExternalUser(u, *gothUser); err != nil { - log.Error("UpdateExternalUser failed: %v", err) - } - } - - // Send confirmation email - if !u.IsActive && u.ID > 1 { - mailer.SendActivateAccountMail(ctx.Locale, u) - - ctx.Data["IsSendRegisterMail"] = true - ctx.Data["Email"] = u.Email - ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) - ctx.HTML(http.StatusOK, TplActivate) - - if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { - log.Error("Set cache(MailResendLimit) fail: %v", err) - } - return - } - - return true -} - -// Activate render activate user page -func Activate(ctx *context.Context) { - code := ctx.FormString("code") - - if len(code) == 0 { - ctx.Data["IsActivatePage"] = true - if ctx.User == nil || ctx.User.IsActive { - ctx.NotFound("invalid user", nil) - return - } - // Resend confirmation email. - if setting.Service.RegisterEmailConfirm { - if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) { - ctx.Data["ResendLimited"] = true - } else { - ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language()) - mailer.SendActivateAccountMail(ctx.Locale, ctx.User) - - if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { - log.Error("Set cache(MailResendLimit) fail: %v", err) - } - } - } else { - ctx.Data["ServiceNotEnabled"] = true - } - ctx.HTML(http.StatusOK, TplActivate) - return - } - - user := user_model.VerifyUserActiveCode(code) - // if code is wrong - if user == nil { - ctx.Data["IsActivateFailed"] = true - ctx.HTML(http.StatusOK, TplActivate) - return - } - - // if account is local account, verify password - if user.LoginSource == 0 { - ctx.Data["Code"] = code - ctx.Data["NeedsPassword"] = true - ctx.HTML(http.StatusOK, TplActivate) - return - } - - handleAccountActivation(ctx, user) -} - -// ActivatePost handles account activation with password check -func ActivatePost(ctx *context.Context) { - code := ctx.FormString("code") - if len(code) == 0 { - ctx.Redirect(setting.AppSubURL + "/user/activate") - return - } - - user := user_model.VerifyUserActiveCode(code) - // if code is wrong - if user == nil { - ctx.Data["IsActivateFailed"] = true - ctx.HTML(http.StatusOK, TplActivate) - return - } - - // if account is local account, verify password - if user.LoginSource == 0 { - password := ctx.FormString("password") - if len(password) == 0 { - ctx.Data["Code"] = code - ctx.Data["NeedsPassword"] = true - ctx.HTML(http.StatusOK, TplActivate) - return - } - if !user.ValidatePassword(password) { - ctx.Data["IsActivateFailed"] = true - ctx.HTML(http.StatusOK, TplActivate) - return - } - } - - handleAccountActivation(ctx, user) -} - -func handleAccountActivation(ctx *context.Context, user *user_model.User) { - user.IsActive = true - var err error - if user.Rands, err = user_model.GetUserSalt(); err != nil { - ctx.ServerError("UpdateUser", err) - return - } - if err := user_model.UpdateUserCols(db.DefaultContext, user, "is_active", "rands"); err != nil { - if user_model.IsErrUserNotExist(err) { - ctx.NotFound("UpdateUserCols", err) - } else { - ctx.ServerError("UpdateUser", err) - } - return - } - - if err := user_model.ActivateUserEmail(user.ID, user.Email, true); err != nil { - log.Error("Unable to activate email for user: %-v with email: %s: %v", user, user.Email, err) - ctx.ServerError("ActivateUserEmail", err) - return - } - - log.Trace("User activated: %s", user.Name) - - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - log.Error("Unable to regenerate session for user: %-v with email: %s: %v", user, user.Email, err) - ctx.ServerError("ActivateUserEmail", err) - return - } - - // Set session IDs - if err := ctx.Session.Set("uid", user.ID); err != nil { - log.Error("Error setting uid in session[%s]: %v", ctx.Session.ID(), err) - } - if err := ctx.Session.Set("uname", user.Name); err != nil { - log.Error("Error setting uname in session[%s]: %v", ctx.Session.ID(), err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session[%s]: %v", ctx.Session.ID(), err) - } - - if err := resetLocale(ctx, user); err != nil { - ctx.ServerError("resetLocale", err) - return - } - - ctx.Flash.Success(ctx.Tr("auth.account_activated")) - ctx.Redirect(setting.AppSubURL + "/") -} - -// ActivateEmail render the activate email page -func ActivateEmail(ctx *context.Context) { - code := ctx.FormString("code") - emailStr := ctx.FormString("email") - - // Verify code. - if email := user_model.VerifyActiveEmailCode(code, emailStr); email != nil { - if err := user_model.ActivateEmail(email); err != nil { - ctx.ServerError("ActivateEmail", err) - } - - log.Trace("Email activated: %s", email.Email) - ctx.Flash.Success(ctx.Tr("settings.add_email_success")) - - if u, err := user_model.GetUserByID(email.UID); err != nil { - log.Warn("GetUserByID: %d", email.UID) - } else { - // Allow user to validate more emails - _ = ctx.Cache.Delete("MailResendLimit_" + u.LowerName) - } - } - - // FIXME: e-mail verification does not require the user to be logged in, - // so this could be redirecting to the login page. - // Should users be logged in automatically here? (consider 2FA requirements, etc.) - ctx.Redirect(setting.AppSubURL + "/user/settings/account") -} - -// ForgotPasswd render the forget password page -func ForgotPasswd(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title") - - if setting.MailService == nil { - log.Warn(ctx.Tr("auth.disable_forgot_password_mail_admin")) - ctx.Data["IsResetDisable"] = true - ctx.HTML(http.StatusOK, tplForgotPassword) - return - } - - ctx.Data["Email"] = ctx.FormString("email") - - ctx.Data["IsResetRequest"] = true - ctx.HTML(http.StatusOK, tplForgotPassword) -} - -// ForgotPasswdPost response for forget password request -func ForgotPasswdPost(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title") - - if setting.MailService == nil { - ctx.NotFound("ForgotPasswdPost", nil) - return - } - ctx.Data["IsResetRequest"] = true - - email := ctx.FormString("email") - ctx.Data["Email"] = email - - u, err := user_model.GetUserByEmail(email) - if err != nil { - if user_model.IsErrUserNotExist(err) { - ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) - ctx.Data["IsResetSent"] = true - ctx.HTML(http.StatusOK, tplForgotPassword) - return - } - - ctx.ServerError("user.ResetPasswd(check existence)", err) - return - } - - if !u.IsLocal() && !u.IsOAuth2() { - ctx.Data["Err_Email"] = true - ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil) - return - } - - if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) { - ctx.Data["ResendLimited"] = true - ctx.HTML(http.StatusOK, tplForgotPassword) - return - } - - mailer.SendResetPasswordMail(u) - - if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { - log.Error("Set cache(MailResendLimit) fail: %v", err) - } - - ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language()) - ctx.Data["IsResetSent"] = true - ctx.HTML(http.StatusOK, tplForgotPassword) -} - -func commonResetPassword(ctx *context.Context) (*user_model.User, *login.TwoFactor) { - code := ctx.FormString("code") - - ctx.Data["Title"] = ctx.Tr("auth.reset_password") - ctx.Data["Code"] = code - - if nil != ctx.User { - ctx.Data["user_signed_in"] = true - } - - if len(code) == 0 { - ctx.Flash.Error(ctx.Tr("auth.invalid_code")) - return nil, nil - } - - // Fail early, don't frustrate the user - u := user_model.VerifyUserActiveCode(code) - if u == nil { - ctx.Flash.Error(ctx.Tr("auth.invalid_code")) - return nil, nil - } - - twofa, err := login.GetTwoFactorByUID(u.ID) - if err != nil { - if !login.IsErrTwoFactorNotEnrolled(err) { - ctx.Error(http.StatusInternalServerError, "CommonResetPassword", err.Error()) - return nil, nil - } - } else { - ctx.Data["has_two_factor"] = true - ctx.Data["scratch_code"] = ctx.FormBool("scratch_code") - } - - // Show the user that they are affecting the account that they intended to - ctx.Data["user_email"] = u.Email - - if nil != ctx.User && u.ID != ctx.User.ID { - ctx.Flash.Error(ctx.Tr("auth.reset_password_wrong_user", ctx.User.Email, u.Email)) - return nil, nil - } - - return u, twofa -} - -// ResetPasswd render the account recovery page -func ResetPasswd(ctx *context.Context) { - ctx.Data["IsResetForm"] = true - - commonResetPassword(ctx) - if ctx.Written() { - return - } - - ctx.HTML(http.StatusOK, tplResetPassword) -} - -// ResetPasswdPost response from account recovery request -func ResetPasswdPost(ctx *context.Context) { - u, twofa := commonResetPassword(ctx) - if ctx.Written() { - return - } - - if u == nil { - // Flash error has been set - ctx.HTML(http.StatusOK, tplResetPassword) - return - } - - // Validate password length. - passwd := ctx.FormString("password") - if len(passwd) < setting.MinPasswordLength { - ctx.Data["IsResetForm"] = true - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil) - return - } else if !password.IsComplexEnough(passwd) { - ctx.Data["IsResetForm"] = true - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(password.BuildComplexityError(ctx), tplResetPassword, nil) - return - } else if pwned, err := password.IsPwned(ctx, passwd); pwned || err != nil { - errMsg := ctx.Tr("auth.password_pwned") - if err != nil { - log.Error(err.Error()) - errMsg = ctx.Tr("auth.password_pwned_err") - } - ctx.Data["IsResetForm"] = true - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(errMsg, tplResetPassword, nil) - return - } - - // Handle two-factor - regenerateScratchToken := false - if twofa != nil { - if ctx.FormBool("scratch_code") { - if !twofa.VerifyScratchToken(ctx.FormString("token")) { - ctx.Data["IsResetForm"] = true - ctx.Data["Err_Token"] = true - ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplResetPassword, nil) - return - } - regenerateScratchToken = true - } else { - passcode := ctx.FormString("passcode") - ok, err := twofa.ValidateTOTP(passcode) - if err != nil { - ctx.Error(http.StatusInternalServerError, "ValidateTOTP", err.Error()) - return - } - if !ok || twofa.LastUsedPasscode == passcode { - ctx.Data["IsResetForm"] = true - ctx.Data["Err_Passcode"] = true - ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplResetPassword, nil) - return - } - - twofa.LastUsedPasscode = passcode - if err = login.UpdateTwoFactor(twofa); err != nil { - ctx.ServerError("ResetPasswdPost: UpdateTwoFactor", err) - return - } - } - } - var err error - if u.Rands, err = user_model.GetUserSalt(); err != nil { - ctx.ServerError("UpdateUser", err) - return - } - if err = u.SetPassword(passwd); err != nil { - ctx.ServerError("UpdateUser", err) - return - } - u.MustChangePassword = false - if err := user_model.UpdateUserCols(db.DefaultContext, u, "must_change_password", "passwd", "passwd_hash_algo", "rands", "salt"); err != nil { - ctx.ServerError("UpdateUser", err) - return - } - - log.Trace("User password reset: %s", u.Name) - ctx.Data["IsResetFailed"] = true - remember := len(ctx.FormString("remember")) != 0 - - if regenerateScratchToken { - // Invalidate the scratch token. - _, err = twofa.GenerateScratchToken() - if err != nil { - ctx.ServerError("UserSignIn", err) - return - } - if err = login.UpdateTwoFactor(twofa); err != nil { - ctx.ServerError("UserSignIn", err) - return - } - - handleSignInFull(ctx, u, remember, false) - ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used")) - if ctx.Written() { - return - } - ctx.Redirect(setting.AppSubURL + "/user/settings/security") - return - } - - handleSignIn(ctx, u, remember) -} - -// MustChangePassword renders the page to change a user's password -func MustChangePassword(ctx *context.Context) { - ctx.Data["Title"] = ctx.Tr("auth.must_change_password") - ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password" - ctx.Data["MustChangePassword"] = true - ctx.HTML(http.StatusOK, tplMustChangePassword) -} - -// MustChangePasswordPost response for updating a user's password after his/her -// account was created by an admin -func MustChangePasswordPost(ctx *context.Context) { - form := web.GetForm(ctx).(*forms.MustChangePasswordForm) - ctx.Data["Title"] = ctx.Tr("auth.must_change_password") - ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password" - if ctx.HasError() { - ctx.HTML(http.StatusOK, tplMustChangePassword) - return - } - u := ctx.User - // Make sure only requests for users who are eligible to change their password via - // this method passes through - if !u.MustChangePassword { - ctx.ServerError("MustUpdatePassword", errors.New("cannot update password.. Please visit the settings page")) - return - } - - if form.Password != form.Retype { - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplMustChangePassword, &form) - return - } - - if len(form.Password) < setting.MinPasswordLength { - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplMustChangePassword, &form) - return - } - if !password.IsComplexEnough(form.Password) { - ctx.Data["Err_Password"] = true - ctx.RenderWithErr(password.BuildComplexityError(ctx), tplMustChangePassword, &form) - return - } - pwned, err := password.IsPwned(ctx, form.Password) - if pwned { - ctx.Data["Err_Password"] = true - errMsg := ctx.Tr("auth.password_pwned") - if err != nil { - log.Error(err.Error()) - errMsg = ctx.Tr("auth.password_pwned_err") - } - ctx.RenderWithErr(errMsg, tplMustChangePassword, &form) - return - } - - if err = u.SetPassword(form.Password); err != nil { - ctx.ServerError("UpdateUser", err) - return - } - - u.MustChangePassword = false - - if err := user_model.UpdateUserCols(db.DefaultContext, u, "must_change_password", "passwd", "passwd_hash_algo", "salt"); err != nil { - ctx.ServerError("UpdateUser", err) - return - } - - ctx.Flash.Success(ctx.Tr("settings.change_password_success")) - - log.Trace("User updated password: %s", u.Name) - - if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 && !utils.IsExternalURL(redirectTo) { - middleware.DeleteRedirectToCookie(ctx.Resp) - ctx.RedirectToFirst(redirectTo) - return - } - - ctx.Redirect(setting.AppSubURL + "/") -} diff --git a/routers/web/user/setting/applications.go b/routers/web/user/setting/applications.go index 9976337bfa..20ffdfaf84 100644 --- a/routers/web/user/setting/applications.go +++ b/routers/web/user/setting/applications.go @@ -9,7 +9,7 @@ import ( "net/http" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" @@ -93,12 +93,12 @@ func loadApplicationsData(ctx *context.Context) { ctx.Data["Tokens"] = tokens ctx.Data["EnableOAuth2"] = setting.OAuth2.Enable if setting.OAuth2.Enable { - ctx.Data["Applications"], err = login.GetOAuth2ApplicationsByUserID(ctx.User.ID) + ctx.Data["Applications"], err = auth.GetOAuth2ApplicationsByUserID(ctx.User.ID) if err != nil { ctx.ServerError("GetOAuth2ApplicationsByUserID", err) return } - ctx.Data["Grants"], err = login.GetOAuth2GrantsByUserID(ctx.User.ID) + ctx.Data["Grants"], err = auth.GetOAuth2GrantsByUserID(ctx.User.ID) if err != nil { ctx.ServerError("GetOAuth2GrantsByUserID", err) return diff --git a/routers/web/user/setting/keys.go b/routers/web/user/setting/keys.go index 8274f8b1b3..26bbf7c195 100644 --- a/routers/web/user/setting/keys.go +++ b/routers/web/user/setting/keys.go @@ -216,7 +216,6 @@ func KeysPost(ctx *context.Context) { // DeleteKey response for delete user's SSH/GPG key func DeleteKey(ctx *context.Context) { - switch ctx.FormString("type") { case "gpg": if err := asymkey_model.DeleteGPGKey(ctx.User, ctx.FormInt64("id")); err != nil { diff --git a/routers/web/user/setting/oauth2.go b/routers/web/user/setting/oauth2.go index 0f338ab5d1..65d0924da0 100644 --- a/routers/web/user/setting/oauth2.go +++ b/routers/web/user/setting/oauth2.go @@ -8,7 +8,7 @@ import ( "fmt" "net/http" - "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" @@ -34,7 +34,7 @@ func OAuthApplicationsPost(ctx *context.Context) { return } // TODO validate redirect URI - app, err := login.CreateOAuth2Application(login.CreateOAuth2ApplicationOptions{ + app, err := auth.CreateOAuth2Application(auth.CreateOAuth2ApplicationOptions{ Name: form.Name, RedirectURIs: []string{form.RedirectURI}, UserID: ctx.User.ID, @@ -67,7 +67,7 @@ func OAuthApplicationsEdit(ctx *context.Context) { } // TODO validate redirect URI var err error - if ctx.Data["App"], err = login.UpdateOAuth2Application(login.UpdateOAuth2ApplicationOptions{ + if ctx.Data["App"], err = auth.UpdateOAuth2Application(auth.UpdateOAuth2ApplicationOptions{ ID: ctx.ParamsInt64("id"), Name: form.Name, RedirectURIs: []string{form.RedirectURI}, @@ -85,9 +85,9 @@ func OAuthApplicationsRegenerateSecret(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsApplications"] = true - app, err := login.GetOAuth2ApplicationByID(ctx.ParamsInt64("id")) + app, err := auth.GetOAuth2ApplicationByID(ctx.ParamsInt64("id")) if err != nil { - if login.IsErrOAuthApplicationNotFound(err) { + if auth.IsErrOAuthApplicationNotFound(err) { ctx.NotFound("Application not found", err) return } @@ -110,9 +110,9 @@ func OAuthApplicationsRegenerateSecret(ctx *context.Context) { // OAuth2ApplicationShow displays the given application func OAuth2ApplicationShow(ctx *context.Context) { - app, err := login.GetOAuth2ApplicationByID(ctx.ParamsInt64("id")) + app, err := auth.GetOAuth2ApplicationByID(ctx.ParamsInt64("id")) if err != nil { - if login.IsErrOAuthApplicationNotFound(err) { + if auth.IsErrOAuthApplicationNotFound(err) { ctx.NotFound("Application not found", err) return } @@ -129,7 +129,7 @@ func OAuth2ApplicationShow(ctx *context.Context) { // DeleteOAuth2Application deletes the given oauth2 application func DeleteOAuth2Application(ctx *context.Context) { - if err := login.DeleteOAuth2Application(ctx.FormInt64("id"), ctx.User.ID); err != nil { + if err := auth.DeleteOAuth2Application(ctx.FormInt64("id"), ctx.User.ID); err != nil { ctx.ServerError("DeleteOAuth2Application", err) return } @@ -147,7 +147,7 @@ func RevokeOAuth2Grant(ctx *context.Context) { ctx.ServerError("RevokeOAuth2Grant", fmt.Errorf("user id or grant id is zero")) return } - if err := login.RevokeOAuth2Grant(ctx.FormInt64("id"), ctx.User.ID); err != nil { + if err := auth.RevokeOAuth2Grant(ctx.FormInt64("id"), ctx.User.ID); err != nil { ctx.ServerError("RevokeOAuth2Grant", err) return } diff --git a/routers/web/user/setting/security_twofa.go b/routers/web/user/setting/security/2fa.go index 94f975f9fe..98e1f9b083 100644 --- a/routers/web/user/setting/security_twofa.go +++ b/routers/web/user/setting/security/2fa.go @@ -3,7 +3,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package setting +package security import ( "bytes" @@ -13,7 +13,7 @@ import ( "net/http" "strings" - "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -29,9 +29,9 @@ func RegenerateScratchTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := login.GetTwoFactorByUID(ctx.User.ID) + t, err := auth.GetTwoFactorByUID(ctx.User.ID) if err != nil { - if login.IsErrTwoFactorNotEnrolled(err) { + if auth.IsErrTwoFactorNotEnrolled(err) { ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled")) ctx.Redirect(setting.AppSubURL + "/user/settings/security") } @@ -45,7 +45,7 @@ func RegenerateScratchTwoFactor(ctx *context.Context) { return } - if err = login.UpdateTwoFactor(t); err != nil { + if err = auth.UpdateTwoFactor(t); err != nil { ctx.ServerError("SettingsTwoFactor: Failed to UpdateTwoFactor", err) return } @@ -59,9 +59,9 @@ func DisableTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := login.GetTwoFactorByUID(ctx.User.ID) + t, err := auth.GetTwoFactorByUID(ctx.User.ID) if err != nil { - if login.IsErrTwoFactorNotEnrolled(err) { + if auth.IsErrTwoFactorNotEnrolled(err) { ctx.Flash.Error(ctx.Tr("settings.twofa_not_enrolled")) ctx.Redirect(setting.AppSubURL + "/user/settings/security") } @@ -69,8 +69,8 @@ func DisableTwoFactor(ctx *context.Context) { return } - if err = login.DeleteTwoFactorByID(t.ID, ctx.User.ID); err != nil { - if login.IsErrTwoFactorNotEnrolled(err) { + if err = auth.DeleteTwoFactorByID(t.ID, ctx.User.ID); err != nil { + if auth.IsErrTwoFactorNotEnrolled(err) { // There is a potential DB race here - we must have been disabled by another request in the intervening period ctx.Flash.Success(ctx.Tr("settings.twofa_disabled")) ctx.Redirect(setting.AppSubURL + "/user/settings/security") @@ -146,7 +146,7 @@ func EnrollTwoFactor(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := login.GetTwoFactorByUID(ctx.User.ID) + t, err := auth.GetTwoFactorByUID(ctx.User.ID) if t != nil { // already enrolled - we should redirect back! log.Warn("Trying to re-enroll %-v in twofa when already enrolled", ctx.User) @@ -154,7 +154,7 @@ func EnrollTwoFactor(ctx *context.Context) { ctx.Redirect(setting.AppSubURL + "/user/settings/security") return } - if err != nil && !login.IsErrTwoFactorNotEnrolled(err) { + if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("SettingsTwoFactor: GetTwoFactorByUID", err) return } @@ -172,14 +172,14 @@ func EnrollTwoFactorPost(ctx *context.Context) { ctx.Data["Title"] = ctx.Tr("settings") ctx.Data["PageIsSettingsSecurity"] = true - t, err := login.GetTwoFactorByUID(ctx.User.ID) + t, err := auth.GetTwoFactorByUID(ctx.User.ID) if t != nil { // already enrolled ctx.Flash.Error(ctx.Tr("settings.twofa_is_enrolled")) ctx.Redirect(setting.AppSubURL + "/user/settings/security") return } - if err != nil && !login.IsErrTwoFactorNotEnrolled(err) { + if err != nil && !auth.IsErrTwoFactorNotEnrolled(err) { ctx.ServerError("SettingsTwoFactor: Failed to check if already enrolled with GetTwoFactorByUID", err) return } @@ -209,7 +209,7 @@ func EnrollTwoFactorPost(ctx *context.Context) { return } - t = &login.TwoFactor{ + t = &auth.TwoFactor{ UID: ctx.User.ID, } err = t.SetSecret(secret) @@ -238,7 +238,7 @@ func EnrollTwoFactorPost(ctx *context.Context) { log.Error("Unable to save changes to the session: %v", err) } - if err = login.NewTwoFactor(t); err != nil { + if err = auth.NewTwoFactor(t); err != nil { // FIXME: We need to handle a unique constraint fail here it's entirely possible that another request has beaten us. // If there is a unique constraint fail we should just tolerate the error ctx.ServerError("SettingsTwoFactor: Failed to save two factor", err) diff --git a/routers/web/user/setting/security_openid.go b/routers/web/user/setting/security/openid.go index 9cdda79b92..1a15a2414c 100644 --- a/routers/web/user/setting/security_openid.go +++ b/routers/web/user/setting/security/openid.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package setting +package security import ( "net/http" diff --git a/routers/web/user/setting/security.go b/routers/web/user/setting/security/security.go index d34de519b7..0ca6503f05 100644 --- a/routers/web/user/setting/security.go +++ b/routers/web/user/setting/security/security.go @@ -3,13 +3,13 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package setting +package security import ( "net/http" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/auth" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -17,8 +17,8 @@ import ( ) const ( - tplSettingsSecurity base.TplName = "user/settings/security" - tplSettingsTwofaEnroll base.TplName = "user/settings/twofa_enroll" + tplSettingsSecurity base.TplName = "user/settings/security/security" + tplSettingsTwofaEnroll base.TplName = "user/settings/security/twofa_enroll" ) // Security render change user's password page and 2FA @@ -56,14 +56,14 @@ func DeleteAccountLink(ctx *context.Context) { } func loadSecurityData(ctx *context.Context) { - enrolled, err := login.HasTwoFactorByUID(ctx.User.ID) + enrolled, err := auth.HasTwoFactorByUID(ctx.User.ID) if err != nil { ctx.ServerError("SettingsTwoFactor", err) return } ctx.Data["TOTPEnrolled"] = enrolled - ctx.Data["U2FRegistrations"], err = login.GetU2FRegistrationsByUID(ctx.User.ID) + ctx.Data["U2FRegistrations"], err = auth.GetU2FRegistrationsByUID(ctx.User.ID) if err != nil { ctx.ServerError("GetU2FRegistrationsByUID", err) return @@ -82,10 +82,10 @@ func loadSecurityData(ctx *context.Context) { return } - // map the provider display name with the LoginSource - sources := make(map[*login.Source]string) + // map the provider display name with the AuthSource + sources := make(map[*auth.Source]string) for _, externalAccount := range accountLinks { - if loginSource, err := login.GetSourceByID(externalAccount.LoginSourceID); err == nil { + if authSource, err := auth.GetSourceByID(externalAccount.LoginSourceID); err == nil { var providerDisplayName string type DisplayNamed interface { @@ -96,14 +96,14 @@ func loadSecurityData(ctx *context.Context) { Name() string } - if displayNamed, ok := loginSource.Cfg.(DisplayNamed); ok { + if displayNamed, ok := authSource.Cfg.(DisplayNamed); ok { providerDisplayName = displayNamed.DisplayName() - } else if named, ok := loginSource.Cfg.(Named); ok { + } else if named, ok := authSource.Cfg.(Named); ok { providerDisplayName = named.Name() } else { - providerDisplayName = loginSource.Name + providerDisplayName = authSource.Name } - sources[loginSource] = providerDisplayName + sources[authSource] = providerDisplayName } } ctx.Data["AccountLinks"] = sources diff --git a/routers/web/user/setting/security_u2f.go b/routers/web/user/setting/security/u2f.go index d1d6d1e8ca..dd35a893f4 100644 --- a/routers/web/user/setting/security_u2f.go +++ b/routers/web/user/setting/security/u2f.go @@ -2,13 +2,13 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package setting +package security import ( "errors" "net/http" - "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -34,7 +34,7 @@ func U2FRegister(ctx *context.Context) { ctx.ServerError("Unable to set session key for u2fChallenge", err) return } - regs, err := login.GetU2FRegistrationsByUID(ctx.User.ID) + regs, err := auth.GetU2FRegistrationsByUID(ctx.User.ID) if err != nil { ctx.ServerError("GetU2FRegistrationsByUID", err) return @@ -78,7 +78,7 @@ func U2FRegisterPost(ctx *context.Context) { ctx.ServerError("u2f.Register", err) return } - if _, err = login.CreateRegistration(ctx.User.ID, name, reg); err != nil { + if _, err = auth.CreateRegistration(ctx.User.ID, name, reg); err != nil { ctx.ServerError("u2f.Register", err) return } @@ -88,9 +88,9 @@ func U2FRegisterPost(ctx *context.Context) { // U2FDelete deletes an security key by id func U2FDelete(ctx *context.Context) { form := web.GetForm(ctx).(*forms.U2FDeleteForm) - reg, err := login.GetU2FRegistrationByID(form.ID) + reg, err := auth.GetU2FRegistrationByID(form.ID) if err != nil { - if login.IsErrU2FRegistrationNotExist(err) { + if auth.IsErrU2FRegistrationNotExist(err) { ctx.Status(200) return } @@ -101,7 +101,7 @@ func U2FDelete(ctx *context.Context) { ctx.Status(401) return } - if err := login.DeleteRegistration(reg); err != nil { + if err := auth.DeleteRegistration(reg); err != nil { ctx.ServerError("DeleteRegistration", err) return } diff --git a/routers/web/web.go b/routers/web/web.go index 486255096d..3589ec9bd6 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -24,14 +24,16 @@ import ( "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/api/v1/misc" "code.gitea.io/gitea/routers/web/admin" + "code.gitea.io/gitea/routers/web/auth" "code.gitea.io/gitea/routers/web/dev" "code.gitea.io/gitea/routers/web/events" "code.gitea.io/gitea/routers/web/explore" "code.gitea.io/gitea/routers/web/org" "code.gitea.io/gitea/routers/web/repo" "code.gitea.io/gitea/routers/web/user" - userSetting "code.gitea.io/gitea/routers/web/user/setting" - "code.gitea.io/gitea/services/auth" + user_setting "code.gitea.io/gitea/routers/web/user/setting" + "code.gitea.io/gitea/routers/web/user/setting/security" + auth_service "code.gitea.io/gitea/services/auth" "code.gitea.io/gitea/services/forms" "code.gitea.io/gitea/services/lfs" "code.gitea.io/gitea/services/mailer" @@ -154,7 +156,7 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route { common = append(common, context.Contexter()) // Get user from session if logged in. - common = append(common, context.Auth(auth.NewGroup(auth.Methods()...))) + common = append(common, context.Auth(auth_service.NewGroup(auth_service.Methods()...))) // GetHead allows a HEAD request redirect to GET if HEAD method is not defined for that route common = append(common, middleware.GetHead) @@ -233,7 +235,7 @@ func RegisterRoutes(m *web.Route) { // for health check m.Get("/", Home) m.Group("/.well-known", func() { - m.Get("/openid-configuration", user.OIDCWellKnown) + m.Get("/openid-configuration", auth.OIDCWellKnown) if setting.Federation.Enabled { m.Get("/nodeinfo", NodeInfoLinks) } @@ -257,42 +259,42 @@ func RegisterRoutes(m *web.Route) { // ***** START: User ***** m.Group("/user", func() { - m.Get("/login", user.SignIn) - m.Post("/login", bindIgnErr(forms.SignInForm{}), user.SignInPost) + m.Get("/login", auth.SignIn) + m.Post("/login", bindIgnErr(forms.SignInForm{}), auth.SignInPost) m.Group("", func() { m.Combo("/login/openid"). - Get(user.SignInOpenID). - Post(bindIgnErr(forms.SignInOpenIDForm{}), user.SignInOpenIDPost) + Get(auth.SignInOpenID). + Post(bindIgnErr(forms.SignInOpenIDForm{}), auth.SignInOpenIDPost) }, openIDSignInEnabled) m.Group("/openid", func() { m.Combo("/connect"). - Get(user.ConnectOpenID). - Post(bindIgnErr(forms.ConnectOpenIDForm{}), user.ConnectOpenIDPost) + Get(auth.ConnectOpenID). + Post(bindIgnErr(forms.ConnectOpenIDForm{}), auth.ConnectOpenIDPost) m.Group("/register", func() { m.Combo(""). - Get(user.RegisterOpenID, openIDSignUpEnabled). - Post(bindIgnErr(forms.SignUpOpenIDForm{}), user.RegisterOpenIDPost) + Get(auth.RegisterOpenID, openIDSignUpEnabled). + Post(bindIgnErr(forms.SignUpOpenIDForm{}), auth.RegisterOpenIDPost) }, openIDSignUpEnabled) }, openIDSignInEnabled) - m.Get("/sign_up", user.SignUp) - m.Post("/sign_up", bindIgnErr(forms.RegisterForm{}), user.SignUpPost) + m.Get("/sign_up", auth.SignUp) + m.Post("/sign_up", bindIgnErr(forms.RegisterForm{}), auth.SignUpPost) m.Group("/oauth2", func() { - m.Get("/{provider}", user.SignInOAuth) - m.Get("/{provider}/callback", user.SignInOAuthCallback) + m.Get("/{provider}", auth.SignInOAuth) + m.Get("/{provider}/callback", auth.SignInOAuthCallback) }) - m.Get("/link_account", user.LinkAccount) - m.Post("/link_account_signin", bindIgnErr(forms.SignInForm{}), user.LinkAccountPostSignIn) - m.Post("/link_account_signup", bindIgnErr(forms.RegisterForm{}), user.LinkAccountPostRegister) + m.Get("/link_account", auth.LinkAccount) + m.Post("/link_account_signin", bindIgnErr(forms.SignInForm{}), auth.LinkAccountPostSignIn) + m.Post("/link_account_signup", bindIgnErr(forms.RegisterForm{}), auth.LinkAccountPostRegister) m.Group("/two_factor", func() { - m.Get("", user.TwoFactor) - m.Post("", bindIgnErr(forms.TwoFactorAuthForm{}), user.TwoFactorPost) - m.Get("/scratch", user.TwoFactorScratch) - m.Post("/scratch", bindIgnErr(forms.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost) + m.Get("", auth.TwoFactor) + m.Post("", bindIgnErr(forms.TwoFactorAuthForm{}), auth.TwoFactorPost) + m.Get("/scratch", auth.TwoFactorScratch) + m.Post("/scratch", bindIgnErr(forms.TwoFactorScratchAuthForm{}), auth.TwoFactorScratchPost) }) m.Group("/u2f", func() { - m.Get("", user.U2F) - m.Get("/challenge", user.U2FChallenge) - m.Post("/sign", bindIgnErr(u2f.SignResponse{}), user.U2FSign) + m.Get("", auth.U2F) + m.Get("/challenge", auth.U2FChallenge) + m.Post("/sign", bindIgnErr(u2f.SignResponse{}), auth.U2FSign) }) }, reqSignOut) @@ -300,71 +302,71 @@ func RegisterRoutes(m *web.Route) { m.Any("/user/events", events.Events) m.Group("/login/oauth", func() { - m.Get("/authorize", bindIgnErr(forms.AuthorizationForm{}), user.AuthorizeOAuth) - m.Post("/grant", bindIgnErr(forms.GrantApplicationForm{}), user.GrantApplicationOAuth) + m.Get("/authorize", bindIgnErr(forms.AuthorizationForm{}), auth.AuthorizeOAuth) + m.Post("/grant", bindIgnErr(forms.GrantApplicationForm{}), auth.GrantApplicationOAuth) // TODO manage redirection - m.Post("/authorize", bindIgnErr(forms.AuthorizationForm{}), user.AuthorizeOAuth) + m.Post("/authorize", bindIgnErr(forms.AuthorizationForm{}), auth.AuthorizeOAuth) }, ignSignInAndCsrf, reqSignIn) - m.Get("/login/oauth/userinfo", ignSignInAndCsrf, user.InfoOAuth) - m.Post("/login/oauth/access_token", CorsHandler(), bindIgnErr(forms.AccessTokenForm{}), ignSignInAndCsrf, user.AccessTokenOAuth) - m.Get("/login/oauth/keys", ignSignInAndCsrf, user.OIDCKeys) - m.Post("/login/oauth/introspect", CorsHandler(), bindIgnErr(forms.IntrospectTokenForm{}), ignSignInAndCsrf, user.IntrospectOAuth) + m.Get("/login/oauth/userinfo", ignSignInAndCsrf, auth.InfoOAuth) + m.Post("/login/oauth/access_token", CorsHandler(), bindIgnErr(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth) + m.Get("/login/oauth/keys", ignSignInAndCsrf, auth.OIDCKeys) + m.Post("/login/oauth/introspect", CorsHandler(), bindIgnErr(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth) m.Group("/user/settings", func() { - m.Get("", userSetting.Profile) - m.Post("", bindIgnErr(forms.UpdateProfileForm{}), userSetting.ProfilePost) - m.Get("/change_password", user.MustChangePassword) - m.Post("/change_password", bindIgnErr(forms.MustChangePasswordForm{}), user.MustChangePasswordPost) - m.Post("/avatar", bindIgnErr(forms.AvatarForm{}), userSetting.AvatarPost) - m.Post("/avatar/delete", userSetting.DeleteAvatar) + m.Get("", user_setting.Profile) + m.Post("", bindIgnErr(forms.UpdateProfileForm{}), user_setting.ProfilePost) + m.Get("/change_password", auth.MustChangePassword) + m.Post("/change_password", bindIgnErr(forms.MustChangePasswordForm{}), auth.MustChangePasswordPost) + m.Post("/avatar", bindIgnErr(forms.AvatarForm{}), user_setting.AvatarPost) + m.Post("/avatar/delete", user_setting.DeleteAvatar) m.Group("/account", func() { - m.Combo("").Get(userSetting.Account).Post(bindIgnErr(forms.ChangePasswordForm{}), userSetting.AccountPost) - m.Post("/email", bindIgnErr(forms.AddEmailForm{}), userSetting.EmailPost) - m.Post("/email/delete", userSetting.DeleteEmail) - m.Post("/delete", userSetting.DeleteAccount) + m.Combo("").Get(user_setting.Account).Post(bindIgnErr(forms.ChangePasswordForm{}), user_setting.AccountPost) + m.Post("/email", bindIgnErr(forms.AddEmailForm{}), user_setting.EmailPost) + m.Post("/email/delete", user_setting.DeleteEmail) + m.Post("/delete", user_setting.DeleteAccount) }) m.Group("/appearance", func() { - m.Get("", userSetting.Appearance) - m.Post("/language", bindIgnErr(forms.UpdateLanguageForm{}), userSetting.UpdateUserLang) - m.Post("/theme", bindIgnErr(forms.UpdateThemeForm{}), userSetting.UpdateUIThemePost) + m.Get("", user_setting.Appearance) + m.Post("/language", bindIgnErr(forms.UpdateLanguageForm{}), user_setting.UpdateUserLang) + m.Post("/theme", bindIgnErr(forms.UpdateThemeForm{}), user_setting.UpdateUIThemePost) }) m.Group("/security", func() { - m.Get("", userSetting.Security) + m.Get("", security.Security) m.Group("/two_factor", func() { - m.Post("/regenerate_scratch", userSetting.RegenerateScratchTwoFactor) - m.Post("/disable", userSetting.DisableTwoFactor) - m.Get("/enroll", userSetting.EnrollTwoFactor) - m.Post("/enroll", bindIgnErr(forms.TwoFactorAuthForm{}), userSetting.EnrollTwoFactorPost) + m.Post("/regenerate_scratch", security.RegenerateScratchTwoFactor) + m.Post("/disable", security.DisableTwoFactor) + m.Get("/enroll", security.EnrollTwoFactor) + m.Post("/enroll", bindIgnErr(forms.TwoFactorAuthForm{}), security.EnrollTwoFactorPost) }) m.Group("/u2f", func() { - m.Post("/request_register", bindIgnErr(forms.U2FRegistrationForm{}), userSetting.U2FRegister) - m.Post("/register", bindIgnErr(u2f.RegisterResponse{}), userSetting.U2FRegisterPost) - m.Post("/delete", bindIgnErr(forms.U2FDeleteForm{}), userSetting.U2FDelete) + m.Post("/request_register", bindIgnErr(forms.U2FRegistrationForm{}), security.U2FRegister) + m.Post("/register", bindIgnErr(u2f.RegisterResponse{}), security.U2FRegisterPost) + m.Post("/delete", bindIgnErr(forms.U2FDeleteForm{}), security.U2FDelete) }) m.Group("/openid", func() { - m.Post("", bindIgnErr(forms.AddOpenIDForm{}), userSetting.OpenIDPost) - m.Post("/delete", userSetting.DeleteOpenID) - m.Post("/toggle_visibility", userSetting.ToggleOpenIDVisibility) + m.Post("", bindIgnErr(forms.AddOpenIDForm{}), security.OpenIDPost) + m.Post("/delete", security.DeleteOpenID) + m.Post("/toggle_visibility", security.ToggleOpenIDVisibility) }, openIDSignInEnabled) - m.Post("/account_link", userSetting.DeleteAccountLink) + m.Post("/account_link", security.DeleteAccountLink) }) m.Group("/applications/oauth2", func() { - m.Get("/{id}", userSetting.OAuth2ApplicationShow) - m.Post("/{id}", bindIgnErr(forms.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsEdit) - m.Post("/{id}/regenerate_secret", userSetting.OAuthApplicationsRegenerateSecret) - m.Post("", bindIgnErr(forms.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsPost) - m.Post("/delete", userSetting.DeleteOAuth2Application) - m.Post("/revoke", userSetting.RevokeOAuth2Grant) + m.Get("/{id}", user_setting.OAuth2ApplicationShow) + m.Post("/{id}", bindIgnErr(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsEdit) + m.Post("/{id}/regenerate_secret", user_setting.OAuthApplicationsRegenerateSecret) + m.Post("", bindIgnErr(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsPost) + m.Post("/delete", user_setting.DeleteOAuth2Application) + m.Post("/revoke", user_setting.RevokeOAuth2Grant) }) - m.Combo("/applications").Get(userSetting.Applications). - Post(bindIgnErr(forms.NewAccessTokenForm{}), userSetting.ApplicationsPost) - m.Post("/applications/delete", userSetting.DeleteApplication) - m.Combo("/keys").Get(userSetting.Keys). - Post(bindIgnErr(forms.AddKeyForm{}), userSetting.KeysPost) - m.Post("/keys/delete", userSetting.DeleteKey) - m.Get("/organization", userSetting.Organization) - m.Get("/repos", userSetting.Repos) - m.Post("/repos/unadopted", userSetting.AdoptOrDeleteRepository) + m.Combo("/applications").Get(user_setting.Applications). + Post(bindIgnErr(forms.NewAccessTokenForm{}), user_setting.ApplicationsPost) + m.Post("/applications/delete", user_setting.DeleteApplication) + m.Combo("/keys").Get(user_setting.Keys). + Post(bindIgnErr(forms.AddKeyForm{}), user_setting.KeysPost) + m.Post("/keys/delete", user_setting.DeleteKey) + m.Get("/organization", user_setting.Organization) + m.Get("/repos", user_setting.Repos) + m.Post("/repos/unadopted", user_setting.AdoptOrDeleteRepository) }, reqSignIn, func(ctx *context.Context) { ctx.Data["PageIsUserSettings"] = true ctx.Data["AllThemes"] = setting.UI.Themes @@ -372,15 +374,15 @@ func RegisterRoutes(m *web.Route) { m.Group("/user", func() { // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds) - m.Get("/activate", user.Activate, reqSignIn) - m.Post("/activate", user.ActivatePost, reqSignIn) - m.Any("/activate_email", user.ActivateEmail) + m.Get("/activate", auth.Activate, reqSignIn) + m.Post("/activate", auth.ActivatePost, reqSignIn) + m.Any("/activate_email", auth.ActivateEmail) m.Get("/avatar/{username}/{size}", user.AvatarByUserName) - m.Get("/recover_account", user.ResetPasswd) - m.Post("/recover_account", user.ResetPasswdPost) - m.Get("/forgot_password", user.ForgotPasswd) - m.Post("/forgot_password", user.ForgotPasswdPost) - m.Post("/logout", user.SignOut) + m.Get("/recover_account", auth.ResetPasswd) + m.Post("/recover_account", auth.ResetPasswdPost) + m.Get("/forgot_password", auth.ForgotPasswd) + m.Post("/forgot_password", auth.ForgotPasswdPost) + m.Post("/logout", auth.SignOut) m.Get("/task/{task}", user.TaskStatus) }) // ***** END: User ***** |