You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1010 lines
29 KiB

Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package user
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/auth/oauth2"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "github.com/go-macaron/captcha"
  19. "github.com/markbates/goth"
  20. )
  21. const (
  22. // tplSignIn template for sign in page
  23. tplSignIn base.TplName = "user/auth/signin"
  24. // tplSignUp template path for sign up page
  25. tplSignUp base.TplName = "user/auth/signup"
  26. // TplActivate template path for activate user
  27. TplActivate base.TplName = "user/auth/activate"
  28. tplForgotPassword base.TplName = "user/auth/forgot_passwd"
  29. tplResetPassword base.TplName = "user/auth/reset_passwd"
  30. tplTwofa base.TplName = "user/auth/twofa"
  31. tplTwofaScratch base.TplName = "user/auth/twofa_scratch"
  32. tplLinkAccount base.TplName = "user/auth/link_account"
  33. )
  34. // AutoSignIn reads cookie and try to auto-login.
  35. func AutoSignIn(ctx *context.Context) (bool, error) {
  36. if !models.HasEngine {
  37. return false, nil
  38. }
  39. uname := ctx.GetCookie(setting.CookieUserName)
  40. if len(uname) == 0 {
  41. return false, nil
  42. }
  43. isSucceed := false
  44. defer func() {
  45. if !isSucceed {
  46. log.Trace("auto-login cookie cleared: %s", uname)
  47. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  48. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  49. }
  50. }()
  51. u, err := models.GetUserByName(uname)
  52. if err != nil {
  53. if !models.IsErrUserNotExist(err) {
  54. return false, fmt.Errorf("GetUserByName: %v", err)
  55. }
  56. return false, nil
  57. }
  58. if val, _ := ctx.GetSuperSecureCookie(
  59. base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name {
  60. return false, nil
  61. }
  62. isSucceed = true
  63. ctx.Session.Set("uid", u.ID)
  64. ctx.Session.Set("uname", u.Name)
  65. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  66. return true, nil
  67. }
  68. func checkAutoLogin(ctx *context.Context) bool {
  69. // Check auto-login.
  70. isSucceed, err := AutoSignIn(ctx)
  71. if err != nil {
  72. ctx.Handle(500, "AutoSignIn", err)
  73. return true
  74. }
  75. redirectTo := ctx.Query("redirect_to")
  76. if len(redirectTo) > 0 {
  77. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL)
  78. } else {
  79. redirectTo, _ = url.QueryUnescape(ctx.GetCookie("redirect_to"))
  80. }
  81. if isSucceed {
  82. if len(redirectTo) > 0 {
  83. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  84. ctx.Redirect(redirectTo)
  85. } else {
  86. ctx.Redirect(setting.AppSubURL + "/")
  87. }
  88. return true
  89. }
  90. return false
  91. }
  92. // SignIn render sign in page
  93. func SignIn(ctx *context.Context) {
  94. ctx.Data["Title"] = ctx.Tr("sign_in")
  95. // Check auto-login.
  96. if checkAutoLogin(ctx) {
  97. return
  98. }
  99. orderedOAuth2Names, oauth2Providers, err := models.GetActiveOAuth2Providers()
  100. if err != nil {
  101. ctx.Handle(500, "UserSignIn", err)
  102. return
  103. }
  104. ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names
  105. ctx.Data["OAuth2Providers"] = oauth2Providers
  106. ctx.Data["Title"] = ctx.Tr("sign_in")
  107. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  108. ctx.Data["PageIsSignIn"] = true
  109. ctx.Data["PageIsLogin"] = true
  110. ctx.HTML(200, tplSignIn)
  111. }
  112. // SignInPost response for sign in request
  113. func SignInPost(ctx *context.Context, form auth.SignInForm) {
  114. ctx.Data["Title"] = ctx.Tr("sign_in")
  115. orderedOAuth2Names, oauth2Providers, err := models.GetActiveOAuth2Providers()
  116. if err != nil {
  117. ctx.Handle(500, "UserSignIn", err)
  118. return
  119. }
  120. ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names
  121. ctx.Data["OAuth2Providers"] = oauth2Providers
  122. ctx.Data["Title"] = ctx.Tr("sign_in")
  123. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  124. ctx.Data["PageIsSignIn"] = true
  125. ctx.Data["PageIsLogin"] = true
  126. if ctx.HasError() {
  127. ctx.HTML(200, tplSignIn)
  128. return
  129. }
  130. u, err := models.UserSignIn(form.UserName, form.Password)
  131. if err != nil {
  132. if models.IsErrUserNotExist(err) {
  133. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form)
  134. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  135. } else if models.IsErrEmailAlreadyUsed(err) {
  136. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignIn, &form)
  137. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  138. } else {
  139. ctx.Handle(500, "UserSignIn", err)
  140. }
  141. return
  142. }
  143. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  144. // Instead, redirect them to the 2FA authentication page.
  145. _, err = models.GetTwoFactorByUID(u.ID)
  146. if err != nil {
  147. if models.IsErrTwoFactorNotEnrolled(err) {
  148. handleSignIn(ctx, u, form.Remember)
  149. } else {
  150. ctx.Handle(500, "UserSignIn", err)
  151. }
  152. return
  153. }
  154. // User needs to use 2FA, save data and redirect to 2FA page.
  155. ctx.Session.Set("twofaUid", u.ID)
  156. ctx.Session.Set("twofaRemember", form.Remember)
  157. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  158. }
  159. // TwoFactor shows the user a two-factor authentication page.
  160. func TwoFactor(ctx *context.Context) {
  161. ctx.Data["Title"] = ctx.Tr("twofa")
  162. // Check auto-login.
  163. if checkAutoLogin(ctx) {
  164. return
  165. }
  166. // Ensure user is in a 2FA session.
  167. if ctx.Session.Get("twofaUid") == nil {
  168. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  169. return
  170. }
  171. ctx.HTML(200, tplTwofa)
  172. }
  173. // TwoFactorPost validates a user's two-factor authentication token.
  174. func TwoFactorPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  175. ctx.Data["Title"] = ctx.Tr("twofa")
  176. // Ensure user is in a 2FA session.
  177. idSess := ctx.Session.Get("twofaUid")
  178. if idSess == nil {
  179. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  180. return
  181. }
  182. id := idSess.(int64)
  183. twofa, err := models.GetTwoFactorByUID(id)
  184. if err != nil {
  185. ctx.Handle(500, "UserSignIn", err)
  186. return
  187. }
  188. // Validate the passcode with the stored TOTP secret.
  189. ok, err := twofa.ValidateTOTP(form.Passcode)
  190. if err != nil {
  191. ctx.Handle(500, "UserSignIn", err)
  192. return
  193. }
  194. if ok {
  195. remember := ctx.Session.Get("twofaRemember").(bool)
  196. u, err := models.GetUserByID(id)
  197. if err != nil {
  198. ctx.Handle(500, "UserSignIn", err)
  199. return
  200. }
  201. if ctx.Session.Get("linkAccount") != nil {
  202. gothUser := ctx.Session.Get("linkAccountGothUser")
  203. if gothUser == nil {
  204. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  205. return
  206. }
  207. err = models.LinkAccountToUser(u, gothUser.(goth.User))
  208. if err != nil {
  209. ctx.Handle(500, "UserSignIn", err)
  210. return
  211. }
  212. }
  213. handleSignIn(ctx, u, remember)
  214. return
  215. }
  216. ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, auth.TwoFactorAuthForm{})
  217. }
  218. // TwoFactorScratch shows the scratch code form for two-factor authentication.
  219. func TwoFactorScratch(ctx *context.Context) {
  220. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  221. // Check auto-login.
  222. if checkAutoLogin(ctx) {
  223. return
  224. }
  225. // Ensure user is in a 2FA session.
  226. if ctx.Session.Get("twofaUid") == nil {
  227. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  228. return
  229. }
  230. ctx.HTML(200, tplTwofaScratch)
  231. }
  232. // TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
  233. func TwoFactorScratchPost(ctx *context.Context, form auth.TwoFactorScratchAuthForm) {
  234. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  235. // Ensure user is in a 2FA session.
  236. idSess := ctx.Session.Get("twofaUid")
  237. if idSess == nil {
  238. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  239. return
  240. }
  241. id := idSess.(int64)
  242. twofa, err := models.GetTwoFactorByUID(id)
  243. if err != nil {
  244. ctx.Handle(500, "UserSignIn", err)
  245. return
  246. }
  247. // Validate the passcode with the stored TOTP secret.
  248. if twofa.VerifyScratchToken(form.Token) {
  249. // Invalidate the scratch token.
  250. twofa.ScratchToken = ""
  251. if err = models.UpdateTwoFactor(twofa); err != nil {
  252. ctx.Handle(500, "UserSignIn", err)
  253. return
  254. }
  255. remember := ctx.Session.Get("twofaRemember").(bool)
  256. u, err := models.GetUserByID(id)
  257. if err != nil {
  258. ctx.Handle(500, "UserSignIn", err)
  259. return
  260. }
  261. handleSignInFull(ctx, u, remember, false)
  262. ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used"))
  263. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  264. return
  265. }
  266. ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, auth.TwoFactorScratchAuthForm{})
  267. }
  268. // This handles the final part of the sign-in process of the user.
  269. func handleSignIn(ctx *context.Context, u *models.User, remember bool) {
  270. handleSignInFull(ctx, u, remember, true)
  271. }
  272. func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyRedirect bool) {
  273. if remember {
  274. days := 86400 * setting.LogInRememberDays
  275. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL)
  276. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  277. setting.CookieRememberName, u.Name, days, setting.AppSubURL)
  278. }
  279. ctx.Session.Delete("openid_verified_uri")
  280. ctx.Session.Delete("openid_signin_remember")
  281. ctx.Session.Delete("openid_determined_email")
  282. ctx.Session.Delete("openid_determined_username")
  283. ctx.Session.Delete("twofaUid")
  284. ctx.Session.Delete("twofaRemember")
  285. ctx.Session.Set("uid", u.ID)
  286. ctx.Session.Set("uname", u.Name)
  287. // Clear whatever CSRF has right now, force to generate a new one
  288. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  289. // Register last login
  290. u.SetLastLogin()
  291. if err := models.UpdateUserCols(u, "last_login_unix"); err != nil {
  292. ctx.Handle(500, "UpdateUserCols", err)
  293. return
  294. }
  295. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  296. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  297. if obeyRedirect {
  298. ctx.Redirect(redirectTo)
  299. }
  300. return
  301. }
  302. if obeyRedirect {
  303. ctx.Redirect(setting.AppSubURL + "/")
  304. }
  305. }
  306. // SignInOAuth handles the OAuth2 login buttons
  307. func SignInOAuth(ctx *context.Context) {
  308. provider := ctx.Params(":provider")
  309. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  310. if err != nil {
  311. ctx.Handle(500, "SignIn", err)
  312. return
  313. }
  314. // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user
  315. user, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  316. if err == nil && user != nil {
  317. // we got the user without going through the whole OAuth2 authentication flow again
  318. handleOAuth2SignIn(user, gothUser, ctx, err)
  319. return
  320. }
  321. err = oauth2.Auth(loginSource.Name, ctx.Req.Request, ctx.Resp)
  322. if err != nil {
  323. ctx.Handle(500, "SignIn", err)
  324. }
  325. // redirect is done in oauth2.Auth
  326. }
  327. // SignInOAuthCallback handles the callback from the given provider
  328. func SignInOAuthCallback(ctx *context.Context) {
  329. provider := ctx.Params(":provider")
  330. // first look if the provider is still active
  331. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  332. if err != nil {
  333. ctx.Handle(500, "SignIn", err)
  334. return
  335. }
  336. if loginSource == nil {
  337. ctx.Handle(500, "SignIn", errors.New("No valid provider found, check configured callback url in provider"))
  338. return
  339. }
  340. u, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  341. handleOAuth2SignIn(u, gothUser, ctx, err)
  342. }
  343. func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context, err error) {
  344. if err != nil {
  345. ctx.Handle(500, "UserSignIn", err)
  346. return
  347. }
  348. if u == nil {
  349. // no existing user is found, request attach or new account
  350. ctx.Session.Set("linkAccountGothUser", gothUser)
  351. ctx.Redirect(setting.AppSubURL + "/user/link_account")
  352. return
  353. }
  354. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  355. // Instead, redirect them to the 2FA authentication page.
  356. _, err = models.GetTwoFactorByUID(u.ID)
  357. if err != nil {
  358. if models.IsErrTwoFactorNotEnrolled(err) {
  359. ctx.Session.Set("uid", u.ID)
  360. ctx.Session.Set("uname", u.Name)
  361. // Clear whatever CSRF has right now, force to generate a new one
  362. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  363. // Register last login
  364. u.SetLastLogin()
  365. if err := models.UpdateUserCols(u, "last_login_unix"); err != nil {
  366. ctx.Handle(500, "UpdateUserCols", err)
  367. return
  368. }
  369. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  370. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  371. ctx.Redirect(redirectTo)
  372. return
  373. }
  374. ctx.Redirect(setting.AppSubURL + "/")
  375. } else {
  376. ctx.Handle(500, "UserSignIn", err)
  377. }
  378. return
  379. }
  380. // User needs to use 2FA, save data and redirect to 2FA page.
  381. ctx.Session.Set("twofaUid", u.ID)
  382. ctx.Session.Set("twofaRemember", false)
  383. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  384. }
  385. // OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful
  386. // login the user
  387. func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) {
  388. gothUser, err := oauth2.ProviderCallback(loginSource.Name, request, response)
  389. if err != nil {
  390. return nil, goth.User{}, err
  391. }
  392. user := &models.User{
  393. LoginName: gothUser.UserID,
  394. LoginType: models.LoginOAuth2,
  395. LoginSource: loginSource.ID,
  396. }
  397. hasUser, err := models.GetUser(user)
  398. if err != nil {
  399. return nil, goth.User{}, err
  400. }
  401. if hasUser {
  402. return user, goth.User{}, nil
  403. }
  404. // search in external linked users
  405. externalLoginUser := &models.ExternalLoginUser{
  406. ExternalID: gothUser.UserID,
  407. LoginSourceID: loginSource.ID,
  408. }
  409. hasUser, err = models.GetExternalLogin(externalLoginUser)
  410. if err != nil {
  411. return nil, goth.User{}, err
  412. }
  413. if hasUser {
  414. user, err = models.GetUserByID(externalLoginUser.UserID)
  415. return user, goth.User{}, err
  416. }
  417. // no user found to login
  418. return nil, gothUser, nil
  419. }
  420. // LinkAccount shows the page where the user can decide to login or create a new account
  421. func LinkAccount(ctx *context.Context) {
  422. ctx.Data["Title"] = ctx.Tr("link_account")
  423. ctx.Data["LinkAccountMode"] = true
  424. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  425. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  426. ctx.Data["ShowRegistrationButton"] = false
  427. // use this to set the right link into the signIn and signUp templates in the link_account template
  428. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  429. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  430. gothUser := ctx.Session.Get("linkAccountGothUser")
  431. if gothUser == nil {
  432. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  433. return
  434. }
  435. ctx.Data["user_name"] = gothUser.(goth.User).NickName
  436. ctx.Data["email"] = gothUser.(goth.User).Email
  437. ctx.HTML(200, tplLinkAccount)
  438. }
  439. // LinkAccountPostSignIn handle the coupling of external account with another account using signIn
  440. func LinkAccountPostSignIn(ctx *context.Context, signInForm auth.SignInForm) {
  441. ctx.Data["Title"] = ctx.Tr("link_account")
  442. ctx.Data["LinkAccountMode"] = true
  443. ctx.Data["LinkAccountModeSignIn"] = true
  444. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  445. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  446. ctx.Data["ShowRegistrationButton"] = false
  447. // use this to set the right link into the signIn and signUp templates in the link_account template
  448. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  449. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  450. gothUser := ctx.Session.Get("linkAccountGothUser")
  451. if gothUser == nil {
  452. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  453. return
  454. }
  455. if ctx.HasError() {
  456. ctx.HTML(200, tplLinkAccount)
  457. return
  458. }
  459. u, err := models.UserSignIn(signInForm.UserName, signInForm.Password)
  460. if err != nil {
  461. if models.IsErrUserNotExist(err) {
  462. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplLinkAccount, &signInForm)
  463. } else {
  464. ctx.Handle(500, "UserLinkAccount", err)
  465. }
  466. return
  467. }
  468. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  469. // Instead, redirect them to the 2FA authentication page.
  470. _, err = models.GetTwoFactorByUID(u.ID)
  471. if err != nil {
  472. if models.IsErrTwoFactorNotEnrolled(err) {
  473. err = models.LinkAccountToUser(u, gothUser.(goth.User))
  474. if err != nil {
  475. ctx.Handle(500, "UserLinkAccount", err)
  476. } else {
  477. handleSignIn(ctx, u, signInForm.Remember)
  478. }
  479. } else {
  480. ctx.Handle(500, "UserLinkAccount", err)
  481. }
  482. return
  483. }
  484. // User needs to use 2FA, save data and redirect to 2FA page.
  485. ctx.Session.Set("twofaUid", u.ID)
  486. ctx.Session.Set("twofaRemember", signInForm.Remember)
  487. ctx.Session.Set("linkAccount", true)
  488. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  489. }
  490. // LinkAccountPostRegister handle the creation of a new account for an external account using signUp
  491. func LinkAccountPostRegister(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  492. ctx.Data["Title"] = ctx.Tr("link_account")
  493. ctx.Data["LinkAccountMode"] = true
  494. ctx.Data["LinkAccountModeRegister"] = true
  495. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  496. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  497. ctx.Data["ShowRegistrationButton"] = false
  498. // use this to set the right link into the signIn and signUp templates in the link_account template
  499. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  500. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  501. gothUser := ctx.Session.Get("linkAccountGothUser")
  502. if gothUser == nil {
  503. ctx.Handle(500, "UserSignUp", errors.New("not in LinkAccount session"))
  504. return
  505. }
  506. if ctx.HasError() {
  507. ctx.HTML(200, tplLinkAccount)
  508. return
  509. }
  510. if setting.Service.DisableRegistration {
  511. ctx.Error(403)
  512. return
  513. }
  514. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  515. ctx.Data["Err_Captcha"] = true
  516. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form)
  517. return
  518. }
  519. if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype {
  520. ctx.Data["Err_Password"] = true
  521. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form)
  522. return
  523. }
  524. if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength {
  525. ctx.Data["Err_Password"] = true
  526. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form)
  527. return
  528. }
  529. loginSource, err := models.GetActiveOAuth2LoginSourceByName(gothUser.(goth.User).Provider)
  530. if err != nil {
  531. ctx.Handle(500, "CreateUser", err)
  532. }
  533. u := &models.User{
  534. Name: form.UserName,
  535. Email: form.Email,
  536. Passwd: form.Password,
  537. IsActive: !setting.Service.RegisterEmailConfirm,
  538. LoginType: models.LoginOAuth2,
  539. LoginSource: loginSource.ID,
  540. LoginName: gothUser.(goth.User).UserID,
  541. }
  542. if err := models.CreateUser(u); err != nil {
  543. switch {
  544. case models.IsErrUserAlreadyExist(err):
  545. ctx.Data["Err_UserName"] = true
  546. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplLinkAccount, &form)
  547. case models.IsErrEmailAlreadyUsed(err):
  548. ctx.Data["Err_Email"] = true
  549. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplLinkAccount, &form)
  550. case models.IsErrNameReserved(err):
  551. ctx.Data["Err_UserName"] = true
  552. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplLinkAccount, &form)
  553. case models.IsErrNamePatternNotAllowed(err):
  554. ctx.Data["Err_UserName"] = true
  555. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplLinkAccount, &form)
  556. default:
  557. ctx.Handle(500, "CreateUser", err)
  558. }
  559. return
  560. }
  561. log.Trace("Account created: %s", u.Name)
  562. // Auto-set admin for the only user.
  563. if models.CountUsers() == 1 {
  564. u.IsAdmin = true
  565. u.IsActive = true
  566. u.SetLastLogin()
  567. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  568. ctx.Handle(500, "UpdateUser", err)
  569. return
  570. }
  571. }
  572. // Send confirmation email
  573. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  574. models.SendActivateAccountMail(ctx.Context, u)
  575. ctx.Data["IsSendRegisterMail"] = true
  576. ctx.Data["Email"] = u.Email
  577. ctx.Data["ActiveCodeLives"] = base.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  578. ctx.HTML(200, TplActivate)
  579. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  580. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  581. }
  582. return
  583. }
  584. ctx.Redirect(setting.AppSubURL + "/user/login")
  585. }
  586. // SignOut sign out from login status
  587. func SignOut(ctx *context.Context) {
  588. ctx.Session.Delete("uid")
  589. ctx.Session.Delete("uname")
  590. ctx.Session.Delete("socialId")
  591. ctx.Session.Delete("socialName")
  592. ctx.Session.Delete("socialEmail")
  593. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  594. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  595. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  596. ctx.Redirect(setting.AppSubURL + "/")
  597. }
  598. // SignUp render the register page
  599. func SignUp(ctx *context.Context) {
  600. ctx.Data["Title"] = ctx.Tr("sign_up")
  601. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
  602. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  603. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  604. ctx.HTML(200, tplSignUp)
  605. }
  606. // SignUpPost response for sign up information submission
  607. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  608. ctx.Data["Title"] = ctx.Tr("sign_up")
  609. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
  610. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  611. if setting.Service.DisableRegistration {
  612. ctx.Error(403)
  613. return
  614. }
  615. if ctx.HasError() {
  616. ctx.HTML(200, tplSignUp)
  617. return
  618. }
  619. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  620. ctx.Data["Err_Captcha"] = true
  621. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  622. return
  623. }
  624. if form.Password != form.Retype {
  625. ctx.Data["Err_Password"] = true
  626. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  627. return
  628. }
  629. if len(form.Password) < setting.MinPasswordLength {
  630. ctx.Data["Err_Password"] = true
  631. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
  632. return
  633. }
  634. u := &models.User{
  635. Name: form.UserName,
  636. Email: form.Email,
  637. Passwd: form.Password,
  638. IsActive: !setting.Service.RegisterEmailConfirm,
  639. }
  640. if err := models.CreateUser(u); err != nil {
  641. switch {
  642. case models.IsErrUserAlreadyExist(err):
  643. ctx.Data["Err_UserName"] = true
  644. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  645. case models.IsErrEmailAlreadyUsed(err):
  646. ctx.Data["Err_Email"] = true
  647. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  648. case models.IsErrNameReserved(err):
  649. ctx.Data["Err_UserName"] = true
  650. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  651. case models.IsErrNamePatternNotAllowed(err):
  652. ctx.Data["Err_UserName"] = true
  653. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  654. default:
  655. ctx.Handle(500, "CreateUser", err)
  656. }
  657. return
  658. }
  659. log.Trace("Account created: %s", u.Name)
  660. // Auto-set admin for the only user.
  661. if models.CountUsers() == 1 {
  662. u.IsAdmin = true
  663. u.IsActive = true
  664. u.SetLastLogin()
  665. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  666. ctx.Handle(500, "UpdateUser", err)
  667. return
  668. }
  669. }
  670. // Send confirmation email, no need for social account.
  671. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  672. models.SendActivateAccountMail(ctx.Context, u)
  673. ctx.Data["IsSendRegisterMail"] = true
  674. ctx.Data["Email"] = u.Email
  675. ctx.Data["ActiveCodeLives"] = base.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  676. ctx.HTML(200, TplActivate)
  677. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  678. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  679. }
  680. return
  681. }
  682. ctx.Redirect(setting.AppSubURL + "/user/login")
  683. }
  684. // Activate render activate user page
  685. func Activate(ctx *context.Context) {
  686. code := ctx.Query("code")
  687. if len(code) == 0 {
  688. ctx.Data["IsActivatePage"] = true
  689. if ctx.User.IsActive {
  690. ctx.Error(404)
  691. return
  692. }
  693. // Resend confirmation email.
  694. if setting.Service.RegisterEmailConfirm {
  695. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  696. ctx.Data["ResendLimited"] = true
  697. } else {
  698. ctx.Data["ActiveCodeLives"] = base.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  699. models.SendActivateAccountMail(ctx.Context, ctx.User)
  700. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  701. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  702. }
  703. }
  704. } else {
  705. ctx.Data["ServiceNotEnabled"] = true
  706. }
  707. ctx.HTML(200, TplActivate)
  708. return
  709. }
  710. // Verify code.
  711. if user := models.VerifyUserActiveCode(code); user != nil {
  712. user.IsActive = true
  713. var err error
  714. if user.Rands, err = models.GetUserSalt(); err != nil {
  715. ctx.Handle(500, "UpdateUser", err)
  716. return
  717. }
  718. if err := models.UpdateUserCols(user, "is_active", "rands"); err != nil {
  719. if models.IsErrUserNotExist(err) {
  720. ctx.Error(404)
  721. } else {
  722. ctx.Handle(500, "UpdateUser", err)
  723. }
  724. return
  725. }
  726. log.Trace("User activated: %s", user.Name)
  727. ctx.Session.Set("uid", user.ID)
  728. ctx.Session.Set("uname", user.Name)
  729. ctx.Redirect(setting.AppSubURL + "/")
  730. return
  731. }
  732. ctx.Data["IsActivateFailed"] = true
  733. ctx.HTML(200, TplActivate)
  734. }
  735. // ActivateEmail render the activate email page
  736. func ActivateEmail(ctx *context.Context) {
  737. code := ctx.Query("code")
  738. emailStr := ctx.Query("email")
  739. // Verify code.
  740. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  741. if err := email.Activate(); err != nil {
  742. ctx.Handle(500, "ActivateEmail", err)
  743. }
  744. log.Trace("Email activated: %s", email.Email)
  745. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  746. }
  747. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  748. return
  749. }
  750. // ForgotPasswd render the forget pasword page
  751. func ForgotPasswd(ctx *context.Context) {
  752. ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
  753. if setting.MailService == nil {
  754. ctx.Data["IsResetDisable"] = true
  755. ctx.HTML(200, tplForgotPassword)
  756. return
  757. }
  758. email := ctx.Query("email")
  759. ctx.Data["Email"] = email
  760. ctx.Data["IsResetRequest"] = true
  761. ctx.HTML(200, tplForgotPassword)
  762. }
  763. // ForgotPasswdPost response for forget password request
  764. func ForgotPasswdPost(ctx *context.Context) {
  765. ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
  766. if setting.MailService == nil {
  767. ctx.Handle(403, "ForgotPasswdPost", nil)
  768. return
  769. }
  770. ctx.Data["IsResetRequest"] = true
  771. email := ctx.Query("email")
  772. ctx.Data["Email"] = email
  773. u, err := models.GetUserByEmail(email)
  774. if err != nil {
  775. if models.IsErrUserNotExist(err) {
  776. ctx.Data["ResetPwdCodeLives"] = base.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
  777. ctx.Data["IsResetSent"] = true
  778. ctx.HTML(200, tplForgotPassword)
  779. return
  780. }
  781. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  782. return
  783. }
  784. if !u.IsLocal() && !u.IsOAuth2() {
  785. ctx.Data["Err_Email"] = true
  786. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  787. return
  788. }
  789. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  790. ctx.Data["ResendLimited"] = true
  791. ctx.HTML(200, tplForgotPassword)
  792. return
  793. }
  794. models.SendResetPasswordMail(ctx.Context, u)
  795. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  796. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  797. }
  798. ctx.Data["ResetPwdCodeLives"] = base.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
  799. ctx.Data["IsResetSent"] = true
  800. ctx.HTML(200, tplForgotPassword)
  801. }
  802. // ResetPasswd render the reset password page
  803. func ResetPasswd(ctx *context.Context) {
  804. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  805. code := ctx.Query("code")
  806. if len(code) == 0 {
  807. ctx.Error(404)
  808. return
  809. }
  810. ctx.Data["Code"] = code
  811. ctx.Data["IsResetForm"] = true
  812. ctx.HTML(200, tplResetPassword)
  813. }
  814. // ResetPasswdPost response from reset password request
  815. func ResetPasswdPost(ctx *context.Context) {
  816. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  817. code := ctx.Query("code")
  818. if len(code) == 0 {
  819. ctx.Error(404)
  820. return
  821. }
  822. ctx.Data["Code"] = code
  823. if u := models.VerifyUserActiveCode(code); u != nil {
  824. // Validate password length.
  825. passwd := ctx.Query("password")
  826. if len(passwd) < setting.MinPasswordLength {
  827. ctx.Data["IsResetForm"] = true
  828. ctx.Data["Err_Password"] = true
  829. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil)
  830. return
  831. }
  832. u.Passwd = passwd
  833. var err error
  834. if u.Rands, err = models.GetUserSalt(); err != nil {
  835. ctx.Handle(500, "UpdateUser", err)
  836. return
  837. }
  838. if u.Salt, err = models.GetUserSalt(); err != nil {
  839. ctx.Handle(500, "UpdateUser", err)
  840. return
  841. }
  842. u.EncodePasswd()
  843. if err := models.UpdateUserCols(u, "passwd", "rands", "salt"); err != nil {
  844. ctx.Handle(500, "UpdateUser", err)
  845. return
  846. }
  847. log.Trace("User password reset: %s", u.Name)
  848. ctx.Redirect(setting.AppSubURL + "/user/login")
  849. return
  850. }
  851. ctx.Data["IsResetFailed"] = true
  852. ctx.HTML(200, tplResetPassword)
  853. }