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

auth.go 28 kB

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