auth.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package user
  7. import (
  8. "fmt"
  9. "gitote/gitote/models"
  10. "gitote/gitote/models/errors"
  11. "gitote/gitote/pkg/context"
  12. "gitote/gitote/pkg/form"
  13. "gitote/gitote/pkg/mailer"
  14. "gitote/gitote/pkg/setting"
  15. "gitote/gitote/pkg/tool"
  16. "net/url"
  17. raven "github.com/getsentry/raven-go"
  18. "github.com/go-macaron/captcha"
  19. log "gopkg.in/clog.v1"
  20. )
  21. const (
  22. // LoginTPL page template
  23. LoginTPL = "user/auth/login"
  24. // TwoFactorTPL page template
  25. TwoFactorTPL = "user/auth/two_factor"
  26. // TwoFactorRecoveryCodeTPL page template
  27. TwoFactorRecoveryCodeTPL = "user/auth/two_factor_recovery_code"
  28. // SignupTPL page template
  29. SignupTPL = "user/auth/signup"
  30. // ActivateTPL page template
  31. ActivateTPL = "user/auth/activate"
  32. // ForgotPasswordTPL page template
  33. ForgotPasswordTPL = "user/auth/forgot_passwd"
  34. // ResetPasswordTPL page template
  35. ResetPasswordTPL = "user/auth/reset_passwd"
  36. )
  37. // AutoLogin reads cookie and try to auto-login.
  38. func AutoLogin(c *context.Context) (bool, error) {
  39. if !models.HasEngine {
  40. return false, nil
  41. }
  42. uname := c.GetCookie(setting.CookieUserName)
  43. if len(uname) == 0 {
  44. return false, nil
  45. }
  46. isSucceed := false
  47. defer func() {
  48. if !isSucceed {
  49. log.Trace("auto-login cookie cleared: %s", uname)
  50. c.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  51. c.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  52. c.SetCookie(setting.LoginStatusCookieName, "", -1, setting.AppSubURL)
  53. }
  54. }()
  55. u, err := models.GetUserByName(uname)
  56. if err != nil {
  57. if !errors.IsUserNotExist(err) {
  58. return false, fmt.Errorf("GetUserByName: %v", err)
  59. }
  60. return false, nil
  61. }
  62. if val, ok := c.GetSuperSecureCookie(u.Rands+u.Passwd, setting.CookieRememberName); !ok || val != u.Name {
  63. return false, nil
  64. }
  65. isSucceed = true
  66. c.Session.Set("uid", u.ID)
  67. c.Session.Set("uname", u.Name)
  68. c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  69. if setting.EnableLoginStatusCookie {
  70. c.SetCookie(setting.LoginStatusCookieName, "true", 0, setting.AppSubURL)
  71. }
  72. return true, nil
  73. }
  74. //Login is the handler for "/login"
  75. func Login(c *context.Context) {
  76. c.Title("sign_in")
  77. // Check auto-login
  78. isSucceed, err := AutoLogin(c)
  79. if err != nil {
  80. c.ServerError("AutoLogin", err)
  81. return
  82. }
  83. redirectTo := c.Query("redirect_to")
  84. if len(redirectTo) > 0 {
  85. c.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL)
  86. } else {
  87. redirectTo, _ = url.QueryUnescape(c.GetCookie("redirect_to"))
  88. }
  89. if isSucceed {
  90. if tool.IsSameSiteURLPath(redirectTo) {
  91. c.Redirect(redirectTo)
  92. } else {
  93. c.SubURLRedirect("/")
  94. }
  95. c.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  96. return
  97. }
  98. // Display normal login page
  99. loginSources, err := models.ActivatedLoginSources()
  100. if err != nil {
  101. c.ServerError("ActivatedLoginSources", err)
  102. return
  103. }
  104. c.Data["LoginSources"] = loginSources
  105. for i := range loginSources {
  106. if loginSources[i].IsDefault {
  107. c.Data["DefaultSource"] = *loginSources[i]
  108. c.Data["login_source"] = loginSources[i].ID
  109. newLoginSources := append(loginSources[:i], loginSources[i+1:]...)
  110. c.Data["LoginSources"] = newLoginSources
  111. break
  112. }
  113. }
  114. c.Success(LoginTPL)
  115. }
  116. //afterLogin set sessions cookies and redirect to "/"
  117. func afterLogin(c *context.Context, u *models.User, remember bool) {
  118. if remember {
  119. days := 86400 * setting.LoginRememberDays
  120. c.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL, "", setting.CookieSecure, true)
  121. c.SetSuperSecureCookie(u.Rands+u.Passwd, setting.CookieRememberName, u.Name, days, setting.AppSubURL, "", setting.CookieSecure, true)
  122. }
  123. c.Session.Set("uid", u.ID)
  124. c.Session.Set("uname", u.Name)
  125. c.Session.Delete("twoFactorRemember")
  126. c.Session.Delete("twoFactorUserID")
  127. // Clear whatever CSRF has right now, force to generate a new one
  128. c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  129. if setting.EnableLoginStatusCookie {
  130. c.SetCookie(setting.LoginStatusCookieName, "true", 0, setting.AppSubURL)
  131. }
  132. redirectTo, _ := url.QueryUnescape(c.GetCookie("redirect_to"))
  133. c.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  134. if tool.IsSameSiteURLPath(redirectTo) {
  135. c.Redirect(redirectTo)
  136. return
  137. }
  138. c.SubURLRedirect("/")
  139. }
  140. //LoginPost is the POST handler for "/login"
  141. func LoginPost(c *context.Context, f form.SignIn) {
  142. c.Title("sign_in")
  143. loginSources, err := models.ActivatedLoginSources()
  144. if err != nil {
  145. c.ServerError("ActivatedLoginSources", err)
  146. return
  147. }
  148. c.Data["LoginSources"] = loginSources
  149. if c.HasError() {
  150. c.Success(LoginTPL)
  151. return
  152. }
  153. u, err := models.UserLogin(f.UserName, f.Password, f.LoginSource)
  154. if err != nil {
  155. switch err.(type) {
  156. case errors.UserNotExist:
  157. c.FormErr("UserName", "Password")
  158. c.RenderWithErr(c.Tr("form.username_password_incorrect"), LoginTPL, &f)
  159. case errors.LoginSourceMismatch:
  160. c.FormErr("LoginSource")
  161. c.RenderWithErr(c.Tr("form.auth_source_mismatch"), LoginTPL, &f)
  162. default:
  163. c.ServerError("UserLogin", err)
  164. }
  165. for i := range loginSources {
  166. if loginSources[i].IsDefault {
  167. c.Data["DefaultSource"] = *loginSources[i]
  168. c.Data["login_source"] = loginSources[i].ID
  169. newLoginSources := append(loginSources[:i], loginSources[i+1:]...)
  170. c.Data["LoginSources"] = newLoginSources
  171. break
  172. }
  173. }
  174. return
  175. }
  176. if !u.IsEnabledTwoFactor() {
  177. afterLogin(c, u, f.Remember)
  178. return
  179. }
  180. c.Session.Set("twoFactorRemember", f.Remember)
  181. c.Session.Set("twoFactorUserID", u.ID)
  182. c.SubURLRedirect("/login/two_factor")
  183. }
  184. //LoginTwoFactor is the handler for "/login" with two factors authentication
  185. func LoginTwoFactor(c *context.Context) {
  186. _, ok := c.Session.Get("twoFactorUserID").(int64)
  187. if !ok {
  188. c.NotFound()
  189. return
  190. }
  191. c.Success(TwoFactorTPL)
  192. }
  193. //LoginTwoFactorPost is the POST handler for "/login" with two factors authentication
  194. func LoginTwoFactorPost(c *context.Context) {
  195. userID, ok := c.Session.Get("twoFactorUserID").(int64)
  196. if !ok {
  197. c.NotFound()
  198. return
  199. }
  200. t, err := models.GetTwoFactorByUserID(userID)
  201. if err != nil {
  202. c.ServerError("GetTwoFactorByUserID", err)
  203. return
  204. }
  205. passcode := c.Query("passcode")
  206. valid, err := t.ValidateTOTP(passcode)
  207. if err != nil {
  208. c.ServerError("ValidateTOTP", err)
  209. return
  210. } else if !valid {
  211. c.Flash.Error(c.Tr("settings.two_factor_invalid_passcode"))
  212. c.SubURLRedirect("/login/two_factor")
  213. return
  214. }
  215. u, err := models.GetUserByID(userID)
  216. if err != nil {
  217. c.ServerError("GetUserByID", err)
  218. return
  219. }
  220. // Prevent same passcode from being reused
  221. if c.Cache.IsExist(u.TwoFactorCacheKey(passcode)) {
  222. c.Flash.Error(c.Tr("settings.two_factor_reused_passcode"))
  223. c.SubURLRedirect("/login/two_factor")
  224. return
  225. }
  226. if err = c.Cache.Put(u.TwoFactorCacheKey(passcode), 1, 60); err != nil {
  227. raven.CaptureErrorAndWait(err, nil)
  228. log.Error(2, "Failed to put cache 'two factor passcode': %v", err)
  229. }
  230. afterLogin(c, u, c.Session.Get("twoFactorRemember").(bool))
  231. }
  232. //LoginTwoFactorRecoveryCode is the handler to recover Two Factor Code
  233. func LoginTwoFactorRecoveryCode(c *context.Context) {
  234. _, ok := c.Session.Get("twoFactorUserID").(int64)
  235. if !ok {
  236. c.NotFound()
  237. return
  238. }
  239. c.Success(TwoFactorRecoveryCodeTPL)
  240. }
  241. //LoginTwoFactorRecoveryCodePost is the POST handler to recover Two Factor Code
  242. func LoginTwoFactorRecoveryCodePost(c *context.Context) {
  243. userID, ok := c.Session.Get("twoFactorUserID").(int64)
  244. if !ok {
  245. c.NotFound()
  246. return
  247. }
  248. if err := models.UseRecoveryCode(userID, c.Query("recovery_code")); err != nil {
  249. if errors.IsTwoFactorRecoveryCodeNotFound(err) {
  250. c.Flash.Error(c.Tr("auth.login_two_factor_invalid_recovery_code"))
  251. c.SubURLRedirect("/login/two_factor_recovery_code")
  252. } else {
  253. c.ServerError("UseRecoveryCode", err)
  254. }
  255. return
  256. }
  257. u, err := models.GetUserByID(userID)
  258. if err != nil {
  259. c.ServerError("GetUserByID", err)
  260. return
  261. }
  262. afterLogin(c, u, c.Session.Get("twoFactorRemember").(bool))
  263. }
  264. //SignOut is the handler for "/user/logout"
  265. func SignOut(c *context.Context) {
  266. c.Session.Flush()
  267. c.Session.Destory(c.Context)
  268. c.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  269. c.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  270. c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  271. c.SubURLRedirect("/")
  272. }
  273. //SignUp is the handler for "/signup"
  274. func SignUp(c *context.Context) {
  275. c.Title("sign_up")
  276. c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  277. if setting.Service.DisableRegistration {
  278. c.Data["DisableRegistration"] = true
  279. c.Success(SignupTPL)
  280. return
  281. }
  282. c.Success(SignupTPL)
  283. }
  284. //SignUpPost is the POST handler for "/join"
  285. func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
  286. c.Title("sign_up")
  287. c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  288. if setting.Service.DisableRegistration {
  289. c.Status(403)
  290. return
  291. }
  292. if c.HasError() {
  293. c.Success(SignupTPL)
  294. return
  295. }
  296. if setting.Service.EnableCaptcha && !cpt.VerifyReq(c.Req) {
  297. c.FormErr("Captcha")
  298. c.RenderWithErr(c.Tr("form.captcha_incorrect"), SignupTPL, &f)
  299. return
  300. }
  301. if f.Password != f.Retype {
  302. c.FormErr("Password")
  303. c.RenderWithErr(c.Tr("form.password_not_match"), SignupTPL, &f)
  304. return
  305. }
  306. u := &models.User{
  307. Name: f.UserName,
  308. Email: f.Email,
  309. Passwd: f.Password,
  310. ThemeColor: "#161616",
  311. IsActive: !setting.Service.RegisterEmailConfirm,
  312. }
  313. if err := models.CreateUser(u); err != nil {
  314. switch {
  315. case models.IsErrUserAlreadyExist(err):
  316. c.FormErr("UserName")
  317. c.RenderWithErr(c.Tr("form.username_been_taken"), SignupTPL, &f)
  318. case models.IsErrEmailAlreadyUsed(err):
  319. c.FormErr("Email")
  320. c.RenderWithErr(c.Tr("form.email_been_used"), SignupTPL, &f)
  321. case models.IsErrNameReserved(err):
  322. c.FormErr("UserName")
  323. c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SignupTPL, &f)
  324. case models.IsErrNamePatternNotAllowed(err):
  325. c.FormErr("UserName")
  326. c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SignupTPL, &f)
  327. default:
  328. c.ServerError("CreateUser", err)
  329. }
  330. return
  331. }
  332. log.Trace("Account created: %s", u.Name)
  333. // Auto-set admin for the only user.
  334. if models.CountUsers() == 1 {
  335. u.IsAdmin = true
  336. u.IsActive = true
  337. if err := models.UpdateUser(u); err != nil {
  338. c.ServerError("UpdateUser", err)
  339. return
  340. }
  341. }
  342. // Auto Follow the first user
  343. models.FollowUser(u.ID, 1)
  344. // Send confirmation email, no need for social account.
  345. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  346. mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(u))
  347. c.Data["IsSendRegisterMail"] = true
  348. c.Data["Email"] = u.Email
  349. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  350. c.Success(ActivateTPL)
  351. if err := c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
  352. raven.CaptureErrorAndWait(err, nil)
  353. log.Error(2, "Failed to put cache key 'mail resend': %v", err)
  354. }
  355. return
  356. }
  357. c.SubURLRedirect("/login")
  358. }
  359. //Activate activates the code
  360. func Activate(c *context.Context) {
  361. code := c.Query("code")
  362. if len(code) == 0 {
  363. c.Data["IsActivatePage"] = true
  364. if c.User.IsActive {
  365. c.NotFound()
  366. return
  367. }
  368. // Resend confirmation email.
  369. if setting.Service.RegisterEmailConfirm {
  370. if c.Cache.IsExist(c.User.MailResendCacheKey()) {
  371. c.Data["ResendLimited"] = true
  372. } else {
  373. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  374. mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(c.User))
  375. if err := c.Cache.Put(c.User.MailResendCacheKey(), 1, 180); err != nil {
  376. raven.CaptureErrorAndWait(err, nil)
  377. log.Error(2, "Failed to put cache key 'mail resend': %v", err)
  378. }
  379. }
  380. } else {
  381. c.Data["ServiceNotEnabled"] = true
  382. }
  383. c.Success(ActivateTPL)
  384. return
  385. }
  386. // Verify code.
  387. if user := models.VerifyUserActiveCode(code); user != nil {
  388. user.IsActive = true
  389. var err error
  390. if user.Rands, err = models.GetUserSalt(); err != nil {
  391. c.ServerError("GetUserSalt", err)
  392. return
  393. }
  394. if err := models.UpdateUser(user); err != nil {
  395. c.ServerError("UpdateUser", err)
  396. return
  397. }
  398. log.Trace("User activated: %s", user.Name)
  399. c.Session.Set("uid", user.ID)
  400. c.Session.Set("uname", user.Name)
  401. c.SubURLRedirect("/")
  402. return
  403. }
  404. c.Data["IsActivateFailed"] = true
  405. c.Success(ActivateTPL)
  406. }
  407. //ActivateEmail is the handler to activate the user email
  408. func ActivateEmail(c *context.Context) {
  409. code := c.Query("code")
  410. emailString := c.Query("email")
  411. // Verify code.
  412. if email := models.VerifyActiveEmailCode(code, emailString); email != nil {
  413. if err := email.Activate(); err != nil {
  414. c.ServerError("ActivateEmail", err)
  415. }
  416. log.Trace("Email activated: %s", email.Email)
  417. c.Flash.Success(c.Tr("settings.add_email_success"))
  418. }
  419. c.SubURLRedirect("/user/settings/email")
  420. return
  421. }
  422. //ForgotPasswd is the handler for "/user/forget_password"
  423. func ForgotPasswd(c *context.Context) {
  424. c.Title("auth.forgot_password")
  425. if setting.MailService == nil {
  426. c.Data["IsResetDisable"] = true
  427. c.Success(ForgotPasswordTPL)
  428. return
  429. }
  430. c.Data["IsResetRequest"] = true
  431. c.Success(ForgotPasswordTPL)
  432. }
  433. //ForgotPasswdPost is the POST handler for "/user/forget_password"
  434. func ForgotPasswdPost(c *context.Context) {
  435. c.Title("auth.forgot_password")
  436. if setting.MailService == nil {
  437. c.Status(403)
  438. return
  439. }
  440. c.Data["IsResetRequest"] = true
  441. email := c.Query("email")
  442. c.Data["Email"] = email
  443. u, err := models.GetUserByEmail(email)
  444. if err != nil {
  445. if errors.IsUserNotExist(err) {
  446. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  447. c.Data["IsResetSent"] = true
  448. c.Success(ForgotPasswordTPL)
  449. return
  450. }
  451. c.ServerError("GetUserByEmail", err)
  452. return
  453. }
  454. if !u.IsLocal() {
  455. c.FormErr("Email")
  456. c.RenderWithErr(c.Tr("auth.non_local_account"), ForgotPasswordTPL, nil)
  457. return
  458. }
  459. if c.Cache.IsExist(u.MailResendCacheKey()) {
  460. c.Data["ResendLimited"] = true
  461. c.Success(ForgotPasswordTPL)
  462. return
  463. }
  464. mailer.SendResetPasswordMail(c.Context, models.NewMailerUser(u))
  465. if err = c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
  466. raven.CaptureErrorAndWait(err, nil)
  467. log.Error(2, "Failed to put cache key 'mail resend': %v", err)
  468. }
  469. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  470. c.Data["IsResetSent"] = true
  471. c.Success(ForgotPasswordTPL)
  472. }
  473. //ResetPasswd is the handler to reset your password
  474. func ResetPasswd(c *context.Context) {
  475. c.Title("auth.reset_password")
  476. code := c.Query("code")
  477. if len(code) == 0 {
  478. c.NotFound()
  479. return
  480. }
  481. c.Data["Code"] = code
  482. c.Data["IsResetForm"] = true
  483. c.Success(ResetPasswordTPL)
  484. }
  485. //ResetPasswdPost is the POST handler to reset your password
  486. func ResetPasswdPost(c *context.Context) {
  487. c.Title("auth.reset_password")
  488. code := c.Query("code")
  489. if len(code) == 0 {
  490. c.NotFound()
  491. return
  492. }
  493. c.Data["Code"] = code
  494. if u := models.VerifyUserActiveCode(code); u != nil {
  495. // Validate password length.
  496. passwd := c.Query("password")
  497. if len(passwd) < 6 {
  498. c.Data["IsResetForm"] = true
  499. c.Data["Err_Password"] = true
  500. c.RenderWithErr(c.Tr("auth.password_too_short"), ResetPasswordTPL, nil)
  501. return
  502. }
  503. u.Passwd = passwd
  504. var err error
  505. if u.Rands, err = models.GetUserSalt(); err != nil {
  506. c.ServerError("GetUserSalt", err)
  507. return
  508. }
  509. if u.Salt, err = models.GetUserSalt(); err != nil {
  510. c.ServerError("GetUserSalt", err)
  511. return
  512. }
  513. u.EncodePasswd()
  514. if err := models.UpdateUser(u); err != nil {
  515. c.ServerError("UpdateUser", err)
  516. return
  517. }
  518. log.Trace("User password reset: %s", u.Name)
  519. c.SubURLRedirect("/login")
  520. return
  521. }
  522. c.Data["IsResetFailed"] = true
  523. c.Success(ResetPasswordTPL)
  524. }