auth.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 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. ShowAds: true,
  312. IsActive: !setting.Service.RegisterEmailConfirm,
  313. }
  314. if err := models.CreateUser(u); err != nil {
  315. switch {
  316. case models.IsErrUserAlreadyExist(err):
  317. c.FormErr("UserName")
  318. c.RenderWithErr(c.Tr("form.username_been_taken"), SignupTPL, &f)
  319. case models.IsErrEmailAlreadyUsed(err):
  320. c.FormErr("Email")
  321. c.RenderWithErr(c.Tr("form.email_been_used"), SignupTPL, &f)
  322. case models.IsErrNameReserved(err):
  323. c.FormErr("UserName")
  324. c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SignupTPL, &f)
  325. case models.IsErrNamePatternNotAllowed(err):
  326. c.FormErr("UserName")
  327. c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SignupTPL, &f)
  328. default:
  329. c.ServerError("CreateUser", err)
  330. }
  331. return
  332. }
  333. log.Trace("Account created: %s", u.Name)
  334. // Auto-set admin for the only user.
  335. if models.CountUsers() == 1 {
  336. u.IsAdmin = true
  337. u.IsActive = true
  338. if err := models.UpdateUser(u); err != nil {
  339. c.ServerError("UpdateUser", err)
  340. return
  341. }
  342. }
  343. // Auto Follow the first user
  344. models.FollowUser(u.ID, 1)
  345. // Send confirmation email, no need for social account.
  346. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  347. mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(u))
  348. c.Data["IsSendRegisterMail"] = true
  349. c.Data["Email"] = u.Email
  350. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  351. c.Success(ActivateTPL)
  352. if err := c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
  353. raven.CaptureErrorAndWait(err, nil)
  354. log.Error(2, "Failed to put cache key 'mail resend': %v", err)
  355. }
  356. return
  357. }
  358. c.SubURLRedirect("/login")
  359. }
  360. //Activate activates the code
  361. func Activate(c *context.Context) {
  362. code := c.Query("code")
  363. if len(code) == 0 {
  364. c.Data["IsActivatePage"] = true
  365. if c.User.IsActive {
  366. c.NotFound()
  367. return
  368. }
  369. // Resend confirmation email.
  370. if setting.Service.RegisterEmailConfirm {
  371. if c.Cache.IsExist(c.User.MailResendCacheKey()) {
  372. c.Data["ResendLimited"] = true
  373. } else {
  374. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  375. mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(c.User))
  376. if err := c.Cache.Put(c.User.MailResendCacheKey(), 1, 180); err != nil {
  377. raven.CaptureErrorAndWait(err, nil)
  378. log.Error(2, "Failed to put cache key 'mail resend': %v", err)
  379. }
  380. }
  381. } else {
  382. c.Data["ServiceNotEnabled"] = true
  383. }
  384. c.Success(ActivateTPL)
  385. return
  386. }
  387. // Verify code.
  388. if user := models.VerifyUserActiveCode(code); user != nil {
  389. user.IsActive = true
  390. var err error
  391. if user.Rands, err = models.GetUserSalt(); err != nil {
  392. c.ServerError("GetUserSalt", err)
  393. return
  394. }
  395. if err := models.UpdateUser(user); err != nil {
  396. c.ServerError("UpdateUser", err)
  397. return
  398. }
  399. log.Trace("User activated: %s", user.Name)
  400. c.Session.Set("uid", user.ID)
  401. c.Session.Set("uname", user.Name)
  402. c.SubURLRedirect("/")
  403. return
  404. }
  405. c.Data["IsActivateFailed"] = true
  406. c.Success(ActivateTPL)
  407. }
  408. //ActivateEmail is the handler to activate the user email
  409. func ActivateEmail(c *context.Context) {
  410. code := c.Query("code")
  411. email_string := c.Query("email")
  412. // Verify code.
  413. if email := models.VerifyActiveEmailCode(code, email_string); email != nil {
  414. if err := email.Activate(); err != nil {
  415. c.ServerError("ActivateEmail", err)
  416. }
  417. log.Trace("Email activated: %s", email.Email)
  418. c.Flash.Success(c.Tr("settings.add_email_success"))
  419. }
  420. c.SubURLRedirect("/user/settings/email")
  421. return
  422. }
  423. //ForgotPasswd is the handler for "/user/forget_password"
  424. func ForgotPasswd(c *context.Context) {
  425. c.Title("auth.forgot_password")
  426. if setting.MailService == nil {
  427. c.Data["IsResetDisable"] = true
  428. c.Success(ForgotPasswordTPL)
  429. return
  430. }
  431. c.Data["IsResetRequest"] = true
  432. c.Success(ForgotPasswordTPL)
  433. }
  434. //ForgotPasswdPost is the POST handler for "/user/forget_password"
  435. func ForgotPasswdPost(c *context.Context) {
  436. c.Title("auth.forgot_password")
  437. if setting.MailService == nil {
  438. c.Status(403)
  439. return
  440. }
  441. c.Data["IsResetRequest"] = true
  442. email := c.Query("email")
  443. c.Data["Email"] = email
  444. u, err := models.GetUserByEmail(email)
  445. if err != nil {
  446. if errors.IsUserNotExist(err) {
  447. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  448. c.Data["IsResetSent"] = true
  449. c.Success(ForgotPasswordTPL)
  450. return
  451. } else {
  452. c.ServerError("GetUserByEmail", err)
  453. }
  454. return
  455. }
  456. if !u.IsLocal() {
  457. c.FormErr("Email")
  458. c.RenderWithErr(c.Tr("auth.non_local_account"), ForgotPasswordTPL, nil)
  459. return
  460. }
  461. if c.Cache.IsExist(u.MailResendCacheKey()) {
  462. c.Data["ResendLimited"] = true
  463. c.Success(ForgotPasswordTPL)
  464. return
  465. }
  466. mailer.SendResetPasswordMail(c.Context, models.NewMailerUser(u))
  467. if err = c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
  468. raven.CaptureErrorAndWait(err, nil)
  469. log.Error(2, "Failed to put cache key 'mail resend': %v", err)
  470. }
  471. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  472. c.Data["IsResetSent"] = true
  473. c.Success(ForgotPasswordTPL)
  474. }
  475. //ResetPasswd is the handler to reset your password
  476. func ResetPasswd(c *context.Context) {
  477. c.Title("auth.reset_password")
  478. code := c.Query("code")
  479. if len(code) == 0 {
  480. c.NotFound()
  481. return
  482. }
  483. c.Data["Code"] = code
  484. c.Data["IsResetForm"] = true
  485. c.Success(ResetPasswordTPL)
  486. }
  487. //ResetPasswdPost is the POST handler to reset your password
  488. func ResetPasswdPost(c *context.Context) {
  489. c.Title("auth.reset_password")
  490. code := c.Query("code")
  491. if len(code) == 0 {
  492. c.NotFound()
  493. return
  494. }
  495. c.Data["Code"] = code
  496. if u := models.VerifyUserActiveCode(code); u != nil {
  497. // Validate password length.
  498. passwd := c.Query("password")
  499. if len(passwd) < 6 {
  500. c.Data["IsResetForm"] = true
  501. c.Data["Err_Password"] = true
  502. c.RenderWithErr(c.Tr("auth.password_too_short"), ResetPasswordTPL, nil)
  503. return
  504. }
  505. u.Passwd = passwd
  506. var err error
  507. if u.Rands, err = models.GetUserSalt(); err != nil {
  508. c.ServerError("GetUserSalt", err)
  509. return
  510. }
  511. if u.Salt, err = models.GetUserSalt(); err != nil {
  512. c.ServerError("GetUserSalt", err)
  513. return
  514. }
  515. u.EncodePasswd()
  516. if err := models.UpdateUser(u); err != nil {
  517. c.ServerError("UpdateUser", err)
  518. return
  519. }
  520. log.Trace("User password reset: %s", u.Name)
  521. c.SubURLRedirect("/login")
  522. return
  523. }
  524. c.Data["IsResetFailed"] = true
  525. c.Success(ResetPasswordTPL)
  526. }