本站源代码
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1431 行
43KB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package user
  6. import (
  7. "errors"
  8. "fmt"
  9. "net/http"
  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/password"
  18. "code.gitea.io/gitea/modules/recaptcha"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/timeutil"
  21. "code.gitea.io/gitea/modules/util"
  22. "code.gitea.io/gitea/services/externalaccount"
  23. "code.gitea.io/gitea/services/mailer"
  24. "gitea.com/macaron/captcha"
  25. "github.com/markbates/goth"
  26. "github.com/tstranex/u2f"
  27. )
  28. const (
  29. // tplMustChangePassword template for updating a user's password
  30. tplMustChangePassword = "user/auth/change_passwd"
  31. // tplSignIn template for sign in page
  32. tplSignIn base.TplName = "user/auth/signin"
  33. // tplSignUp template path for sign up page
  34. tplSignUp base.TplName = "user/auth/signup"
  35. // TplActivate template path for activate user
  36. TplActivate base.TplName = "user/auth/activate"
  37. tplForgotPassword base.TplName = "user/auth/forgot_passwd"
  38. tplResetPassword base.TplName = "user/auth/reset_passwd"
  39. tplTwofa base.TplName = "user/auth/twofa"
  40. tplTwofaScratch base.TplName = "user/auth/twofa_scratch"
  41. tplLinkAccount base.TplName = "user/auth/link_account"
  42. tplU2F base.TplName = "user/auth/u2f"
  43. )
  44. // AutoSignIn reads cookie and try to auto-login.
  45. func AutoSignIn(ctx *context.Context) (bool, error) {
  46. if !models.HasEngine {
  47. return false, nil
  48. }
  49. uname := ctx.GetCookie(setting.CookieUserName)
  50. if len(uname) == 0 {
  51. return false, nil
  52. }
  53. isSucceed := false
  54. defer func() {
  55. if !isSucceed {
  56. log.Trace("auto-login cookie cleared: %s", uname)
  57. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  58. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  59. }
  60. }()
  61. u, err := models.GetUserByName(uname)
  62. if err != nil {
  63. if !models.IsErrUserNotExist(err) {
  64. return false, fmt.Errorf("GetUserByName: %v", err)
  65. }
  66. return false, nil
  67. }
  68. if val, ok := ctx.GetSuperSecureCookie(
  69. base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); !ok || val != u.Name {
  70. return false, nil
  71. }
  72. isSucceed = true
  73. err = ctx.Session.Set("uid", u.ID)
  74. if err != nil {
  75. return false, err
  76. }
  77. err = ctx.Session.Set("uname", u.Name)
  78. if err != nil {
  79. return false, err
  80. }
  81. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  82. return true, nil
  83. }
  84. func checkAutoLogin(ctx *context.Context) bool {
  85. // Check auto-login.
  86. isSucceed, err := AutoSignIn(ctx)
  87. if err != nil {
  88. ctx.ServerError("AutoSignIn", err)
  89. return true
  90. }
  91. redirectTo := ctx.Query("redirect_to")
  92. if len(redirectTo) > 0 {
  93. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  94. } else {
  95. redirectTo = ctx.GetCookie("redirect_to")
  96. }
  97. if isSucceed {
  98. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  99. ctx.RedirectToFirst(redirectTo, setting.AppSubURL+string(setting.LandingPageURL))
  100. return true
  101. }
  102. return false
  103. }
  104. // SignIn render sign in page
  105. func SignIn(ctx *context.Context) {
  106. ctx.Data["Title"] = ctx.Tr("sign_in")
  107. // Check auto-login.
  108. if checkAutoLogin(ctx) {
  109. return
  110. }
  111. orderedOAuth2Names, oauth2Providers, err := models.GetActiveOAuth2Providers()
  112. if err != nil {
  113. ctx.ServerError("UserSignIn", err)
  114. return
  115. }
  116. ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names
  117. ctx.Data["OAuth2Providers"] = oauth2Providers
  118. ctx.Data["Title"] = ctx.Tr("sign_in")
  119. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  120. ctx.Data["PageIsSignIn"] = true
  121. ctx.Data["PageIsLogin"] = true
  122. ctx.HTML(200, tplSignIn)
  123. }
  124. // SignInPost response for sign in request
  125. func SignInPost(ctx *context.Context, form auth.SignInForm) {
  126. ctx.Data["Title"] = ctx.Tr("sign_in")
  127. orderedOAuth2Names, oauth2Providers, err := models.GetActiveOAuth2Providers()
  128. if err != nil {
  129. ctx.ServerError("UserSignIn", err)
  130. return
  131. }
  132. ctx.Data["OrderedOAuth2Names"] = orderedOAuth2Names
  133. ctx.Data["OAuth2Providers"] = oauth2Providers
  134. ctx.Data["Title"] = ctx.Tr("sign_in")
  135. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
  136. ctx.Data["PageIsSignIn"] = true
  137. ctx.Data["PageIsLogin"] = true
  138. if ctx.HasError() {
  139. ctx.HTML(200, tplSignIn)
  140. return
  141. }
  142. u, err := models.UserSignIn(form.UserName, form.Password)
  143. if err != nil {
  144. if models.IsErrUserNotExist(err) {
  145. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form)
  146. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  147. } else if models.IsErrEmailAlreadyUsed(err) {
  148. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignIn, &form)
  149. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  150. } else if models.IsErrUserProhibitLogin(err) {
  151. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  152. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  153. ctx.HTML(200, "user/auth/prohibit_login")
  154. } else if models.IsErrUserInactive(err) {
  155. if setting.Service.RegisterEmailConfirm {
  156. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  157. ctx.HTML(200, TplActivate)
  158. } else {
  159. log.Info("Failed authentication attempt for %s from %s", form.UserName, ctx.RemoteAddr())
  160. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  161. ctx.HTML(200, "user/auth/prohibit_login")
  162. }
  163. } else {
  164. ctx.ServerError("UserSignIn", err)
  165. }
  166. return
  167. }
  168. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  169. // Instead, redirect them to the 2FA authentication page.
  170. _, err = models.GetTwoFactorByUID(u.ID)
  171. if err != nil {
  172. if models.IsErrTwoFactorNotEnrolled(err) {
  173. handleSignIn(ctx, u, form.Remember)
  174. } else {
  175. ctx.ServerError("UserSignIn", err)
  176. }
  177. return
  178. }
  179. // User needs to use 2FA, save data and redirect to 2FA page.
  180. err = ctx.Session.Set("twofaUid", u.ID)
  181. if err != nil {
  182. ctx.ServerError("UserSignIn", err)
  183. return
  184. }
  185. err = ctx.Session.Set("twofaRemember", form.Remember)
  186. if err != nil {
  187. ctx.ServerError("UserSignIn", err)
  188. return
  189. }
  190. regs, err := models.GetU2FRegistrationsByUID(u.ID)
  191. if err == nil && len(regs) > 0 {
  192. ctx.Redirect(setting.AppSubURL + "/user/u2f")
  193. return
  194. }
  195. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  196. }
  197. // TwoFactor shows the user a two-factor authentication page.
  198. func TwoFactor(ctx *context.Context) {
  199. ctx.Data["Title"] = ctx.Tr("twofa")
  200. // Check auto-login.
  201. if checkAutoLogin(ctx) {
  202. return
  203. }
  204. // Ensure user is in a 2FA session.
  205. if ctx.Session.Get("twofaUid") == nil {
  206. ctx.ServerError("UserSignIn", errors.New("not in 2FA session"))
  207. return
  208. }
  209. ctx.HTML(200, tplTwofa)
  210. }
  211. // TwoFactorPost validates a user's two-factor authentication token.
  212. func TwoFactorPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  213. ctx.Data["Title"] = ctx.Tr("twofa")
  214. // Ensure user is in a 2FA session.
  215. idSess := ctx.Session.Get("twofaUid")
  216. if idSess == nil {
  217. ctx.ServerError("UserSignIn", errors.New("not in 2FA session"))
  218. return
  219. }
  220. id := idSess.(int64)
  221. twofa, err := models.GetTwoFactorByUID(id)
  222. if err != nil {
  223. ctx.ServerError("UserSignIn", err)
  224. return
  225. }
  226. // Validate the passcode with the stored TOTP secret.
  227. ok, err := twofa.ValidateTOTP(form.Passcode)
  228. if err != nil {
  229. ctx.ServerError("UserSignIn", err)
  230. return
  231. }
  232. if ok && twofa.LastUsedPasscode != form.Passcode {
  233. remember := ctx.Session.Get("twofaRemember").(bool)
  234. u, err := models.GetUserByID(id)
  235. if err != nil {
  236. ctx.ServerError("UserSignIn", err)
  237. return
  238. }
  239. if ctx.Session.Get("linkAccount") != nil {
  240. gothUser := ctx.Session.Get("linkAccountGothUser")
  241. if gothUser == nil {
  242. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  243. return
  244. }
  245. err = externalaccount.LinkAccountToUser(u, gothUser.(goth.User))
  246. if err != nil {
  247. ctx.ServerError("UserSignIn", err)
  248. return
  249. }
  250. }
  251. twofa.LastUsedPasscode = form.Passcode
  252. if err = models.UpdateTwoFactor(twofa); err != nil {
  253. ctx.ServerError("UserSignIn", err)
  254. return
  255. }
  256. handleSignIn(ctx, u, remember)
  257. return
  258. }
  259. ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, auth.TwoFactorAuthForm{})
  260. }
  261. // TwoFactorScratch shows the scratch code form for two-factor authentication.
  262. func TwoFactorScratch(ctx *context.Context) {
  263. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  264. // Check auto-login.
  265. if checkAutoLogin(ctx) {
  266. return
  267. }
  268. // Ensure user is in a 2FA session.
  269. if ctx.Session.Get("twofaUid") == nil {
  270. ctx.ServerError("UserSignIn", errors.New("not in 2FA session"))
  271. return
  272. }
  273. ctx.HTML(200, tplTwofaScratch)
  274. }
  275. // TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
  276. func TwoFactorScratchPost(ctx *context.Context, form auth.TwoFactorScratchAuthForm) {
  277. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  278. // Ensure user is in a 2FA session.
  279. idSess := ctx.Session.Get("twofaUid")
  280. if idSess == nil {
  281. ctx.ServerError("UserSignIn", errors.New("not in 2FA session"))
  282. return
  283. }
  284. id := idSess.(int64)
  285. twofa, err := models.GetTwoFactorByUID(id)
  286. if err != nil {
  287. ctx.ServerError("UserSignIn", err)
  288. return
  289. }
  290. // Validate the passcode with the stored TOTP secret.
  291. if twofa.VerifyScratchToken(form.Token) {
  292. // Invalidate the scratch token.
  293. _, err = twofa.GenerateScratchToken()
  294. if err != nil {
  295. ctx.ServerError("UserSignIn", err)
  296. return
  297. }
  298. if err = models.UpdateTwoFactor(twofa); err != nil {
  299. ctx.ServerError("UserSignIn", err)
  300. return
  301. }
  302. remember := ctx.Session.Get("twofaRemember").(bool)
  303. u, err := models.GetUserByID(id)
  304. if err != nil {
  305. ctx.ServerError("UserSignIn", err)
  306. return
  307. }
  308. handleSignInFull(ctx, u, remember, false)
  309. ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used"))
  310. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  311. return
  312. }
  313. ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, auth.TwoFactorScratchAuthForm{})
  314. }
  315. // U2F shows the U2F login page
  316. func U2F(ctx *context.Context) {
  317. ctx.Data["Title"] = ctx.Tr("twofa")
  318. ctx.Data["RequireU2F"] = true
  319. // Check auto-login.
  320. if checkAutoLogin(ctx) {
  321. return
  322. }
  323. // Ensure user is in a 2FA session.
  324. if ctx.Session.Get("twofaUid") == nil {
  325. ctx.ServerError("UserSignIn", errors.New("not in U2F session"))
  326. return
  327. }
  328. ctx.HTML(200, tplU2F)
  329. }
  330. // U2FChallenge submits a sign challenge to the browser
  331. func U2FChallenge(ctx *context.Context) {
  332. // Ensure user is in a U2F session.
  333. idSess := ctx.Session.Get("twofaUid")
  334. if idSess == nil {
  335. ctx.ServerError("UserSignIn", errors.New("not in U2F session"))
  336. return
  337. }
  338. id := idSess.(int64)
  339. regs, err := models.GetU2FRegistrationsByUID(id)
  340. if err != nil {
  341. ctx.ServerError("UserSignIn", err)
  342. return
  343. }
  344. if len(regs) == 0 {
  345. ctx.ServerError("UserSignIn", errors.New("no device registered"))
  346. return
  347. }
  348. challenge, err := u2f.NewChallenge(setting.U2F.AppID, setting.U2F.TrustedFacets)
  349. if err != nil {
  350. ctx.ServerError("u2f.NewChallenge", err)
  351. return
  352. }
  353. if err = ctx.Session.Set("u2fChallenge", challenge); err != nil {
  354. ctx.ServerError("UserSignIn", err)
  355. return
  356. }
  357. ctx.JSON(200, challenge.SignRequest(regs.ToRegistrations()))
  358. }
  359. // U2FSign authenticates the user by signResp
  360. func U2FSign(ctx *context.Context, signResp u2f.SignResponse) {
  361. challSess := ctx.Session.Get("u2fChallenge")
  362. idSess := ctx.Session.Get("twofaUid")
  363. if challSess == nil || idSess == nil {
  364. ctx.ServerError("UserSignIn", errors.New("not in U2F session"))
  365. return
  366. }
  367. challenge := challSess.(*u2f.Challenge)
  368. id := idSess.(int64)
  369. regs, err := models.GetU2FRegistrationsByUID(id)
  370. if err != nil {
  371. ctx.ServerError("UserSignIn", err)
  372. return
  373. }
  374. for _, reg := range regs {
  375. r, err := reg.Parse()
  376. if err != nil {
  377. log.Fatal("parsing u2f registration: %v", err)
  378. continue
  379. }
  380. newCounter, authErr := r.Authenticate(signResp, *challenge, reg.Counter)
  381. if authErr == nil {
  382. reg.Counter = newCounter
  383. user, err := models.GetUserByID(id)
  384. if err != nil {
  385. ctx.ServerError("UserSignIn", err)
  386. return
  387. }
  388. remember := ctx.Session.Get("twofaRemember").(bool)
  389. if err := reg.UpdateCounter(); err != nil {
  390. ctx.ServerError("UserSignIn", err)
  391. return
  392. }
  393. if ctx.Session.Get("linkAccount") != nil {
  394. gothUser := ctx.Session.Get("linkAccountGothUser")
  395. if gothUser == nil {
  396. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  397. return
  398. }
  399. err = externalaccount.LinkAccountToUser(user, gothUser.(goth.User))
  400. if err != nil {
  401. ctx.ServerError("UserSignIn", err)
  402. return
  403. }
  404. }
  405. redirect := handleSignInFull(ctx, user, remember, false)
  406. if redirect == "" {
  407. redirect = setting.AppSubURL + "/"
  408. }
  409. ctx.PlainText(200, []byte(redirect))
  410. return
  411. }
  412. }
  413. ctx.Error(401)
  414. }
  415. // This handles the final part of the sign-in process of the user.
  416. func handleSignIn(ctx *context.Context, u *models.User, remember bool) {
  417. handleSignInFull(ctx, u, remember, true)
  418. }
  419. func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyRedirect bool) string {
  420. if remember {
  421. days := 86400 * setting.LogInRememberDays
  422. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  423. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  424. setting.CookieRememberName, u.Name, days, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  425. }
  426. _ = ctx.Session.Delete("openid_verified_uri")
  427. _ = ctx.Session.Delete("openid_signin_remember")
  428. _ = ctx.Session.Delete("openid_determined_email")
  429. _ = ctx.Session.Delete("openid_determined_username")
  430. _ = ctx.Session.Delete("twofaUid")
  431. _ = ctx.Session.Delete("twofaRemember")
  432. _ = ctx.Session.Delete("u2fChallenge")
  433. _ = ctx.Session.Delete("linkAccount")
  434. err := ctx.Session.Set("uid", u.ID)
  435. if err != nil {
  436. log.Error(fmt.Sprintf("Error setting session: %v", err))
  437. }
  438. err = ctx.Session.Set("uname", u.Name)
  439. if err != nil {
  440. log.Error(fmt.Sprintf("Error setting session: %v", err))
  441. }
  442. // Language setting of the user overwrites the one previously set
  443. // If the user does not have a locale set, we save the current one.
  444. if len(u.Language) == 0 {
  445. u.Language = ctx.Locale.Language()
  446. if err := models.UpdateUserCols(u, "language"); err != nil {
  447. log.Error(fmt.Sprintf("Error updating user language [user: %d, locale: %s]", u.ID, u.Language))
  448. return setting.AppSubURL + "/"
  449. }
  450. }
  451. ctx.SetCookie("lang", u.Language, nil, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  452. // Clear whatever CSRF has right now, force to generate a new one
  453. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  454. // Register last login
  455. u.SetLastLogin()
  456. if err := models.UpdateUserCols(u, "last_login_unix"); err != nil {
  457. ctx.ServerError("UpdateUserCols", err)
  458. return setting.AppSubURL + "/"
  459. }
  460. if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 && !util.IsExternalURL(redirectTo) {
  461. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  462. if obeyRedirect {
  463. ctx.RedirectToFirst(redirectTo)
  464. }
  465. return redirectTo
  466. }
  467. if obeyRedirect {
  468. ctx.Redirect(setting.AppSubURL + "/")
  469. }
  470. return setting.AppSubURL + "/"
  471. }
  472. // SignInOAuth handles the OAuth2 login buttons
  473. func SignInOAuth(ctx *context.Context) {
  474. provider := ctx.Params(":provider")
  475. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  476. if err != nil {
  477. ctx.ServerError("SignIn", err)
  478. return
  479. }
  480. // try to do a direct callback flow, so we don't authenticate the user again but use the valid accesstoken to get the user
  481. user, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  482. if err == nil && user != nil {
  483. // we got the user without going through the whole OAuth2 authentication flow again
  484. handleOAuth2SignIn(user, gothUser, ctx, err)
  485. return
  486. }
  487. err = oauth2.Auth(loginSource.Name, ctx.Req.Request, ctx.Resp)
  488. if err != nil {
  489. ctx.ServerError("SignIn", err)
  490. }
  491. // redirect is done in oauth2.Auth
  492. }
  493. // SignInOAuthCallback handles the callback from the given provider
  494. func SignInOAuthCallback(ctx *context.Context) {
  495. provider := ctx.Params(":provider")
  496. // first look if the provider is still active
  497. loginSource, err := models.GetActiveOAuth2LoginSourceByName(provider)
  498. if err != nil {
  499. ctx.ServerError("SignIn", err)
  500. return
  501. }
  502. if loginSource == nil {
  503. ctx.ServerError("SignIn", errors.New("No valid provider found, check configured callback url in provider"))
  504. return
  505. }
  506. u, gothUser, err := oAuth2UserLoginCallback(loginSource, ctx.Req.Request, ctx.Resp)
  507. handleOAuth2SignIn(u, gothUser, ctx, err)
  508. }
  509. func handleOAuth2SignIn(u *models.User, gothUser goth.User, ctx *context.Context, err error) {
  510. if err != nil {
  511. ctx.ServerError("UserSignIn", err)
  512. return
  513. }
  514. if u == nil {
  515. // no existing user is found, request attach or new account
  516. err = ctx.Session.Set("linkAccountGothUser", gothUser)
  517. if err != nil {
  518. log.Error(fmt.Sprintf("Error setting session: %v", err))
  519. }
  520. ctx.Redirect(setting.AppSubURL + "/user/link_account")
  521. return
  522. }
  523. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  524. // Instead, redirect them to the 2FA authentication page.
  525. _, err = models.GetTwoFactorByUID(u.ID)
  526. if err != nil {
  527. if !models.IsErrTwoFactorNotEnrolled(err) {
  528. ctx.ServerError("UserSignIn", err)
  529. return
  530. }
  531. err = ctx.Session.Set("uid", u.ID)
  532. if err != nil {
  533. log.Error(fmt.Sprintf("Error setting session: %v", err))
  534. }
  535. err = ctx.Session.Set("uname", u.Name)
  536. if err != nil {
  537. log.Error(fmt.Sprintf("Error setting session: %v", err))
  538. }
  539. // Clear whatever CSRF has right now, force to generate a new one
  540. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  541. // Register last login
  542. u.SetLastLogin()
  543. if err := models.UpdateUserCols(u, "last_login_unix"); err != nil {
  544. ctx.ServerError("UpdateUserCols", err)
  545. return
  546. }
  547. // update external user information
  548. if err := models.UpdateExternalUser(u, gothUser); err != nil {
  549. log.Error("UpdateExternalUser failed: %v", err)
  550. }
  551. if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 {
  552. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  553. ctx.RedirectToFirst(redirectTo)
  554. return
  555. }
  556. ctx.Redirect(setting.AppSubURL + "/")
  557. return
  558. }
  559. // User needs to use 2FA, save data and redirect to 2FA page.
  560. err = ctx.Session.Set("twofaUid", u.ID)
  561. if err != nil {
  562. log.Error(fmt.Sprintf("Error setting session: %v", err))
  563. }
  564. err = ctx.Session.Set("twofaRemember", false)
  565. if err != nil {
  566. log.Error(fmt.Sprintf("Error setting session: %v", err))
  567. }
  568. // If U2F is enrolled -> Redirect to U2F instead
  569. regs, err := models.GetU2FRegistrationsByUID(u.ID)
  570. if err == nil && len(regs) > 0 {
  571. ctx.Redirect(setting.AppSubURL + "/user/u2f")
  572. return
  573. }
  574. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  575. }
  576. // OAuth2UserLoginCallback attempts to handle the callback from the OAuth2 provider and if successful
  577. // login the user
  578. func oAuth2UserLoginCallback(loginSource *models.LoginSource, request *http.Request, response http.ResponseWriter) (*models.User, goth.User, error) {
  579. gothUser, err := oauth2.ProviderCallback(loginSource.Name, request, response)
  580. if err != nil {
  581. return nil, goth.User{}, err
  582. }
  583. user := &models.User{
  584. LoginName: gothUser.UserID,
  585. LoginType: models.LoginOAuth2,
  586. LoginSource: loginSource.ID,
  587. }
  588. hasUser, err := models.GetUser(user)
  589. if err != nil {
  590. return nil, goth.User{}, err
  591. }
  592. if hasUser {
  593. return user, gothUser, nil
  594. }
  595. // search in external linked users
  596. externalLoginUser := &models.ExternalLoginUser{
  597. ExternalID: gothUser.UserID,
  598. LoginSourceID: loginSource.ID,
  599. }
  600. hasUser, err = models.GetExternalLogin(externalLoginUser)
  601. if err != nil {
  602. return nil, goth.User{}, err
  603. }
  604. if hasUser {
  605. user, err = models.GetUserByID(externalLoginUser.UserID)
  606. return user, gothUser, err
  607. }
  608. // no user found to login
  609. return nil, gothUser, nil
  610. }
  611. // LinkAccount shows the page where the user can decide to login or create a new account
  612. func LinkAccount(ctx *context.Context) {
  613. ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationCaptcha || setting.Service.AllowOnlyExternalRegistration
  614. ctx.Data["Title"] = ctx.Tr("link_account")
  615. ctx.Data["LinkAccountMode"] = true
  616. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  617. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  618. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  619. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  620. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  621. ctx.Data["ShowRegistrationButton"] = false
  622. // use this to set the right link into the signIn and signUp templates in the link_account template
  623. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  624. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  625. gothUser := ctx.Session.Get("linkAccountGothUser")
  626. if gothUser == nil {
  627. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  628. return
  629. }
  630. uname := gothUser.(goth.User).NickName
  631. email := gothUser.(goth.User).Email
  632. ctx.Data["user_name"] = uname
  633. ctx.Data["email"] = email
  634. if len(email) != 0 {
  635. u, err := models.GetUserByEmail(email)
  636. if err != nil && !models.IsErrUserNotExist(err) {
  637. ctx.ServerError("UserSignIn", err)
  638. return
  639. }
  640. if u != nil {
  641. ctx.Data["user_exists"] = true
  642. }
  643. } else if len(uname) != 0 {
  644. u, err := models.GetUserByName(uname)
  645. if err != nil && !models.IsErrUserNotExist(err) {
  646. ctx.ServerError("UserSignIn", err)
  647. return
  648. }
  649. if u != nil {
  650. ctx.Data["user_exists"] = true
  651. }
  652. }
  653. ctx.HTML(200, tplLinkAccount)
  654. }
  655. // LinkAccountPostSignIn handle the coupling of external account with another account using signIn
  656. func LinkAccountPostSignIn(ctx *context.Context, signInForm auth.SignInForm) {
  657. ctx.Data["DisablePassword"] = setting.Service.AllowOnlyExternalRegistration
  658. ctx.Data["Title"] = ctx.Tr("link_account")
  659. ctx.Data["LinkAccountMode"] = true
  660. ctx.Data["LinkAccountModeSignIn"] = true
  661. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  662. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  663. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  664. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  665. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  666. ctx.Data["ShowRegistrationButton"] = false
  667. // use this to set the right link into the signIn and signUp templates in the link_account template
  668. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  669. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  670. gothUser := ctx.Session.Get("linkAccountGothUser")
  671. if gothUser == nil {
  672. ctx.ServerError("UserSignIn", errors.New("not in LinkAccount session"))
  673. return
  674. }
  675. if ctx.HasError() {
  676. ctx.HTML(200, tplLinkAccount)
  677. return
  678. }
  679. u, err := models.UserSignIn(signInForm.UserName, signInForm.Password)
  680. if err != nil {
  681. if models.IsErrUserNotExist(err) {
  682. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplLinkAccount, &signInForm)
  683. } else {
  684. ctx.ServerError("UserLinkAccount", err)
  685. }
  686. return
  687. }
  688. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  689. // Instead, redirect them to the 2FA authentication page.
  690. _, err = models.GetTwoFactorByUID(u.ID)
  691. if err != nil {
  692. if !models.IsErrTwoFactorNotEnrolled(err) {
  693. ctx.ServerError("UserLinkAccount", err)
  694. return
  695. }
  696. err = externalaccount.LinkAccountToUser(u, gothUser.(goth.User))
  697. if err != nil {
  698. ctx.ServerError("UserLinkAccount", err)
  699. return
  700. }
  701. handleSignIn(ctx, u, signInForm.Remember)
  702. return
  703. }
  704. // User needs to use 2FA, save data and redirect to 2FA page.
  705. err = ctx.Session.Set("twofaUid", u.ID)
  706. if err != nil {
  707. log.Error(fmt.Sprintf("Error setting session: %v", err))
  708. }
  709. err = ctx.Session.Set("twofaRemember", signInForm.Remember)
  710. if err != nil {
  711. log.Error(fmt.Sprintf("Error setting session: %v", err))
  712. }
  713. err = ctx.Session.Set("linkAccount", true)
  714. if err != nil {
  715. log.Error(fmt.Sprintf("Error setting session: %v", err))
  716. }
  717. // If U2F is enrolled -> Redirect to U2F instead
  718. regs, err := models.GetU2FRegistrationsByUID(u.ID)
  719. if err == nil && len(regs) > 0 {
  720. ctx.Redirect(setting.AppSubURL + "/user/u2f")
  721. return
  722. }
  723. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  724. }
  725. // LinkAccountPostRegister handle the creation of a new account for an external account using signUp
  726. func LinkAccountPostRegister(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  727. // TODO Make insecure passwords optional for local accounts also,
  728. // once email-based Second-Factor Auth is available
  729. ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationCaptcha || setting.Service.AllowOnlyExternalRegistration
  730. ctx.Data["Title"] = ctx.Tr("link_account")
  731. ctx.Data["LinkAccountMode"] = true
  732. ctx.Data["LinkAccountModeRegister"] = true
  733. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha
  734. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  735. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  736. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  737. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  738. ctx.Data["ShowRegistrationButton"] = false
  739. // use this to set the right link into the signIn and signUp templates in the link_account template
  740. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
  741. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
  742. gothUser := ctx.Session.Get("linkAccountGothUser")
  743. if gothUser == nil {
  744. ctx.ServerError("UserSignUp", errors.New("not in LinkAccount session"))
  745. return
  746. }
  747. if ctx.HasError() {
  748. ctx.HTML(200, tplLinkAccount)
  749. return
  750. }
  751. if setting.Service.DisableRegistration {
  752. ctx.Error(403)
  753. return
  754. }
  755. if setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha {
  756. var valid bool
  757. switch setting.Service.CaptchaType {
  758. case setting.ImageCaptcha:
  759. valid = cpt.VerifyReq(ctx.Req)
  760. case setting.ReCaptcha:
  761. valid, _ = recaptcha.Verify(form.GRecaptchaResponse)
  762. default:
  763. ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType))
  764. return
  765. }
  766. if !valid {
  767. ctx.Data["Err_Captcha"] = true
  768. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form)
  769. return
  770. }
  771. }
  772. if setting.Service.AllowOnlyExternalRegistration || !setting.Service.RequireExternalRegistrationPassword {
  773. // In models.User an empty password is classed as not set, so we set form.Password to empty.
  774. // Eventually the database should be changed to indicate "Second Factor"-enabled accounts
  775. // (accounts that do not introduce the security vulnerabilities of a password).
  776. // If a user decides to circumvent second-factor security, and purposefully create a password,
  777. // they can still do so using the "Recover Account" option.
  778. form.Password = ""
  779. } else {
  780. if (len(strings.TrimSpace(form.Password)) > 0 || len(strings.TrimSpace(form.Retype)) > 0) && form.Password != form.Retype {
  781. ctx.Data["Err_Password"] = true
  782. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplLinkAccount, &form)
  783. return
  784. }
  785. if len(strings.TrimSpace(form.Password)) > 0 && len(form.Password) < setting.MinPasswordLength {
  786. ctx.Data["Err_Password"] = true
  787. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplLinkAccount, &form)
  788. return
  789. }
  790. }
  791. loginSource, err := models.GetActiveOAuth2LoginSourceByName(gothUser.(goth.User).Provider)
  792. if err != nil {
  793. ctx.ServerError("CreateUser", err)
  794. }
  795. u := &models.User{
  796. Name: form.UserName,
  797. Email: form.Email,
  798. Passwd: form.Password,
  799. IsActive: !setting.Service.RegisterEmailConfirm,
  800. LoginType: models.LoginOAuth2,
  801. LoginSource: loginSource.ID,
  802. LoginName: gothUser.(goth.User).UserID,
  803. }
  804. if err := models.CreateUser(u); err != nil {
  805. switch {
  806. case models.IsErrUserAlreadyExist(err):
  807. ctx.Data["Err_UserName"] = true
  808. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplLinkAccount, &form)
  809. case models.IsErrEmailAlreadyUsed(err):
  810. ctx.Data["Err_Email"] = true
  811. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplLinkAccount, &form)
  812. case models.IsErrNameReserved(err):
  813. ctx.Data["Err_UserName"] = true
  814. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplLinkAccount, &form)
  815. case models.IsErrNamePatternNotAllowed(err):
  816. ctx.Data["Err_UserName"] = true
  817. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplLinkAccount, &form)
  818. default:
  819. ctx.ServerError("CreateUser", err)
  820. }
  821. return
  822. }
  823. log.Trace("Account created: %s", u.Name)
  824. // Auto-set admin for the only user.
  825. if models.CountUsers() == 1 {
  826. u.IsAdmin = true
  827. u.IsActive = true
  828. u.SetLastLogin()
  829. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  830. ctx.ServerError("UpdateUser", err)
  831. return
  832. }
  833. }
  834. // update external user information
  835. if err := models.UpdateExternalUser(u, gothUser.(goth.User)); err != nil {
  836. log.Error("UpdateExternalUser failed: %v", err)
  837. }
  838. // Send confirmation email
  839. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  840. mailer.SendActivateAccountMail(ctx.Locale, u)
  841. ctx.Data["IsSendRegisterMail"] = true
  842. ctx.Data["Email"] = u.Email
  843. ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  844. ctx.HTML(200, TplActivate)
  845. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  846. log.Error("Set cache(MailResendLimit) fail: %v", err)
  847. }
  848. return
  849. }
  850. ctx.Redirect(setting.AppSubURL + "/user/login")
  851. }
  852. func handleSignOut(ctx *context.Context) {
  853. _ = ctx.Session.Delete("uid")
  854. _ = ctx.Session.Delete("uname")
  855. _ = ctx.Session.Delete("socialId")
  856. _ = ctx.Session.Delete("socialName")
  857. _ = ctx.Session.Delete("socialEmail")
  858. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  859. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  860. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true)
  861. ctx.SetCookie("lang", "", -1, setting.AppSubURL, setting.SessionConfig.Domain, setting.SessionConfig.Secure, true) // Setting the lang cookie will trigger the middleware to reset the language ot previous state.
  862. }
  863. // SignOut sign out from login status
  864. func SignOut(ctx *context.Context) {
  865. handleSignOut(ctx)
  866. ctx.Redirect(setting.AppSubURL + "/")
  867. }
  868. // SignUp render the register page
  869. func SignUp(ctx *context.Context) {
  870. ctx.Data["Title"] = ctx.Tr("sign_up")
  871. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
  872. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  873. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  874. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  875. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  876. ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
  877. ctx.HTML(200, tplSignUp)
  878. }
  879. // SignUpPost response for sign up information submission
  880. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  881. ctx.Data["Title"] = ctx.Tr("sign_up")
  882. ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
  883. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  884. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  885. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  886. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  887. //Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true
  888. if setting.Service.DisableRegistration {
  889. ctx.Error(403)
  890. return
  891. }
  892. if ctx.HasError() {
  893. ctx.HTML(200, tplSignUp)
  894. return
  895. }
  896. if setting.Service.EnableCaptcha {
  897. var valid bool
  898. switch setting.Service.CaptchaType {
  899. case setting.ImageCaptcha:
  900. valid = cpt.VerifyReq(ctx.Req)
  901. case setting.ReCaptcha:
  902. valid, _ = recaptcha.Verify(form.GRecaptchaResponse)
  903. default:
  904. ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType))
  905. return
  906. }
  907. if !valid {
  908. ctx.Data["Err_Captcha"] = true
  909. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  910. return
  911. }
  912. }
  913. if !form.IsEmailDomainWhitelisted() {
  914. ctx.RenderWithErr(ctx.Tr("auth.email_domain_blacklisted"), tplSignUp, &form)
  915. return
  916. }
  917. if form.Password != form.Retype {
  918. ctx.Data["Err_Password"] = true
  919. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  920. return
  921. }
  922. if len(form.Password) < setting.MinPasswordLength {
  923. ctx.Data["Err_Password"] = true
  924. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
  925. return
  926. }
  927. u := &models.User{
  928. Name: form.UserName,
  929. Email: form.Email,
  930. Passwd: form.Password,
  931. IsActive: !setting.Service.RegisterEmailConfirm,
  932. }
  933. if err := models.CreateUser(u); err != nil {
  934. switch {
  935. case models.IsErrUserAlreadyExist(err):
  936. ctx.Data["Err_UserName"] = true
  937. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  938. case models.IsErrEmailAlreadyUsed(err):
  939. ctx.Data["Err_Email"] = true
  940. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  941. case models.IsErrNameReserved(err):
  942. ctx.Data["Err_UserName"] = true
  943. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  944. case models.IsErrNamePatternNotAllowed(err):
  945. ctx.Data["Err_UserName"] = true
  946. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  947. default:
  948. ctx.ServerError("CreateUser", err)
  949. }
  950. return
  951. }
  952. log.Trace("Account created: %s", u.Name)
  953. // Auto-set admin for the only user.
  954. if models.CountUsers() == 1 {
  955. u.IsAdmin = true
  956. u.IsActive = true
  957. u.SetLastLogin()
  958. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  959. ctx.ServerError("UpdateUser", err)
  960. return
  961. }
  962. }
  963. // Send confirmation email, no need for social account.
  964. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  965. mailer.SendActivateAccountMail(ctx.Locale, u)
  966. ctx.Data["IsSendRegisterMail"] = true
  967. ctx.Data["Email"] = u.Email
  968. ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  969. ctx.HTML(200, TplActivate)
  970. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  971. log.Error("Set cache(MailResendLimit) fail: %v", err)
  972. }
  973. return
  974. }
  975. ctx.Flash.Success(ctx.Tr("auth.sign_up_successful"))
  976. handleSignInFull(ctx, u, false, true)
  977. }
  978. // Activate render activate user page
  979. func Activate(ctx *context.Context) {
  980. code := ctx.Query("code")
  981. if len(code) == 0 {
  982. ctx.Data["IsActivatePage"] = true
  983. if ctx.User.IsActive {
  984. ctx.Error(404)
  985. return
  986. }
  987. // Resend confirmation email.
  988. if setting.Service.RegisterEmailConfirm {
  989. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  990. ctx.Data["ResendLimited"] = true
  991. } else {
  992. ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  993. mailer.SendActivateAccountMail(ctx.Locale, ctx.User)
  994. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  995. log.Error("Set cache(MailResendLimit) fail: %v", err)
  996. }
  997. }
  998. } else {
  999. ctx.Data["ServiceNotEnabled"] = true
  1000. }
  1001. ctx.HTML(200, TplActivate)
  1002. return
  1003. }
  1004. // Verify code.
  1005. if user := models.VerifyUserActiveCode(code); user != nil {
  1006. user.IsActive = true
  1007. var err error
  1008. if user.Rands, err = models.GetUserSalt(); err != nil {
  1009. ctx.ServerError("UpdateUser", err)
  1010. return
  1011. }
  1012. if err := models.UpdateUserCols(user, "is_active", "rands"); err != nil {
  1013. if models.IsErrUserNotExist(err) {
  1014. ctx.Error(404)
  1015. } else {
  1016. ctx.ServerError("UpdateUser", err)
  1017. }
  1018. return
  1019. }
  1020. log.Trace("User activated: %s", user.Name)
  1021. err = ctx.Session.Set("uid", user.ID)
  1022. if err != nil {
  1023. log.Error(fmt.Sprintf("Error setting session: %v", err))
  1024. }
  1025. err = ctx.Session.Set("uname", user.Name)
  1026. if err != nil {
  1027. log.Error(fmt.Sprintf("Error setting session: %v", err))
  1028. }
  1029. ctx.Flash.Success(ctx.Tr("auth.account_activated"))
  1030. ctx.Redirect(setting.AppSubURL + "/")
  1031. return
  1032. }
  1033. ctx.Data["IsActivateFailed"] = true
  1034. ctx.HTML(200, TplActivate)
  1035. }
  1036. // ActivateEmail render the activate email page
  1037. func ActivateEmail(ctx *context.Context) {
  1038. code := ctx.Query("code")
  1039. emailStr := ctx.Query("email")
  1040. // Verify code.
  1041. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  1042. if err := email.Activate(); err != nil {
  1043. ctx.ServerError("ActivateEmail", err)
  1044. }
  1045. log.Trace("Email activated: %s", email.Email)
  1046. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  1047. }
  1048. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  1049. }
  1050. // ForgotPasswd render the forget pasword page
  1051. func ForgotPasswd(ctx *context.Context) {
  1052. ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
  1053. if setting.MailService == nil {
  1054. ctx.Data["IsResetDisable"] = true
  1055. ctx.HTML(200, tplForgotPassword)
  1056. return
  1057. }
  1058. email := ctx.Query("email")
  1059. ctx.Data["Email"] = email
  1060. ctx.Data["IsResetRequest"] = true
  1061. ctx.HTML(200, tplForgotPassword)
  1062. }
  1063. // ForgotPasswdPost response for forget password request
  1064. func ForgotPasswdPost(ctx *context.Context) {
  1065. ctx.Data["Title"] = ctx.Tr("auth.forgot_password_title")
  1066. if setting.MailService == nil {
  1067. ctx.NotFound("ForgotPasswdPost", nil)
  1068. return
  1069. }
  1070. ctx.Data["IsResetRequest"] = true
  1071. email := ctx.Query("email")
  1072. ctx.Data["Email"] = email
  1073. u, err := models.GetUserByEmail(email)
  1074. if err != nil {
  1075. if models.IsErrUserNotExist(err) {
  1076. ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
  1077. ctx.Data["IsResetSent"] = true
  1078. ctx.HTML(200, tplForgotPassword)
  1079. return
  1080. }
  1081. ctx.ServerError("user.ResetPasswd(check existence)", err)
  1082. return
  1083. }
  1084. if !u.IsLocal() && !u.IsOAuth2() {
  1085. ctx.Data["Err_Email"] = true
  1086. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  1087. return
  1088. }
  1089. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  1090. ctx.Data["ResendLimited"] = true
  1091. ctx.HTML(200, tplForgotPassword)
  1092. return
  1093. }
  1094. mailer.SendResetPasswordMail(ctx.Locale, u)
  1095. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  1096. log.Error("Set cache(MailResendLimit) fail: %v", err)
  1097. }
  1098. ctx.Data["ResetPwdCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, ctx.Locale.Language())
  1099. ctx.Data["IsResetSent"] = true
  1100. ctx.HTML(200, tplForgotPassword)
  1101. }
  1102. func commonResetPassword(ctx *context.Context) *models.User {
  1103. code := ctx.Query("code")
  1104. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  1105. ctx.Data["Code"] = code
  1106. if nil != ctx.User {
  1107. ctx.Data["user_signed_in"] = true
  1108. }
  1109. if len(code) == 0 {
  1110. ctx.Flash.Error(ctx.Tr("auth.invalid_code"))
  1111. return nil
  1112. }
  1113. // Fail early, don't frustrate the user
  1114. u := models.VerifyUserActiveCode(code)
  1115. if u == nil {
  1116. ctx.Flash.Error(ctx.Tr("auth.invalid_code"))
  1117. return nil
  1118. }
  1119. // Show the user that they are affecting the account that they intended to
  1120. ctx.Data["user_email"] = u.Email
  1121. if nil != ctx.User && u.ID != ctx.User.ID {
  1122. ctx.Flash.Error(ctx.Tr("auth.reset_password_wrong_user", ctx.User.Email, u.Email))
  1123. return nil
  1124. }
  1125. return u
  1126. }
  1127. // ResetPasswd render the account recovery page
  1128. func ResetPasswd(ctx *context.Context) {
  1129. ctx.Data["IsResetForm"] = true
  1130. commonResetPassword(ctx)
  1131. ctx.HTML(200, tplResetPassword)
  1132. }
  1133. // ResetPasswdPost response from account recovery request
  1134. func ResetPasswdPost(ctx *context.Context) {
  1135. u := commonResetPassword(ctx)
  1136. if u == nil {
  1137. // Flash error has been set
  1138. ctx.HTML(200, tplResetPassword)
  1139. return
  1140. }
  1141. // Validate password length.
  1142. passwd := ctx.Query("password")
  1143. if len(passwd) < setting.MinPasswordLength {
  1144. ctx.Data["IsResetForm"] = true
  1145. ctx.Data["Err_Password"] = true
  1146. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil)
  1147. return
  1148. } else if !password.IsComplexEnough(passwd) {
  1149. ctx.Data["IsResetForm"] = true
  1150. ctx.Data["Err_Password"] = true
  1151. ctx.RenderWithErr(ctx.Tr("form.password_complexity"), tplResetPassword, nil)
  1152. return
  1153. }
  1154. var err error
  1155. if u.Rands, err = models.GetUserSalt(); err != nil {
  1156. ctx.ServerError("UpdateUser", err)
  1157. return
  1158. }
  1159. if u.Salt, err = models.GetUserSalt(); err != nil {
  1160. ctx.ServerError("UpdateUser", err)
  1161. return
  1162. }
  1163. u.HashPassword(passwd)
  1164. u.MustChangePassword = false
  1165. if err := models.UpdateUserCols(u, "must_change_password", "passwd", "rands", "salt"); err != nil {
  1166. ctx.ServerError("UpdateUser", err)
  1167. return
  1168. }
  1169. log.Trace("User password reset: %s", u.Name)
  1170. ctx.Data["IsResetFailed"] = true
  1171. remember := len(ctx.Query("remember")) != 0
  1172. handleSignInFull(ctx, u, remember, true)
  1173. }
  1174. // MustChangePassword renders the page to change a user's password
  1175. func MustChangePassword(ctx *context.Context) {
  1176. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  1177. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password"
  1178. ctx.HTML(200, tplMustChangePassword)
  1179. }
  1180. // MustChangePasswordPost response for updating a user's password after his/her
  1181. // account was created by an admin
  1182. func MustChangePasswordPost(ctx *context.Context, cpt *captcha.Captcha, form auth.MustChangePasswordForm) {
  1183. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  1184. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/settings/change_password"
  1185. if ctx.HasError() {
  1186. ctx.HTML(200, tplMustChangePassword)
  1187. return
  1188. }
  1189. u := ctx.User
  1190. // Make sure only requests for users who are eligible to change their password via
  1191. // this method passes through
  1192. if !u.MustChangePassword {
  1193. ctx.ServerError("MustUpdatePassword", errors.New("cannot update password.. Please visit the settings page"))
  1194. return
  1195. }
  1196. if form.Password != form.Retype {
  1197. ctx.Data["Err_Password"] = true
  1198. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplMustChangePassword, &form)
  1199. return
  1200. }
  1201. if len(form.Password) < setting.MinPasswordLength {
  1202. ctx.Data["Err_Password"] = true
  1203. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplMustChangePassword, &form)
  1204. return
  1205. }
  1206. var err error
  1207. if u.Salt, err = models.GetUserSalt(); err != nil {
  1208. ctx.ServerError("UpdateUser", err)
  1209. return
  1210. }
  1211. u.HashPassword(form.Password)
  1212. u.MustChangePassword = false
  1213. if err := models.UpdateUserCols(u, "must_change_password", "passwd", "salt"); err != nil {
  1214. ctx.ServerError("UpdateUser", err)
  1215. return
  1216. }
  1217. ctx.Flash.Success(ctx.Tr("settings.change_password_success"))
  1218. log.Trace("User updated password: %s", u.Name)
  1219. if redirectTo := ctx.GetCookie("redirect_to"); len(redirectTo) > 0 && !util.IsExternalURL(redirectTo) {
  1220. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  1221. ctx.RedirectToFirst(redirectTo)
  1222. return
  1223. }
  1224. ctx.Redirect(setting.AppSubURL + "/")
  1225. }
上海开阖软件有限公司 沪ICP备12045867号-1