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.

1006 lines
28 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
  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. } else if models.IsErrEmailAlreadyUsed(err) {
  135. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignIn, &form)
  136. } else {
  137. ctx.Handle(500, "UserSignIn", err)
  138. }
  139. return
  140. }
  141. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  142. // Instead, redirect them to the 2FA authentication page.
  143. _, err = models.GetTwoFactorByUID(u.ID)
  144. if err != nil {
  145. if models.IsErrTwoFactorNotEnrolled(err) {
  146. handleSignIn(ctx, u, form.Remember)
  147. } else {
  148. ctx.Handle(500, "UserSignIn", err)
  149. }
  150. return
  151. }
  152. // User needs to use 2FA, save data and redirect to 2FA page.
  153. ctx.Session.Set("twofaUid", u.ID)
  154. ctx.Session.Set("twofaRemember", form.Remember)
  155. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  156. }
  157. // TwoFactor shows the user a two-factor authentication page.
  158. func TwoFactor(ctx *context.Context) {
  159. ctx.Data["Title"] = ctx.Tr("twofa")
  160. // Check auto-login.
  161. if checkAutoLogin(ctx) {
  162. return
  163. }
  164. // Ensure user is in a 2FA session.
  165. if ctx.Session.Get("twofaUid") == nil {
  166. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  167. return
  168. }
  169. ctx.HTML(200, tplTwofa)
  170. }
  171. // TwoFactorPost validates a user's two-factor authentication token.
  172. func TwoFactorPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  173. ctx.Data["Title"] = ctx.Tr("twofa")
  174. // Ensure user is in a 2FA session.
  175. idSess := ctx.Session.Get("twofaUid")
  176. if idSess == nil {
  177. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  178. return
  179. }
  180. id := idSess.(int64)
  181. twofa, err := models.GetTwoFactorByUID(id)
  182. if err != nil {
  183. ctx.Handle(500, "UserSignIn", err)
  184. return
  185. }
  186. // Validate the passcode with the stored TOTP secret.
  187. ok, err := twofa.ValidateTOTP(form.Passcode)
  188. if err != nil {
  189. ctx.Handle(500, "UserSignIn", err)
  190. return
  191. }
  192. if ok {
  193. remember := ctx.Session.Get("twofaRemember").(bool)
  194. u, err := models.GetUserByID(id)
  195. if err != nil {
  196. ctx.Handle(500, "UserSignIn", err)
  197. return
  198. }
  199. if ctx.Session.Get("linkAccount") != nil {
  200. gothUser := ctx.Session.Get("linkAccountGothUser")
  201. if gothUser == nil {
  202. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  203. return
  204. }
  205. err = models.LinkAccountToUser(u, gothUser.(goth.User))
  206. if err != nil {
  207. ctx.Handle(500, "UserSignIn", err)
  208. return
  209. }
  210. }
  211. handleSignIn(ctx, u, remember)
  212. return
  213. }
  214. ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, auth.TwoFactorAuthForm{})
  215. }
  216. // TwoFactorScratch shows the scratch code form for two-factor authentication.
  217. func TwoFactorScratch(ctx *context.Context) {
  218. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  219. // Check auto-login.
  220. if checkAutoLogin(ctx) {
  221. return
  222. }
  223. // Ensure user is in a 2FA session.
  224. if ctx.Session.Get("twofaUid") == nil {
  225. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  226. return
  227. }
  228. ctx.HTML(200, tplTwofaScratch)
  229. }
  230. // TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
  231. func TwoFactorScratchPost(ctx *context.Context, form auth.TwoFactorScratchAuthForm) {
  232. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  233. // Ensure user is in a 2FA session.
  234. idSess := ctx.Session.Get("twofaUid")
  235. if idSess == nil {
  236. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  237. return
  238. }
  239. id := idSess.(int64)
  240. twofa, err := models.GetTwoFactorByUID(id)
  241. if err != nil {
  242. ctx.Handle(500, "UserSignIn", err)
  243. return
  244. }
  245. // Validate the passcode with the stored TOTP secret.
  246. if twofa.VerifyScratchToken(form.Token) {
  247. // Invalidate the scratch token.
  248. twofa.ScratchToken = ""
  249. if err = models.UpdateTwoFactor(twofa); err != nil {
  250. ctx.Handle(500, "UserSignIn", err)
  251. return
  252. }
  253. remember := ctx.Session.Get("twofaRemember").(bool)
  254. u, err := models.GetUserByID(id)
  255. if err != nil {
  256. ctx.Handle(500, "UserSignIn", err)
  257. return
  258. }
  259. handleSignInFull(ctx, u, remember, false)
  260. ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used"))
  261. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  262. return
  263. }
  264. ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, auth.TwoFactorScratchAuthForm{})
  265. }
  266. // This handles the final part of the sign-in process of the user.
  267. func handleSignIn(ctx *context.Context, u *models.User, remember bool) {
  268. handleSignInFull(ctx, u, remember, true)
  269. }
  270. func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyRedirect bool) {
  271. if remember {
  272. days := 86400 * setting.LogInRememberDays
  273. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL)
  274. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  275. setting.CookieRememberName, u.Name, days, setting.AppSubURL)
  276. }
  277. ctx.Session.Delete("openid_verified_uri")
  278. ctx.Session.Delete("openid_signin_remember")
  279. ctx.Session.Delete("openid_determined_email")
  280. ctx.Session.Delete("openid_determined_username")
  281. ctx.Session.Delete("twofaUid")
  282. ctx.Session.Delete("twofaRemember")
  283. ctx.Session.Set("uid", u.ID)
  284. ctx.Session.Set("uname", u.Name)
  285. // Clear whatever CSRF has right now, force to generate a new one
  286. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  287. // Register last login
  288. u.SetLastLogin()
  289. if err := models.UpdateUser(u); err != nil {
  290. ctx.Handle(500, "UpdateUser", err)
  291. return
  292. }
  293. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  294. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  295. if obeyRedirect {
  296. ctx.Redirect(redirectTo)
  297. }
  298. return
  299. }
  300. if obeyRedirect {
  301. ctx.Redirect(setting.AppSubURL + "/")
  302. }
  303. }
  304. // SignInOAuth handles the OAuth2 login buttons
  305. func SignInOAuth(ctx *context.Context) {
  306. provider := ctx.Params(":provider")
  307. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  308. if err != nil {
  309. ctx.Handle(500, "SignIn", err)
  310. return
  311. }
  312. // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user
  313. user, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  314. if err == nil && user != nil {
  315. // we got the user without going through the whole OAuth2 authentication flow again
  316. handleOAuth2SignIn(user, gothUser, ctx, err)
  317. return
  318. }
  319. err = oauth2.Auth(loginSource.Name, ctx.Req.Request, ctx.Resp)
  320. if err != nil {
  321. ctx.Handle(500, "SignIn", err)
  322. }
  323. // redirect is done in oauth2.Auth
  324. }
  325. // SignInOAuthCallback handles the callback from the given provider
  326. func SignInOAuthCallback(ctx *context.Context) {
  327. provider := ctx.Params(":provider")
  328. // first look if the provider is still active
  329. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  330. if err != nil {
  331. ctx.Handle(500, "SignIn", err)
  332. return
  333. }
  334. if loginSource == nil {
  335. ctx.Handle(500, "SignIn", errors.New("No valid provider found, check configured callback url in provider"))
  336. return
  337. }
  338. u, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  339. handleOAuth2SignIn(u, gothUser, ctx, err)
  340. }
  341. func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context, err error) {
  342. if err != nil {
  343. ctx.Handle(500, "UserSignIn", err)
  344. return
  345. }
  346. if u == nil {
  347. // no existing user is found, request attach or new account
  348. ctx.Session.Set("linkAccountGothUser", gothUser)
  349. ctx.Redirect(setting.AppSubURL + "/user/link_account")
  350. return
  351. }
  352. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  353. // Instead, redirect them to the 2FA authentication page.
  354. _, err = models.GetTwoFactorByUID(u.ID)
  355. if err != nil {
  356. if models.IsErrTwoFactorNotEnrolled(err) {
  357. ctx.Session.Set("uid", u.ID)
  358. ctx.Session.Set("uname", u.Name)
  359. // Clear whatever CSRF has right now, force to generate a new one
  360. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  361. // Register last login
  362. u.SetLastLogin()
  363. if err := models.UpdateUser(u); err != nil {
  364. ctx.Handle(500, "UpdateUser", err)
  365. return
  366. }
  367. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  368. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  369. ctx.Redirect(redirectTo)
  370. return
  371. }
  372. ctx.Redirect(setting.AppSubURL + "/")
  373. } else {
  374. ctx.Handle(500, "UserSignIn", err)
  375. }
  376. return
  377. }
  378. // User needs to use 2FA, save data and redirect to 2FA page.
  379. ctx.Session.Set("twofaUid", u.ID)
  380. ctx.Session.Set("twofaRemember", false)
  381. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  382. }
  383. // OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful
  384. // login the user
  385. func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) {
  386. gothUser, err := oauth2.ProviderCallback(loginSource.Name, request, response)
  387. if err != nil {
  388. return nil, goth.User{}, err
  389. }
  390. user := &models.User{
  391. LoginName: gothUser.UserID,
  392. LoginType: models.LoginOAuth2,
  393. LoginSource: loginSource.ID,
  394. }
  395. hasUser, err := models.GetUser(user)
  396. if err != nil {
  397. return nil, goth.User{}, err
  398. }
  399. if hasUser {
  400. return user, goth.User{}, nil
  401. }
  402. // search in external linked users
  403. externalLoginUser := &models.ExternalLoginUser{
  404. ExternalID: gothUser.UserID,
  405. LoginSourceID: loginSource.ID,
  406. }
  407. hasUser, err = models.GetExternalLogin(externalLoginUser)
  408. if err != nil {
  409. return nil, goth.User{}, err
  410. }
  411. if hasUser {
  412. user, err = models.GetUserByID(externalLoginUser.UserID)
  413. return user, goth.User{}, err
  414. }
  415. // no user found to login
  416. return nil, gothUser, nil
  417. }
  418. // LinkAccount shows the page where the user can decide to login or create a new account
  419. func LinkAccount(ctx *context.Context) {
  420. ctx.Data["Title"] = ctx.Tr("link_account")
  421. ctx.Data["LinkAccountMode"] = true
  422. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  423. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  424. ctx.Data["ShowRegistrationButton"] = false
  425. // use this to set the right link into the signIn and signUp templates in the link_account template
  426. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  427. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  428. gothUser := ctx.Session.Get("linkAccountGothUser")
  429. if gothUser == nil {
  430. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  431. return
  432. }
  433. ctx.Data["user_name"] = gothUser.(goth.User).NickName
  434. ctx.Data["email"] = gothUser.(goth.User).Email
  435. ctx.HTML(200, tplLinkAccount)
  436. }
  437. // LinkAccountPostSignIn handle the coupling of external account with another account using signIn
  438. func LinkAccountPostSignIn(ctx *context.Context, signInForm auth.SignInForm) {
  439. ctx.Data["Title"] = ctx.Tr("link_account")
  440. ctx.Data["LinkAccountMode"] = true
  441. ctx.Data["LinkAccountModeSignIn"] = true
  442. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  443. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  444. ctx.Data["ShowRegistrationButton"] = false
  445. // use this to set the right link into the signIn and signUp templates in the link_account template
  446. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  447. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  448. gothUser := ctx.Session.Get("linkAccountGothUser")
  449. if gothUser == nil {
  450. ctx.Handle(500, "UserSignIn", errors.New("not in LinkAccount session"))
  451. return
  452. }
  453. if ctx.HasError() {
  454. ctx.HTML(200, tplLinkAccount)
  455. return
  456. }
  457. u, err := models.UserSignIn(signInForm.UserName, signInForm.Password)
  458. if err != nil {
  459. if models.IsErrUserNotExist(err) {
  460. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplLinkAccount, &signInForm)
  461. } else {
  462. ctx.Handle(500, "UserLinkAccount", err)
  463. }
  464. return
  465. }
  466. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  467. // Instead, redirect them to the 2FA authentication page.
  468. _, err = models.GetTwoFactorByUID(u.ID)
  469. if err != nil {
  470. if models.IsErrTwoFactorNotEnrolled(err) {
  471. err = models.LinkAccountToUser(u, gothUser.(goth.User))
  472. if err != nil {
  473. ctx.Handle(500, "UserLinkAccount", err)
  474. } else {
  475. handleSignIn(ctx, u, signInForm.Remember)
  476. }
  477. } else {
  478. ctx.Handle(500, "UserLinkAccount", err)
  479. }
  480. return
  481. }
  482. // User needs to use 2FA, save data and redirect to 2FA page.
  483. ctx.Session.Set("twofaUid", u.ID)
  484. ctx.Session.Set("twofaRemember", signInForm.Remember)
  485. ctx.Session.Set("linkAccount", true)
  486. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  487. }
  488. // LinkAccountPostRegister handle the creation of a new account for an external account using signUp
  489. func LinkAccountPostRegister(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  490. ctx.Data["Title"] = ctx.Tr("link_account")
  491. ctx.Data["LinkAccountMode"] = true
  492. ctx.Data["LinkAccountModeRegister"] = true
  493. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  494. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  495. ctx.Data["ShowRegistrationButton"] = false
  496. // use this to set the right link into the signIn and signUp templates in the link_account template
  497. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  498. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  499. gothUser := ctx.Session.Get("linkAccountGothUser")
  500. if gothUser == nil {
  501. ctx.Handle(500, "UserSignUp", errors.New("not in LinkAccount session"))
  502. return
  503. }
  504. if ctx.HasError() {
  505. ctx.HTML(200, tplLinkAccount)
  506. return
  507. }
  508. if setting.Service.DisableRegistration {
  509. ctx.Error(403)
  510. return
  511. }
  512. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  513. ctx.Data["Err_Captcha"] = true
  514. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form)
  515. return
  516. }
  517. if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype {
  518. ctx.Data["Err_Password"] = true
  519. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form)
  520. return
  521. }
  522. if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength {
  523. ctx.Data["Err_Password"] = true
  524. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form)
  525. return
  526. }
  527. loginSource, err := models.GetActiveOAuth2LoginSourceByName(gothUser.(goth.User).Provider)
  528. if err != nil {
  529. ctx.Handle(500, "CreateUser", err)
  530. }
  531. u := &models.User{
  532. Name: form.UserName,
  533. Email: form.Email,
  534. Passwd: form.Password,
  535. IsActive: !setting.Service.RegisterEmailConfirm,
  536. LoginType: models.LoginOAuth2,
  537. LoginSource: loginSource.ID,
  538. LoginName: gothUser.(goth.User).UserID,
  539. }
  540. if err := models.CreateUser(u); err != nil {
  541. switch {
  542. case models.IsErrUserAlreadyExist(err):
  543. ctx.Data["Err_UserName"] = true
  544. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplLinkAccount, &form)
  545. case models.IsErrEmailAlreadyUsed(err):
  546. ctx.Data["Err_Email"] = true
  547. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplLinkAccount, &form)
  548. case models.IsErrNameReserved(err):
  549. ctx.Data["Err_UserName"] = true
  550. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplLinkAccount, &form)
  551. case models.IsErrNamePatternNotAllowed(err):
  552. ctx.Data["Err_UserName"] = true
  553. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplLinkAccount, &form)
  554. default:
  555. ctx.Handle(500, "CreateUser", err)
  556. }
  557. return
  558. }
  559. log.Trace("Account created: %s", u.Name)
  560. // Auto-set admin for the only user.
  561. if models.CountUsers() == 1 {
  562. u.IsAdmin = true
  563. u.IsActive = true
  564. if err := models.UpdateUser(u); err != nil {
  565. ctx.Handle(500, "UpdateUser", err)
  566. return
  567. }
  568. }
  569. // Send confirmation email
  570. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  571. models.SendActivateAccountMail(ctx.Context, u)
  572. ctx.Data["IsSendRegisterMail"] = true
  573. ctx.Data["Email"] = u.Email
  574. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  575. ctx.HTML(200, TplActivate)
  576. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  577. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  578. }
  579. return
  580. }
  581. ctx.Redirect(setting.AppSubURL + "/user/login")
  582. }
  583. // SignOut sign out from login status
  584. func SignOut(ctx *context.Context) {
  585. ctx.Session.Delete("uid")
  586. ctx.Session.Delete("uname")
  587. ctx.Session.Delete("socialId")
  588. ctx.Session.Delete("socialName")
  589. ctx.Session.Delete("socialEmail")
  590. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  591. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  592. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  593. ctx.Redirect(setting.AppSubURL + "/")
  594. }
  595. // SignUp render the register page
  596. func SignUp(ctx *context.Context) {
  597. ctx.Data["Title"] = ctx.Tr("sign_up")
  598. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
  599. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  600. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  601. ctx.HTML(200, tplSignUp)
  602. }
  603. // SignUpPost response for sign up information submission
  604. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  605. ctx.Data["Title"] = ctx.Tr("sign_up")
  606. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
  607. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  608. if setting.Service.DisableRegistration {
  609. ctx.Error(403)
  610. return
  611. }
  612. if ctx.HasError() {
  613. ctx.HTML(200, tplSignUp)
  614. return
  615. }
  616. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  617. ctx.Data["Err_Captcha"] = true
  618. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  619. return
  620. }
  621. if form.Password != form.Retype {
  622. ctx.Data["Err_Password"] = true
  623. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  624. return
  625. }
  626. if len(form.Password) < setting.MinPasswordLength {
  627. ctx.Data["Err_Password"] = true
  628. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
  629. return
  630. }
  631. u := &models.User{
  632. Name: form.UserName,
  633. Email: form.Email,
  634. Passwd: form.Password,
  635. IsActive: !setting.Service.RegisterEmailConfirm,
  636. }
  637. if err := models.CreateUser(u); err != nil {
  638. switch {
  639. case models.IsErrUserAlreadyExist(err):
  640. ctx.Data["Err_UserName"] = true
  641. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  642. case models.IsErrEmailAlreadyUsed(err):
  643. ctx.Data["Err_Email"] = true
  644. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  645. case models.IsErrNameReserved(err):
  646. ctx.Data["Err_UserName"] = true
  647. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  648. case models.IsErrNamePatternNotAllowed(err):
  649. ctx.Data["Err_UserName"] = true
  650. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  651. default:
  652. ctx.Handle(500, "CreateUser", err)
  653. }
  654. return
  655. }
  656. log.Trace("Account created: %s", u.Name)
  657. // Auto-set admin for the only user.
  658. if models.CountUsers() == 1 {
  659. u.IsAdmin = true
  660. u.IsActive = true
  661. if err := models.UpdateUser(u); err != nil {
  662. ctx.Handle(500, "UpdateUser", err)
  663. return
  664. }
  665. }
  666. // Send confirmation email, no need for social account.
  667. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  668. models.SendActivateAccountMail(ctx.Context, u)
  669. ctx.Data["IsSendRegisterMail"] = true
  670. ctx.Data["Email"] = u.Email
  671. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  672. ctx.HTML(200, TplActivate)
  673. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  674. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  675. }
  676. return
  677. }
  678. ctx.Redirect(setting.AppSubURL + "/user/login")
  679. }
  680. // Activate render activate user page
  681. func Activate(ctx *context.Context) {
  682. code := ctx.Query("code")
  683. if len(code) == 0 {
  684. ctx.Data["IsActivatePage"] = true
  685. if ctx.User.IsActive {
  686. ctx.Error(404)
  687. return
  688. }
  689. // Resend confirmation email.
  690. if setting.Service.RegisterEmailConfirm {
  691. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  692. ctx.Data["ResendLimited"] = true
  693. } else {
  694. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  695. models.SendActivateAccountMail(ctx.Context, ctx.User)
  696. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  697. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  698. }
  699. }
  700. } else {
  701. ctx.Data["ServiceNotEnabled"] = true
  702. }
  703. ctx.HTML(200, TplActivate)
  704. return
  705. }
  706. // Verify code.
  707. if user := models.VerifyUserActiveCode(code); user != nil {
  708. user.IsActive = true
  709. var err error
  710. if user.Rands, err = models.GetUserSalt(); err != nil {
  711. ctx.Handle(500, "UpdateUser", err)
  712. return
  713. }
  714. if err := models.UpdateUser(user); err != nil {
  715. if models.IsErrUserNotExist(err) {
  716. ctx.Error(404)
  717. } else {
  718. ctx.Handle(500, "UpdateUser", err)
  719. }
  720. return
  721. }
  722. log.Trace("User activated: %s", user.Name)
  723. ctx.Session.Set("uid", user.ID)
  724. ctx.Session.Set("uname", user.Name)
  725. ctx.Redirect(setting.AppSubURL + "/")
  726. return
  727. }
  728. ctx.Data["IsActivateFailed"] = true
  729. ctx.HTML(200, TplActivate)
  730. }
  731. // ActivateEmail render the activate email page
  732. func ActivateEmail(ctx *context.Context) {
  733. code := ctx.Query("code")
  734. emailStr := ctx.Query("email")
  735. // Verify code.
  736. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  737. if err := email.Activate(); err != nil {
  738. ctx.Handle(500, "ActivateEmail", err)
  739. }
  740. log.Trace("Email activated: %s", email.Email)
  741. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  742. }
  743. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  744. return
  745. }
  746. // ForgotPasswd render the forget pasword page
  747. func ForgotPasswd(ctx *context.Context) {
  748. ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
  749. if setting.MailService == nil {
  750. ctx.Data["IsResetDisable"] = true
  751. ctx.HTML(200, tplForgotPassword)
  752. return
  753. }
  754. email := ctx.Query("email")
  755. ctx.Data["Email"] = email
  756. ctx.Data["IsResetRequest"] = true
  757. ctx.HTML(200, tplForgotPassword)
  758. }
  759. // ForgotPasswdPost response for forget password request
  760. func ForgotPasswdPost(ctx *context.Context) {
  761. ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
  762. if setting.MailService == nil {
  763. ctx.Handle(403, "ForgotPasswdPost", nil)
  764. return
  765. }
  766. ctx.Data["IsResetRequest"] = true
  767. email := ctx.Query("email")
  768. ctx.Data["Email"] = email
  769. u, err := models.GetUserByEmail(email)
  770. if err != nil {
  771. if models.IsErrUserNotExist(err) {
  772. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  773. ctx.Data["IsResetSent"] = true
  774. ctx.HTML(200, tplForgotPassword)
  775. return
  776. }
  777. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  778. return
  779. }
  780. if !u.IsLocal() && !u.IsOAuth2() {
  781. ctx.Data["Err_Email"] = true
  782. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  783. return
  784. }
  785. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  786. ctx.Data["ResendLimited"] = true
  787. ctx.HTML(200, tplForgotPassword)
  788. return
  789. }
  790. models.SendResetPasswordMail(ctx.Context, u)
  791. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  792. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  793. }
  794. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  795. ctx.Data["IsResetSent"] = true
  796. ctx.HTML(200, tplForgotPassword)
  797. }
  798. // ResetPasswd render the reset password page
  799. func ResetPasswd(ctx *context.Context) {
  800. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  801. code := ctx.Query("code")
  802. if len(code) == 0 {
  803. ctx.Error(404)
  804. return
  805. }
  806. ctx.Data["Code"] = code
  807. ctx.Data["IsResetForm"] = true
  808. ctx.HTML(200, tplResetPassword)
  809. }
  810. // ResetPasswdPost response from reset password request
  811. func ResetPasswdPost(ctx *context.Context) {
  812. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  813. code := ctx.Query("code")
  814. if len(code) == 0 {
  815. ctx.Error(404)
  816. return
  817. }
  818. ctx.Data["Code"] = code
  819. if u := models.VerifyUserActiveCode(code); u != nil {
  820. // Validate password length.
  821. passwd := ctx.Query("password")
  822. if len(passwd) < setting.MinPasswordLength {
  823. ctx.Data["IsResetForm"] = true
  824. ctx.Data["Err_Password"] = true
  825. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil)
  826. return
  827. }
  828. u.Passwd = passwd
  829. var err error
  830. if u.Rands, err = models.GetUserSalt(); err != nil {
  831. ctx.Handle(500, "UpdateUser", err)
  832. return
  833. }
  834. if u.Salt, err = models.GetUserSalt(); err != nil {
  835. ctx.Handle(500, "UpdateUser", err)
  836. return
  837. }
  838. u.EncodePasswd()
  839. if err := models.UpdateUser(u); err != nil {
  840. ctx.Handle(500, "UpdateUser", err)
  841. return
  842. }
  843. log.Trace("User password reset: %s", u.Name)
  844. ctx.Redirect(setting.AppSubURL + "/user/login")
  845. return
  846. }
  847. ctx.Data["IsResetFailed"] = true
  848. ctx.HTML(200, tplResetPassword)
  849. }