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

623 lines
16 KiB

9 years ago
9 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package user
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. "github.com/go-macaron/captcha"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/auth"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/context"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. )
  17. const (
  18. // tplSignIn template for sign in page
  19. tplSignIn base.TplName = "user/auth/signin"
  20. // tplSignUp template path for sign up page
  21. tplSignUp base.TplName = "user/auth/signup"
  22. // TplActivate template path for activate user
  23. TplActivate base.TplName = "user/auth/activate"
  24. tplForgotPassword base.TplName = "user/auth/forgot_passwd"
  25. tplResetPassword base.TplName = "user/auth/reset_passwd"
  26. tplTwofa base.TplName = "user/auth/twofa"
  27. tplTwofaScratch base.TplName = "user/auth/twofa_scratch"
  28. )
  29. // AutoSignIn reads cookie and try to auto-login.
  30. func AutoSignIn(ctx *context.Context) (bool, error) {
  31. if !models.HasEngine {
  32. return false, nil
  33. }
  34. uname := ctx.GetCookie(setting.CookieUserName)
  35. if len(uname) == 0 {
  36. return false, nil
  37. }
  38. isSucceed := false
  39. defer func() {
  40. if !isSucceed {
  41. log.Trace("auto-login cookie cleared: %s", uname)
  42. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  43. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  44. }
  45. }()
  46. u, err := models.GetUserByName(uname)
  47. if err != nil {
  48. if !models.IsErrUserNotExist(err) {
  49. return false, fmt.Errorf("GetUserByName: %v", err)
  50. }
  51. return false, nil
  52. }
  53. if val, _ := ctx.GetSuperSecureCookie(
  54. base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name {
  55. return false, nil
  56. }
  57. isSucceed = true
  58. ctx.Session.Set("uid", u.ID)
  59. ctx.Session.Set("uname", u.Name)
  60. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  61. return true, nil
  62. }
  63. func checkAutoLogin(ctx *context.Context) bool {
  64. // Check auto-login.
  65. isSucceed, err := AutoSignIn(ctx)
  66. if err != nil {
  67. ctx.Handle(500, "AutoSignIn", err)
  68. return true
  69. }
  70. redirectTo := ctx.Query("redirect_to")
  71. if len(redirectTo) > 0 {
  72. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL)
  73. } else {
  74. redirectTo, _ = url.QueryUnescape(ctx.GetCookie("redirect_to"))
  75. }
  76. if isSucceed {
  77. if len(redirectTo) > 0 {
  78. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  79. ctx.Redirect(redirectTo)
  80. } else {
  81. ctx.Redirect(setting.AppSubURL + "/")
  82. }
  83. return true
  84. }
  85. return false
  86. }
  87. // SignIn render sign in page
  88. func SignIn(ctx *context.Context) {
  89. ctx.Data["Title"] = ctx.Tr("sign_in")
  90. // Check auto-login.
  91. if checkAutoLogin(ctx) {
  92. return
  93. }
  94. ctx.HTML(200, tplSignIn)
  95. }
  96. // SignInPost response for sign in request
  97. func SignInPost(ctx *context.Context, form auth.SignInForm) {
  98. ctx.Data["Title"] = ctx.Tr("sign_in")
  99. if ctx.HasError() {
  100. ctx.HTML(200, tplSignIn)
  101. return
  102. }
  103. u, err := models.UserSignIn(form.UserName, form.Password)
  104. if err != nil {
  105. if models.IsErrUserNotExist(err) {
  106. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form)
  107. } else {
  108. ctx.Handle(500, "UserSignIn", err)
  109. }
  110. return
  111. }
  112. // If this user is enrolled in 2FA, we can't sign the user in just yet.
  113. // Instead, redirect them to the 2FA authentication page.
  114. _, err = models.GetTwoFactorByUID(u.ID)
  115. if err != nil {
  116. if models.IsErrTwoFactorNotEnrolled(err) {
  117. handleSignIn(ctx, u, form.Remember)
  118. } else {
  119. ctx.Handle(500, "UserSignIn", err)
  120. }
  121. return
  122. }
  123. // User needs to use 2FA, save data and redirect to 2FA page.
  124. ctx.Session.Set("twofaUid", u.ID)
  125. ctx.Session.Set("twofaRemember", form.Remember)
  126. ctx.Redirect(setting.AppSubURL + "/user/two_factor")
  127. }
  128. // TwoFactor shows the user a two-factor authentication page.
  129. func TwoFactor(ctx *context.Context) {
  130. ctx.Data["Title"] = ctx.Tr("twofa")
  131. // Check auto-login.
  132. if checkAutoLogin(ctx) {
  133. return
  134. }
  135. // Ensure user is in a 2FA session.
  136. if ctx.Session.Get("twofaUid") == nil {
  137. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  138. return
  139. }
  140. ctx.HTML(200, tplTwofa)
  141. }
  142. // TwoFactorPost validates a user's two-factor authentication token.
  143. func TwoFactorPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  144. ctx.Data["Title"] = ctx.Tr("twofa")
  145. // Ensure user is in a 2FA session.
  146. idSess := ctx.Session.Get("twofaUid")
  147. if idSess == nil {
  148. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  149. return
  150. }
  151. id := idSess.(int64)
  152. twofa, err := models.GetTwoFactorByUID(id)
  153. if err != nil {
  154. ctx.Handle(500, "UserSignIn", err)
  155. return
  156. }
  157. // Validate the passcode with the stored TOTP secret.
  158. ok, err := twofa.ValidateTOTP(form.Passcode)
  159. if err != nil {
  160. ctx.Handle(500, "UserSignIn", err)
  161. return
  162. }
  163. if ok {
  164. remember := ctx.Session.Get("twofaRemember").(bool)
  165. u, err := models.GetUserByID(id)
  166. if err != nil {
  167. ctx.Handle(500, "UserSignIn", err)
  168. return
  169. }
  170. handleSignIn(ctx, u, remember)
  171. return
  172. }
  173. ctx.RenderWithErr(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, auth.TwoFactorAuthForm{})
  174. }
  175. // TwoFactorScratch shows the scratch code form for two-factor authentication.
  176. func TwoFactorScratch(ctx *context.Context) {
  177. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  178. // Check auto-login.
  179. if checkAutoLogin(ctx) {
  180. return
  181. }
  182. // Ensure user is in a 2FA session.
  183. if ctx.Session.Get("twofaUid") == nil {
  184. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  185. return
  186. }
  187. ctx.HTML(200, tplTwofaScratch)
  188. }
  189. // TwoFactorScratchPost validates and invalidates a user's two-factor scratch token.
  190. func TwoFactorScratchPost(ctx *context.Context, form auth.TwoFactorScratchAuthForm) {
  191. ctx.Data["Title"] = ctx.Tr("twofa_scratch")
  192. // Ensure user is in a 2FA session.
  193. idSess := ctx.Session.Get("twofaUid")
  194. if idSess == nil {
  195. ctx.Handle(500, "UserSignIn", errors.New("not in 2FA session"))
  196. return
  197. }
  198. id := idSess.(int64)
  199. twofa, err := models.GetTwoFactorByUID(id)
  200. if err != nil {
  201. ctx.Handle(500, "UserSignIn", err)
  202. return
  203. }
  204. // Validate the passcode with the stored TOTP secret.
  205. if twofa.VerifyScratchToken(form.Token) {
  206. // Invalidate the scratch token.
  207. twofa.ScratchToken = ""
  208. if err = models.UpdateTwoFactor(twofa); err != nil {
  209. ctx.Handle(500, "UserSignIn", err)
  210. return
  211. }
  212. remember := ctx.Session.Get("twofaRemember").(bool)
  213. u, err := models.GetUserByID(id)
  214. if err != nil {
  215. ctx.Handle(500, "UserSignIn", err)
  216. return
  217. }
  218. handleSignInFull(ctx, u, remember, false)
  219. ctx.Flash.Info(ctx.Tr("auth.twofa_scratch_used"))
  220. ctx.Redirect(setting.AppSubURL + "/user/settings/two_factor")
  221. return
  222. }
  223. ctx.RenderWithErr(ctx.Tr("auth.twofa_scratch_token_incorrect"), tplTwofaScratch, auth.TwoFactorScratchAuthForm{})
  224. }
  225. // This handles the final part of the sign-in process of the user.
  226. func handleSignIn(ctx *context.Context, u *models.User, remember bool) {
  227. handleSignInFull(ctx, u, remember, true)
  228. }
  229. func handleSignInFull(ctx *context.Context, u *models.User, remember bool, obeyRedirect bool) {
  230. if remember {
  231. days := 86400 * setting.LogInRememberDays
  232. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL)
  233. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  234. setting.CookieRememberName, u.Name, days, setting.AppSubURL)
  235. }
  236. ctx.Session.Delete("twofaUid")
  237. ctx.Session.Delete("twofaRemember")
  238. ctx.Session.Set("uid", u.ID)
  239. ctx.Session.Set("uname", u.Name)
  240. // Clear whatever CSRF has right now, force to generate a new one
  241. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  242. // Register last login
  243. u.SetLastLogin()
  244. if err := models.UpdateUser(u); err != nil {
  245. ctx.Handle(500, "UpdateUser", err)
  246. return
  247. }
  248. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  249. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  250. if obeyRedirect {
  251. ctx.Redirect(redirectTo)
  252. }
  253. return
  254. }
  255. if obeyRedirect {
  256. ctx.Redirect(setting.AppSubURL + "/")
  257. }
  258. }
  259. // SignOut sign out from login status
  260. func SignOut(ctx *context.Context) {
  261. ctx.Session.Delete("uid")
  262. ctx.Session.Delete("uname")
  263. ctx.Session.Delete("socialId")
  264. ctx.Session.Delete("socialName")
  265. ctx.Session.Delete("socialEmail")
  266. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  267. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  268. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  269. ctx.Redirect(setting.AppSubURL + "/")
  270. }
  271. // SignUp render the register page
  272. func SignUp(ctx *context.Context) {
  273. ctx.Data["Title"] = ctx.Tr("sign_up")
  274. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  275. if setting.Service.DisableRegistration {
  276. ctx.Data["DisableRegistration"] = true
  277. ctx.HTML(200, tplSignUp)
  278. return
  279. }
  280. ctx.HTML(200, tplSignUp)
  281. }
  282. // SignUpPost response for sign up information submission
  283. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  284. ctx.Data["Title"] = ctx.Tr("sign_up")
  285. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  286. if setting.Service.DisableRegistration {
  287. ctx.Error(403)
  288. return
  289. }
  290. if ctx.HasError() {
  291. ctx.HTML(200, tplSignUp)
  292. return
  293. }
  294. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  295. ctx.Data["Err_Captcha"] = true
  296. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  297. return
  298. }
  299. if form.Password != form.Retype {
  300. ctx.Data["Err_Password"] = true
  301. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  302. return
  303. }
  304. if len(form.Password) < setting.MinPasswordLength {
  305. ctx.Data["Err_Password"] = true
  306. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
  307. return
  308. }
  309. u := &models.User{
  310. Name: form.UserName,
  311. Email: form.Email,
  312. Passwd: form.Password,
  313. IsActive: !setting.Service.RegisterEmailConfirm,
  314. }
  315. if err := models.CreateUser(u); err != nil {
  316. switch {
  317. case models.IsErrUserAlreadyExist(err):
  318. ctx.Data["Err_UserName"] = true
  319. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  320. case models.IsErrEmailAlreadyUsed(err):
  321. ctx.Data["Err_Email"] = true
  322. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  323. case models.IsErrNameReserved(err):
  324. ctx.Data["Err_UserName"] = true
  325. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  326. case models.IsErrNamePatternNotAllowed(err):
  327. ctx.Data["Err_UserName"] = true
  328. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  329. default:
  330. ctx.Handle(500, "CreateUser", err)
  331. }
  332. return
  333. }
  334. log.Trace("Account created: %s", u.Name)
  335. // Auto-set admin for the only user.
  336. if models.CountUsers() == 1 {
  337. u.IsAdmin = true
  338. u.IsActive = true
  339. if err := models.UpdateUser(u); err != nil {
  340. ctx.Handle(500, "UpdateUser", err)
  341. return
  342. }
  343. }
  344. // Send confirmation email, no need for social account.
  345. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  346. models.SendActivateAccountMail(ctx.Context, u)
  347. ctx.Data["IsSendRegisterMail"] = true
  348. ctx.Data["Email"] = u.Email
  349. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  350. ctx.HTML(200, TplActivate)
  351. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  352. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  353. }
  354. return
  355. }
  356. ctx.Redirect(setting.AppSubURL + "/user/login")
  357. }
  358. // Activate render activate user page
  359. func Activate(ctx *context.Context) {
  360. code := ctx.Query("code")
  361. if len(code) == 0 {
  362. ctx.Data["IsActivatePage"] = true
  363. if ctx.User.IsActive {
  364. ctx.Error(404)
  365. return
  366. }
  367. // Resend confirmation email.
  368. if setting.Service.RegisterEmailConfirm {
  369. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  370. ctx.Data["ResendLimited"] = true
  371. } else {
  372. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  373. models.SendActivateAccountMail(ctx.Context, ctx.User)
  374. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  375. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  376. }
  377. }
  378. } else {
  379. ctx.Data["ServiceNotEnabled"] = true
  380. }
  381. ctx.HTML(200, TplActivate)
  382. return
  383. }
  384. // Verify code.
  385. if user := models.VerifyUserActiveCode(code); user != nil {
  386. user.IsActive = true
  387. var err error
  388. if user.Rands, err = models.GetUserSalt(); err != nil {
  389. ctx.Handle(500, "UpdateUser", err)
  390. return
  391. }
  392. if err := models.UpdateUser(user); err != nil {
  393. if models.IsErrUserNotExist(err) {
  394. ctx.Error(404)
  395. } else {
  396. ctx.Handle(500, "UpdateUser", err)
  397. }
  398. return
  399. }
  400. log.Trace("User activated: %s", user.Name)
  401. ctx.Session.Set("uid", user.ID)
  402. ctx.Session.Set("uname", user.Name)
  403. ctx.Redirect(setting.AppSubURL + "/")
  404. return
  405. }
  406. ctx.Data["IsActivateFailed"] = true
  407. ctx.HTML(200, TplActivate)
  408. }
  409. // ActivateEmail render the activate email page
  410. func ActivateEmail(ctx *context.Context) {
  411. code := ctx.Query("code")
  412. emailStr := ctx.Query("email")
  413. // Verify code.
  414. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  415. if err := email.Activate(); err != nil {
  416. ctx.Handle(500, "ActivateEmail", err)
  417. }
  418. log.Trace("Email activated: %s", email.Email)
  419. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  420. }
  421. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  422. return
  423. }
  424. // ForgotPasswd render the forget pasword page
  425. func ForgotPasswd(ctx *context.Context) {
  426. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  427. if setting.MailService == nil {
  428. ctx.Data["IsResetDisable"] = true
  429. ctx.HTML(200, tplForgotPassword)
  430. return
  431. }
  432. ctx.Data["IsResetRequest"] = true
  433. ctx.HTML(200, tplForgotPassword)
  434. }
  435. // ForgotPasswdPost response for forget password request
  436. func ForgotPasswdPost(ctx *context.Context) {
  437. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  438. if setting.MailService == nil {
  439. ctx.Handle(403, "ForgotPasswdPost", nil)
  440. return
  441. }
  442. ctx.Data["IsResetRequest"] = true
  443. email := ctx.Query("email")
  444. ctx.Data["Email"] = email
  445. u, err := models.GetUserByEmail(email)
  446. if err != nil {
  447. if models.IsErrUserNotExist(err) {
  448. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  449. ctx.Data["IsResetSent"] = true
  450. ctx.HTML(200, tplForgotPassword)
  451. return
  452. }
  453. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  454. return
  455. }
  456. if !u.IsLocal() {
  457. ctx.Data["Err_Email"] = true
  458. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  459. return
  460. }
  461. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  462. ctx.Data["ResendLimited"] = true
  463. ctx.HTML(200, tplForgotPassword)
  464. return
  465. }
  466. models.SendResetPasswordMail(ctx.Context, u)
  467. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  468. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  469. }
  470. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  471. ctx.Data["IsResetSent"] = true
  472. ctx.HTML(200, tplForgotPassword)
  473. }
  474. // ResetPasswd render the reset password page
  475. func ResetPasswd(ctx *context.Context) {
  476. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  477. code := ctx.Query("code")
  478. if len(code) == 0 {
  479. ctx.Error(404)
  480. return
  481. }
  482. ctx.Data["Code"] = code
  483. ctx.Data["IsResetForm"] = true
  484. ctx.HTML(200, tplResetPassword)
  485. }
  486. // ResetPasswdPost response from reset password request
  487. func ResetPasswdPost(ctx *context.Context) {
  488. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  489. code := ctx.Query("code")
  490. if len(code) == 0 {
  491. ctx.Error(404)
  492. return
  493. }
  494. ctx.Data["Code"] = code
  495. if u := models.VerifyUserActiveCode(code); u != nil {
  496. // Validate password length.
  497. passwd := ctx.Query("password")
  498. if len(passwd) < setting.MinPasswordLength {
  499. ctx.Data["IsResetForm"] = true
  500. ctx.Data["Err_Password"] = true
  501. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil)
  502. return
  503. }
  504. u.Passwd = passwd
  505. var err error
  506. if u.Rands, err = models.GetUserSalt(); err != nil {
  507. ctx.Handle(500, "UpdateUser", err)
  508. return
  509. }
  510. if u.Salt, err = models.GetUserSalt(); err != nil {
  511. ctx.Handle(500, "UpdateUser", err)
  512. return
  513. }
  514. u.EncodePasswd()
  515. if err := models.UpdateUser(u); err != nil {
  516. ctx.Handle(500, "UpdateUser", err)
  517. return
  518. }
  519. log.Trace("User password reset: %s", u.Name)
  520. ctx.Redirect(setting.AppSubURL + "/user/login")
  521. return
  522. }
  523. ctx.Data["IsResetFailed"] = true
  524. ctx.HTML(200, tplResetPassword)
  525. }