Browse Source

routes/user/auth: improve coding style

pull/5238/merge
Unknwon 7 years ago
parent
commit
05edcde6c9
No known key found for this signature in database
GPG Key ID: 7A02C406FAC875A2
  1. 5
      models/user_cache.go
  2. 122
      routes/user/auth.go

5
models/user_cache.go

@ -4,6 +4,11 @@
package models package models
// MailResendCacheKey returns key used for cache mail resend.
func (u *User) MailResendCacheKey() string {
return "MailResend_" + u.IDStr()
}
// TwoFactorCacheKey returns key used for cache two factor passcode. // TwoFactorCacheKey returns key used for cache two factor passcode.
// e.g. TwoFactor_1_012664 // e.g. TwoFactor_1_012664
func (u *User) TwoFactorCacheKey(passcode string) string { func (u *User) TwoFactorCacheKey(passcode string) string {

122
routes/user/auth.go

@ -100,7 +100,7 @@ func Login(c *context.Context) {
if isValidRedirect(redirectTo) { if isValidRedirect(redirectTo) {
c.Redirect(redirectTo) c.Redirect(redirectTo)
} else { } else {
c.Redirect(setting.AppSubURL + "/") c.SubURLRedirect("/")
} }
c.SetCookie("redirect_to", "", -1, setting.AppSubURL) c.SetCookie("redirect_to", "", -1, setting.AppSubURL)
return return
@ -142,7 +142,7 @@ func afterLogin(c *context.Context, u *models.User, remember bool) {
return return
} }
c.Redirect(setting.AppSubURL + "/") c.SubURLRedirect("/")
} }
func LoginPost(c *context.Context, f form.SignIn) { func LoginPost(c *context.Context, f form.SignIn) {
@ -164,8 +164,7 @@ func LoginPost(c *context.Context, f form.SignIn) {
if err != nil { if err != nil {
switch err.(type) { switch err.(type) {
case errors.UserNotExist: case errors.UserNotExist:
c.FormErr("UserName") c.FormErr("UserName", "Password")
c.FormErr("Password")
c.RenderWithErr(c.Tr("form.username_password_incorrect"), LOGIN, &f) c.RenderWithErr(c.Tr("form.username_password_incorrect"), LOGIN, &f)
case errors.LoginSourceMismatch: case errors.LoginSourceMismatch:
c.FormErr("LoginSource") c.FormErr("LoginSource")
@ -184,7 +183,7 @@ func LoginPost(c *context.Context, f form.SignIn) {
c.Session.Set("twoFactorRemember", f.Remember) c.Session.Set("twoFactorRemember", f.Remember)
c.Session.Set("twoFactorUserID", u.ID) c.Session.Set("twoFactorUserID", u.ID)
c.Redirect(setting.AppSubURL + "/user/login/two_factor") c.SubURLRedirect("/user/login/two_factor")
} }
func LoginTwoFactor(c *context.Context) { func LoginTwoFactor(c *context.Context) {
@ -217,7 +216,7 @@ func LoginTwoFactorPost(c *context.Context) {
return return
} else if !valid { } else if !valid {
c.Flash.Error(c.Tr("settings.two_factor_invalid_passcode")) c.Flash.Error(c.Tr("settings.two_factor_invalid_passcode"))
c.Redirect(setting.AppSubURL + "/user/login/two_factor") c.SubURLRedirect("/user/login/two_factor")
return return
} }
@ -230,7 +229,7 @@ func LoginTwoFactorPost(c *context.Context) {
// Prevent same passcode from being reused // Prevent same passcode from being reused
if c.Cache.IsExist(u.TwoFactorCacheKey(passcode)) { if c.Cache.IsExist(u.TwoFactorCacheKey(passcode)) {
c.Flash.Error(c.Tr("settings.two_factor_reused_passcode")) c.Flash.Error(c.Tr("settings.two_factor_reused_passcode"))
c.Redirect(setting.AppSubURL + "/user/login/two_factor") c.SubURLRedirect("/user/login/two_factor")
return return
} }
if err = c.Cache.Put(u.TwoFactorCacheKey(passcode), 1, 60); err != nil { if err = c.Cache.Put(u.TwoFactorCacheKey(passcode), 1, 60); err != nil {
@ -260,7 +259,7 @@ func LoginTwoFactorRecoveryCodePost(c *context.Context) {
if err := models.UseRecoveryCode(userID, c.Query("recovery_code")); err != nil { if err := models.UseRecoveryCode(userID, c.Query("recovery_code")); err != nil {
if errors.IsTwoFactorRecoveryCodeNotFound(err) { if errors.IsTwoFactorRecoveryCodeNotFound(err) {
c.Flash.Error(c.Tr("auth.login_two_factor_invalid_recovery_code")) c.Flash.Error(c.Tr("auth.login_two_factor_invalid_recovery_code"))
c.Redirect(setting.AppSubURL + "/user/login/two_factor_recovery_code") c.SubURLRedirect("/user/login/two_factor_recovery_code")
} else { } else {
c.ServerError("UseRecoveryCode", err) c.ServerError("UseRecoveryCode", err)
} }
@ -281,46 +280,46 @@ func SignOut(c *context.Context) {
c.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL) c.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
c.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL) c.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL) c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
c.Redirect(setting.AppSubURL + "/") c.SubURLRedirect("/")
} }
func SignUp(c *context.Context) { func SignUp(c *context.Context) {
c.Data["Title"] = c.Tr("sign_up") c.Title("sign_up")
c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
if setting.Service.DisableRegistration { if setting.Service.DisableRegistration {
c.Data["DisableRegistration"] = true c.Data["DisableRegistration"] = true
c.HTML(200, SIGNUP) c.Success(SIGNUP)
return return
} }
c.HTML(200, SIGNUP) c.Success(SIGNUP)
} }
func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) { func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
c.Data["Title"] = c.Tr("sign_up") c.Title("sign_up")
c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
if setting.Service.DisableRegistration { if setting.Service.DisableRegistration {
c.Error(403) c.Status(403)
return return
} }
if c.HasError() { if c.HasError() {
c.HTML(200, SIGNUP) c.Success(SIGNUP)
return return
} }
if setting.Service.EnableCaptcha && !cpt.VerifyReq(c.Req) { if setting.Service.EnableCaptcha && !cpt.VerifyReq(c.Req) {
c.Data["Err_Captcha"] = true c.FormErr("Captcha")
c.RenderWithErr(c.Tr("form.captcha_incorrect"), SIGNUP, &f) c.RenderWithErr(c.Tr("form.captcha_incorrect"), SIGNUP, &f)
return return
} }
if f.Password != f.Retype { if f.Password != f.Retype {
c.Data["Err_Password"] = true c.FormErr("Password")
c.RenderWithErr(c.Tr("form.password_not_match"), SIGNUP, &f) c.RenderWithErr(c.Tr("form.password_not_match"), SIGNUP, &f)
return return
} }
@ -334,19 +333,19 @@ func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
if err := models.CreateUser(u); err != nil { if err := models.CreateUser(u); err != nil {
switch { switch {
case models.IsErrUserAlreadyExist(err): case models.IsErrUserAlreadyExist(err):
c.Data["Err_UserName"] = true c.FormErr("UserName")
c.RenderWithErr(c.Tr("form.username_been_taken"), SIGNUP, &f) c.RenderWithErr(c.Tr("form.username_been_taken"), SIGNUP, &f)
case models.IsErrEmailAlreadyUsed(err): case models.IsErrEmailAlreadyUsed(err):
c.Data["Err_Email"] = true c.FormErr("Email")
c.RenderWithErr(c.Tr("form.email_been_used"), SIGNUP, &f) c.RenderWithErr(c.Tr("form.email_been_used"), SIGNUP, &f)
case models.IsErrNameReserved(err): case models.IsErrNameReserved(err):
c.Data["Err_UserName"] = true c.FormErr("UserName")
c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f) c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f)
case models.IsErrNamePatternNotAllowed(err): case models.IsErrNamePatternNotAllowed(err):
c.Data["Err_UserName"] = true c.FormErr("UserName")
c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f) c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f)
default: default:
c.Handle(500, "CreateUser", err) c.ServerError("CreateUser", err)
} }
return return
} }
@ -357,7 +356,7 @@ func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
u.IsAdmin = true u.IsAdmin = true
u.IsActive = true u.IsActive = true
if err := models.UpdateUser(u); err != nil { if err := models.UpdateUser(u); err != nil {
c.Handle(500, "UpdateUser", err) c.ServerError("UpdateUser", err)
return return
} }
} }
@ -368,15 +367,15 @@ func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
c.Data["IsSendRegisterMail"] = true c.Data["IsSendRegisterMail"] = true
c.Data["Email"] = u.Email c.Data["Email"] = u.Email
c.Data["Hours"] = setting.Service.ActiveCodeLives / 60 c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
c.HTML(200, ACTIVATE) c.Success(ACTIVATE)
if err := c.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { if err := c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
log.Error(4, "Set cache(MailResendLimit) fail: %v", err) log.Error(2, "Failed to put cache key 'mail resend': %v", err)
} }
return return
} }
c.Redirect(setting.AppSubURL + "/user/login") c.SubURLRedirect("/user/login")
} }
func Activate(c *context.Context) { func Activate(c *context.Context) {
@ -384,26 +383,25 @@ func Activate(c *context.Context) {
if len(code) == 0 { if len(code) == 0 {
c.Data["IsActivatePage"] = true c.Data["IsActivatePage"] = true
if c.User.IsActive { if c.User.IsActive {
c.Error(404) c.NotFound()
return return
} }
// Resend confirmation email. // Resend confirmation email.
if setting.Service.RegisterEmailConfirm { if setting.Service.RegisterEmailConfirm {
if c.Cache.IsExist("MailResendLimit_" + c.User.LowerName) { if c.Cache.IsExist(c.User.MailResendCacheKey()) {
c.Data["ResendLimited"] = true c.Data["ResendLimited"] = true
} else { } else {
c.Data["Hours"] = setting.Service.ActiveCodeLives / 60 c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(c.User)) mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(c.User))
keyName := "MailResendLimit_" + c.User.LowerName if err := c.Cache.Put(c.User.MailResendCacheKey(), 1, 180); err != nil {
if err := c.Cache.Put(keyName, c.User.LowerName, 180); err != nil { log.Error(2, "Failed to put cache key 'mail resend': %v", err)
log.Error(2, "Set cache '%s' fail: %v", keyName, err)
} }
} }
} else { } else {
c.Data["ServiceNotEnabled"] = true c.Data["ServiceNotEnabled"] = true
} }
c.HTML(200, ACTIVATE) c.Success(ACTIVATE)
return return
} }
@ -412,11 +410,11 @@ func Activate(c *context.Context) {
user.IsActive = true user.IsActive = true
var err error var err error
if user.Rands, err = models.GetUserSalt(); err != nil { if user.Rands, err = models.GetUserSalt(); err != nil {
c.Handle(500, "UpdateUser", err) c.ServerError("GetUserSalt", err)
return return
} }
if err := models.UpdateUser(user); err != nil { if err := models.UpdateUser(user); err != nil {
c.Handle(500, "UpdateUser", err) c.ServerError("UpdateUser", err)
return return
} }
@ -424,12 +422,12 @@ func Activate(c *context.Context) {
c.Session.Set("uid", user.ID) c.Session.Set("uid", user.ID)
c.Session.Set("uname", user.Name) c.Session.Set("uname", user.Name)
c.Redirect(setting.AppSubURL + "/") c.SubURLRedirect("/")
return return
} }
c.Data["IsActivateFailed"] = true c.Data["IsActivateFailed"] = true
c.HTML(200, ACTIVATE) c.Success(ACTIVATE)
} }
func ActivateEmail(c *context.Context) { func ActivateEmail(c *context.Context) {
@ -439,35 +437,35 @@ func ActivateEmail(c *context.Context) {
// Verify code. // Verify code.
if email := models.VerifyActiveEmailCode(code, email_string); email != nil { if email := models.VerifyActiveEmailCode(code, email_string); email != nil {
if err := email.Activate(); err != nil { if err := email.Activate(); err != nil {
c.Handle(500, "ActivateEmail", err) c.ServerError("ActivateEmail", err)
} }
log.Trace("Email activated: %s", email.Email) log.Trace("Email activated: %s", email.Email)
c.Flash.Success(c.Tr("settings.add_email_success")) c.Flash.Success(c.Tr("settings.add_email_success"))
} }
c.Redirect(setting.AppSubURL + "/user/settings/email") c.SubURLRedirect("/user/settings/email")
return return
} }
func ForgotPasswd(c *context.Context) { func ForgotPasswd(c *context.Context) {
c.Data["Title"] = c.Tr("auth.forgot_password") c.Title("auth.forgot_password")
if setting.MailService == nil { if setting.MailService == nil {
c.Data["IsResetDisable"] = true c.Data["IsResetDisable"] = true
c.HTML(200, FORGOT_PASSWORD) c.Success(FORGOT_PASSWORD)
return return
} }
c.Data["IsResetRequest"] = true c.Data["IsResetRequest"] = true
c.HTML(200, FORGOT_PASSWORD) c.Success(FORGOT_PASSWORD)
} }
func ForgotPasswdPost(c *context.Context) { func ForgotPasswdPost(c *context.Context) {
c.Data["Title"] = c.Tr("auth.forgot_password") c.Title("auth.forgot_password")
if setting.MailService == nil { if setting.MailService == nil {
c.Handle(403, "ForgotPasswdPost", nil) c.Status(403)
return return
} }
c.Data["IsResetRequest"] = true c.Data["IsResetRequest"] = true
@ -480,55 +478,55 @@ func ForgotPasswdPost(c *context.Context) {
if errors.IsUserNotExist(err) { if errors.IsUserNotExist(err) {
c.Data["Hours"] = setting.Service.ActiveCodeLives / 60 c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
c.Data["IsResetSent"] = true c.Data["IsResetSent"] = true
c.HTML(200, FORGOT_PASSWORD) c.Success(FORGOT_PASSWORD)
return return
} else { } else {
c.Handle(500, "user.ResetPasswd(check existence)", err) c.ServerError("GetUserByEmail", err)
} }
return return
} }
if !u.IsLocal() { if !u.IsLocal() {
c.Data["Err_Email"] = true c.FormErr("Email")
c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil) c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
return return
} }
if c.Cache.IsExist("MailResendLimit_" + u.LowerName) { if c.Cache.IsExist(u.MailResendCacheKey()) {
c.Data["ResendLimited"] = true c.Data["ResendLimited"] = true
c.HTML(200, FORGOT_PASSWORD) c.Success(FORGOT_PASSWORD)
return return
} }
mailer.SendResetPasswordMail(c.Context, models.NewMailerUser(u)) mailer.SendResetPasswordMail(c.Context, models.NewMailerUser(u))
if err = c.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { if err = c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
log.Error(4, "Set cache(MailResendLimit) fail: %v", err) log.Error(2, "Failed to put cache key 'mail resend': %v", err)
} }
c.Data["Hours"] = setting.Service.ActiveCodeLives / 60 c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
c.Data["IsResetSent"] = true c.Data["IsResetSent"] = true
c.HTML(200, FORGOT_PASSWORD) c.Success(FORGOT_PASSWORD)
} }
func ResetPasswd(c *context.Context) { func ResetPasswd(c *context.Context) {
c.Data["Title"] = c.Tr("auth.reset_password") c.Title("auth.reset_password")
code := c.Query("code") code := c.Query("code")
if len(code) == 0 { if len(code) == 0 {
c.Error(404) c.NotFound()
return return
} }
c.Data["Code"] = code c.Data["Code"] = code
c.Data["IsResetForm"] = true c.Data["IsResetForm"] = true
c.HTML(200, RESET_PASSWORD) c.Success(RESET_PASSWORD)
} }
func ResetPasswdPost(c *context.Context) { func ResetPasswdPost(c *context.Context) {
c.Data["Title"] = c.Tr("auth.reset_password") c.Title("auth.reset_password")
code := c.Query("code") code := c.Query("code")
if len(code) == 0 { if len(code) == 0 {
c.Error(404) c.NotFound()
return return
} }
c.Data["Code"] = code c.Data["Code"] = code
@ -546,24 +544,24 @@ func ResetPasswdPost(c *context.Context) {
u.Passwd = passwd u.Passwd = passwd
var err error var err error
if u.Rands, err = models.GetUserSalt(); err != nil { if u.Rands, err = models.GetUserSalt(); err != nil {
c.Handle(500, "UpdateUser", err) c.ServerError("GetUserSalt", err)
return return
} }
if u.Salt, err = models.GetUserSalt(); err != nil { if u.Salt, err = models.GetUserSalt(); err != nil {
c.Handle(500, "UpdateUser", err) c.ServerError("GetUserSalt", err)
return return
} }
u.EncodePasswd() u.EncodePasswd()
if err := models.UpdateUser(u); err != nil { if err := models.UpdateUser(u); err != nil {
c.Handle(500, "UpdateUser", err) c.ServerError("UpdateUser", err)
return return
} }
log.Trace("User password reset: %s", u.Name) log.Trace("User password reset: %s", u.Name)
c.Redirect(setting.AppSubURL + "/user/login") c.SubURLRedirect("/user/login")
return return
} }
c.Data["IsResetFailed"] = true c.Data["IsResetFailed"] = true
c.HTML(200, RESET_PASSWORD) c.Success(RESET_PASSWORD)
} }

Loading…
Cancel
Save