auth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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.gogs file.
  4. package user
  5. import (
  6. gocontext "context"
  7. "fmt"
  8. "github.com/go-macaron/captcha"
  9. "net/http"
  10. "net/url"
  11. log "unknwon.dev/clog/v2"
  12. "gogs.io/gogs/internal/auth"
  13. "gogs.io/gogs/internal/conf"
  14. "gogs.io/gogs/internal/context"
  15. "gogs.io/gogs/internal/database"
  16. "gogs.io/gogs/internal/email"
  17. "gogs.io/gogs/internal/form"
  18. "gogs.io/gogs/internal/tool"
  19. "gogs.io/gogs/internal/userutil"
  20. )
  21. const (
  22. LOGIN = "user/auth/login"
  23. TWO_FACTOR = "user/auth/two_factor"
  24. TWO_FACTOR_RECOVERY_CODE = "user/auth/two_factor_recovery_code"
  25. SIGNUP = "user/auth/signup"
  26. ACTIVATE = "user/auth/activate"
  27. FORGOT_PASSWORD = "user/auth/forgot_passwd"
  28. RESET_PASSWORD = "user/auth/reset_passwd"
  29. )
  30. // AutoLogin reads cookie and try to auto-login.
  31. func AutoLogin(c *context.Context) (bool, error) {
  32. if !database.HasEngine {
  33. return false, nil
  34. }
  35. uname := c.GetCookie(conf.Security.CookieUsername)
  36. if uname == "" {
  37. return false, nil
  38. }
  39. isSucceed := false
  40. defer func() {
  41. if !isSucceed {
  42. log.Trace("auto-login cookie cleared: %s", uname)
  43. c.SetCookie(conf.Security.CookieUsername, "", -1, conf.Server.Subpath)
  44. c.SetCookie(conf.Security.CookieRememberName, "", -1, conf.Server.Subpath)
  45. c.SetCookie(conf.Security.LoginStatusCookieName, "", -1, conf.Server.Subpath)
  46. }
  47. }()
  48. u, err := database.Handle.Users().GetByUsername(c.Req.Context(), uname)
  49. if err != nil {
  50. if !database.IsErrUserNotExist(err) {
  51. return false, fmt.Errorf("get user by name: %v", err)
  52. }
  53. return false, nil
  54. }
  55. if val, ok := c.GetSuperSecureCookie(u.Rands+u.Password, conf.Security.CookieRememberName); !ok || val != u.Name {
  56. return false, nil
  57. }
  58. isSucceed = true
  59. _ = c.Session.Set("uid", u.ID)
  60. _ = c.Session.Set("uname", u.Name)
  61. c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
  62. if conf.Security.EnableLoginStatusCookie {
  63. c.SetCookie(conf.Security.LoginStatusCookieName, "true", 0, conf.Server.Subpath)
  64. }
  65. return true, nil
  66. }
  67. func Login(c *context.Context) {
  68. c.Title("sign_in")
  69. // Check auto-login
  70. isSucceed, err := AutoLogin(c)
  71. if err != nil {
  72. c.Error(err, "auto login")
  73. return
  74. }
  75. redirectTo := c.Query("redirect_to")
  76. if len(redirectTo) > 0 {
  77. c.SetCookie("redirect_to", redirectTo, 0, conf.Server.Subpath)
  78. } else {
  79. redirectTo, _ = url.QueryUnescape(c.GetCookie("redirect_to"))
  80. }
  81. if isSucceed {
  82. if tool.IsSameSiteURLPath(redirectTo) {
  83. c.Redirect(redirectTo)
  84. } else {
  85. c.RedirectSubpath("/")
  86. }
  87. c.SetCookie("redirect_to", "", -1, conf.Server.Subpath)
  88. return
  89. }
  90. // Display normal login page
  91. loginSources, err := database.Handle.LoginSources().List(c.Req.Context(), database.ListLoginSourceOptions{OnlyActivated: true})
  92. if err != nil {
  93. c.Error(err, "list activated login sources")
  94. return
  95. }
  96. c.Data["LoginSources"] = loginSources
  97. for i := range loginSources {
  98. if loginSources[i].IsDefault {
  99. c.Data["DefaultLoginSource"] = loginSources[i]
  100. c.Data["login_source"] = loginSources[i].ID
  101. break
  102. }
  103. }
  104. c.Success(LOGIN)
  105. }
  106. func afterLogin(c *context.Context, u *database.User, remember bool) {
  107. if remember {
  108. days := 86400 * conf.Security.LoginRememberDays
  109. c.SetCookie(conf.Security.CookieUsername, u.Name, days, conf.Server.Subpath, "", conf.Security.CookieSecure, true)
  110. c.SetSuperSecureCookie(u.Rands+u.Password, conf.Security.CookieRememberName, u.Name, days, conf.Server.Subpath, "", conf.Security.CookieSecure, true)
  111. }
  112. _ = c.Session.Set("uid", u.ID)
  113. _ = c.Session.Set("uname", u.Name)
  114. _ = c.Session.Delete("twoFactorRemember")
  115. _ = c.Session.Delete("twoFactorUserID")
  116. // Clear whatever CSRF has right now, force to generate a new one
  117. c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
  118. if conf.Security.EnableLoginStatusCookie {
  119. c.SetCookie(conf.Security.LoginStatusCookieName, "true", 0, conf.Server.Subpath)
  120. }
  121. redirectTo, _ := url.QueryUnescape(c.GetCookie("redirect_to"))
  122. c.SetCookie("redirect_to", "", -1, conf.Server.Subpath)
  123. if tool.IsSameSiteURLPath(redirectTo) {
  124. c.Redirect(redirectTo)
  125. return
  126. }
  127. c.RedirectSubpath("/")
  128. }
  129. func LoginPost(c *context.Context, f form.SignIn) {
  130. c.Title("sign_in")
  131. loginSources, err := database.Handle.LoginSources().List(c.Req.Context(), database.ListLoginSourceOptions{OnlyActivated: true})
  132. if err != nil {
  133. c.Error(err, "list activated login sources")
  134. return
  135. }
  136. c.Data["LoginSources"] = loginSources
  137. if c.HasError() {
  138. c.Success(LOGIN)
  139. return
  140. }
  141. u, err := database.Handle.Users().Authenticate(c.Req.Context(), f.UserName, f.Password, f.LoginSource)
  142. if err != nil {
  143. switch {
  144. case auth.IsErrBadCredentials(err):
  145. c.FormErr("UserName", "Password")
  146. c.RenderWithErr(c.Tr("form.username_password_incorrect"), LOGIN, &f)
  147. case database.IsErrLoginSourceMismatch(err):
  148. c.FormErr("LoginSource")
  149. c.RenderWithErr(c.Tr("form.auth_source_mismatch"), LOGIN, &f)
  150. default:
  151. c.Error(err, "authenticate user")
  152. }
  153. for i := range loginSources {
  154. if loginSources[i].IsDefault {
  155. c.Data["DefaultLoginSource"] = loginSources[i]
  156. break
  157. }
  158. }
  159. return
  160. }
  161. if !database.Handle.TwoFactors().IsEnabled(c.Req.Context(), u.ID) {
  162. afterLogin(c, u, f.Remember)
  163. return
  164. }
  165. _ = c.Session.Set("twoFactorRemember", f.Remember)
  166. _ = c.Session.Set("twoFactorUserID", u.ID)
  167. c.RedirectSubpath("/user/login/two_factor")
  168. }
  169. func LoginTwoFactor(c *context.Context) {
  170. _, ok := c.Session.Get("twoFactorUserID").(int64)
  171. if !ok {
  172. c.NotFound()
  173. return
  174. }
  175. c.Success(TWO_FACTOR)
  176. }
  177. func LoginTwoFactorPost(c *context.Context) {
  178. userID, ok := c.Session.Get("twoFactorUserID").(int64)
  179. if !ok {
  180. c.NotFound()
  181. return
  182. }
  183. t, err := database.Handle.TwoFactors().GetByUserID(c.Req.Context(), userID)
  184. if err != nil {
  185. c.Error(err, "get two factor by user ID")
  186. return
  187. }
  188. passcode := c.Query("passcode")
  189. valid, err := t.ValidateTOTP(passcode)
  190. if err != nil {
  191. c.Error(err, "validate TOTP")
  192. return
  193. } else if !valid {
  194. c.Flash.Error(c.Tr("settings.two_factor_invalid_passcode"))
  195. c.RedirectSubpath("/user/login/two_factor")
  196. return
  197. }
  198. u, err := database.Handle.Users().GetByID(c.Req.Context(), userID)
  199. if err != nil {
  200. c.Error(err, "get user by ID")
  201. return
  202. }
  203. // Prevent same passcode from being reused
  204. if c.Cache.IsExist(userutil.TwoFactorCacheKey(u.ID, passcode)) {
  205. c.Flash.Error(c.Tr("settings.two_factor_reused_passcode"))
  206. c.RedirectSubpath("/user/login/two_factor")
  207. return
  208. }
  209. if err = c.Cache.Put(userutil.TwoFactorCacheKey(u.ID, passcode), 1, 60); err != nil {
  210. log.Error("Failed to put cache 'two factor passcode': %v", err)
  211. }
  212. afterLogin(c, u, c.Session.Get("twoFactorRemember").(bool))
  213. }
  214. func LoginTwoFactorRecoveryCode(c *context.Context) {
  215. _, ok := c.Session.Get("twoFactorUserID").(int64)
  216. if !ok {
  217. c.NotFound()
  218. return
  219. }
  220. c.Success(TWO_FACTOR_RECOVERY_CODE)
  221. }
  222. func LoginTwoFactorRecoveryCodePost(c *context.Context) {
  223. userID, ok := c.Session.Get("twoFactorUserID").(int64)
  224. if !ok {
  225. c.NotFound()
  226. return
  227. }
  228. if err := database.UseRecoveryCode(userID, c.Query("recovery_code")); err != nil {
  229. if database.IsTwoFactorRecoveryCodeNotFound(err) {
  230. c.Flash.Error(c.Tr("auth.login_two_factor_invalid_recovery_code"))
  231. c.RedirectSubpath("/user/login/two_factor_recovery_code")
  232. } else {
  233. c.Error(err, "use recovery code")
  234. }
  235. return
  236. }
  237. u, err := database.Handle.Users().GetByID(c.Req.Context(), userID)
  238. if err != nil {
  239. c.Error(err, "get user by ID")
  240. return
  241. }
  242. afterLogin(c, u, c.Session.Get("twoFactorRemember").(bool))
  243. }
  244. func SignOut(c *context.Context) {
  245. _ = c.Session.Flush()
  246. _ = c.Session.Destory(c.Context)
  247. c.SetCookie(conf.Security.CookieUsername, "", -1, conf.Server.Subpath)
  248. c.SetCookie(conf.Security.CookieRememberName, "", -1, conf.Server.Subpath)
  249. c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
  250. c.RedirectSubpath("/")
  251. }
  252. func SignUp(c *context.Context) {
  253. c.Title("sign_up")
  254. c.Data["EnableCaptcha"] = conf.Auth.EnableRegistrationCaptcha
  255. if conf.Auth.DisableRegistration {
  256. c.Data["DisableRegistration"] = true
  257. c.Success(SIGNUP)
  258. return
  259. }
  260. c.Success(SIGNUP)
  261. }
  262. func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
  263. c.Title("sign_up")
  264. c.Data["EnableCaptcha"] = conf.Auth.EnableRegistrationCaptcha
  265. if conf.Auth.DisableRegistration {
  266. c.Status(http.StatusForbidden)
  267. return
  268. }
  269. if c.HasError() {
  270. c.Success(SIGNUP)
  271. return
  272. }
  273. if conf.Auth.EnableRegistrationCaptcha && !cpt.VerifyReq(c.Req) {
  274. c.FormErr("Captcha")
  275. c.RenderWithErr(c.Tr("form.captcha_incorrect"), SIGNUP, &f)
  276. return
  277. }
  278. if f.Password != f.Retype {
  279. c.FormErr("Password")
  280. c.RenderWithErr(c.Tr("form.password_not_match"), SIGNUP, &f)
  281. return
  282. }
  283. user, err := database.Handle.Users().Create(c.Req.Context(), f.UserName, f.Email, database.CreateUserOptions{
  284. Password: f.Password,
  285. Activated: !conf.Auth.RequireEmailConfirmation,
  286. })
  287. if err != nil {
  288. switch {
  289. case database.IsErrUserAlreadyExist(err):
  290. c.FormErr("UserName")
  291. c.RenderWithErr(c.Tr("form.username_been_taken"), SIGNUP, &f)
  292. case database.IsErrEmailAlreadyUsed(err):
  293. c.FormErr("Email")
  294. c.RenderWithErr(c.Tr("form.email_been_used"), SIGNUP, &f)
  295. case database.IsErrNameNotAllowed(err):
  296. c.FormErr("UserName")
  297. c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), SIGNUP, &f)
  298. default:
  299. c.Error(err, "create user")
  300. }
  301. return
  302. }
  303. log.Trace("Account created: %s", user.Name)
  304. // FIXME: Count has pretty bad performance implication in large instances, we
  305. // should have a dedicate method to check whether the "user" table is empty.
  306. //
  307. // Auto-set admin for the only user.
  308. if database.Handle.Users().Count(c.Req.Context()) == 1 {
  309. v := true
  310. err := database.Handle.Users().Update(
  311. c.Req.Context(),
  312. user.ID,
  313. database.UpdateUserOptions{
  314. IsActivated: &v,
  315. IsAdmin: &v,
  316. },
  317. )
  318. if err != nil {
  319. c.Error(err, "update user")
  320. return
  321. }
  322. }
  323. // Send confirmation email.
  324. if conf.Auth.RequireEmailConfirmation && user.ID > 1 {
  325. email.SendActivateAccountMail(c.Context, database.NewMailerUser(user))
  326. c.Data["IsSendRegisterMail"] = true
  327. c.Data["Email"] = user.Email
  328. c.Data["PublicEmail"] = user.PublicEmail
  329. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  330. c.Success(ACTIVATE)
  331. if err := c.Cache.Put(userutil.MailResendCacheKey(user.ID), 1, 180); err != nil {
  332. log.Error("Failed to put cache key 'mail resend': %v", err)
  333. }
  334. return
  335. }
  336. c.RedirectSubpath("/user/login")
  337. }
  338. // verify active code when active account
  339. func verifyUserActiveCode(code string) (user *database.User) {
  340. data, err := tool.ParseToken(code)
  341. if err != nil || data.Valid() != nil {
  342. return nil
  343. }
  344. if user, err = database.Handle.Users().GetByID(gocontext.TODO(), data.Id); err != nil {
  345. if !database.IsErrUserNotExist(err) {
  346. log.Error("Failed to get user by id %d: %v", data.Id, err)
  347. }
  348. return nil
  349. }
  350. return user
  351. }
  352. // verify active code when active account
  353. func verifyActiveEmailCode(code, email string) *database.EmailAddress {
  354. data, err := tool.ParseToken(code)
  355. if err != nil {
  356. return nil
  357. } else if data.Valid() != nil {
  358. return nil
  359. }
  360. user, err := database.Handle.Users().GetByID(gocontext.TODO(), data.Id)
  361. if err != nil || user == nil {
  362. log.Error("Failed to get user by id %d: %v", data.Id, err)
  363. return nil
  364. }
  365. emailAddress, err := database.Handle.Users().GetEmail(gocontext.TODO(), user.ID, email, false)
  366. if err != nil {
  367. return nil
  368. }
  369. return emailAddress
  370. }
  371. func Activate(c *context.Context) {
  372. code := c.Query("code")
  373. if code == "" {
  374. c.Data["IsActivatePage"] = true
  375. if c.User == nil || c.User.IsActive {
  376. c.NotFound()
  377. return
  378. }
  379. // Resend confirmation email.
  380. if conf.Auth.RequireEmailConfirmation {
  381. if c.Cache.IsExist(userutil.MailResendCacheKey(c.User.ID)) {
  382. c.Data["ResendLimited"] = true
  383. } else {
  384. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  385. email.SendActivateAccountMail(c.Context, database.NewMailerUser(c.User))
  386. if err := c.Cache.Put(userutil.MailResendCacheKey(c.User.ID), 1, 180); err != nil {
  387. log.Error("Failed to put cache key 'mail resend': %v", err)
  388. }
  389. }
  390. } else {
  391. c.Data["ServiceNotEnabled"] = true
  392. }
  393. c.Success(ACTIVATE)
  394. return
  395. }
  396. // Verify code.
  397. if user := verifyUserActiveCode(code); user != nil {
  398. err := database.Handle.Users().Active(
  399. c.Req.Context(),
  400. user.ID,
  401. )
  402. if err != nil {
  403. c.Error(err, "update user")
  404. return
  405. }
  406. log.Trace("User activated: %s", user.Name)
  407. _ = c.Session.Set("uid", user.ID)
  408. _ = c.Session.Set("uname", user.Name)
  409. c.RedirectSubpath("/")
  410. return
  411. }
  412. c.Data["IsActivateFailed"] = true
  413. c.Success(ACTIVATE)
  414. }
  415. func ActivateEmail(c *context.Context) {
  416. code := c.Query("code")
  417. emailAddr := c.Query("email")
  418. // Verify code.
  419. if email := verifyActiveEmailCode(code, emailAddr); email != nil {
  420. err := database.Handle.Users().MarkEmailActivated(c.Req.Context(), email.UserID, email.Email)
  421. if err != nil {
  422. c.Error(err, "activate email")
  423. return
  424. }
  425. log.Trace("Email activated: %s", email.Email)
  426. c.Flash.Success(c.Tr("settings.add_email_success"))
  427. }
  428. c.RedirectSubpath("/user/settings/email")
  429. }
  430. func ForgotPasswd(c *context.Context) {
  431. c.Title("auth.forgot_password")
  432. if !conf.Email.Enabled {
  433. c.Data["IsResetDisable"] = true
  434. c.Success(FORGOT_PASSWORD)
  435. return
  436. }
  437. c.Data["IsResetRequest"] = true
  438. c.Success(FORGOT_PASSWORD)
  439. }
  440. func ForgotPasswdPost(c *context.Context) {
  441. c.Title("auth.forgot_password")
  442. if !conf.Email.Enabled {
  443. c.Status(403)
  444. return
  445. }
  446. c.Data["IsResetRequest"] = true
  447. emailAddr := c.Query("email")
  448. c.Data["Email"] = emailAddr
  449. u, err := database.Handle.Users().GetByEmail(c.Req.Context(), emailAddr)
  450. if err != nil {
  451. if database.IsErrUserNotExist(err) {
  452. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  453. c.Data["IsResetSent"] = true
  454. c.Success(FORGOT_PASSWORD)
  455. return
  456. }
  457. c.Error(err, "get user by email")
  458. return
  459. }
  460. if !u.IsLocal() {
  461. c.FormErr("Email")
  462. c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
  463. return
  464. }
  465. if c.Cache.IsExist(userutil.MailResendCacheKey(u.ID)) {
  466. c.Data["ResendLimited"] = true
  467. c.Success(FORGOT_PASSWORD)
  468. return
  469. }
  470. email.SendResetPasswordMail(c.Context, database.NewMailerUser(u))
  471. if err = c.Cache.Put(userutil.MailResendCacheKey(u.ID), 1, 180); err != nil {
  472. log.Error("Failed to put cache key 'mail resend': %v", err)
  473. }
  474. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  475. c.Data["IsResetSent"] = true
  476. c.Success(FORGOT_PASSWORD)
  477. }
  478. func ResetPasswd(c *context.Context) {
  479. c.Title("auth.reset_password")
  480. code := c.Query("code")
  481. if code == "" {
  482. c.NotFound()
  483. return
  484. }
  485. c.Data["Code"] = code
  486. c.Data["IsResetForm"] = true
  487. c.Success(RESET_PASSWORD)
  488. }
  489. func ResetPasswdPost(c *context.Context) {
  490. c.Title("auth.reset_password")
  491. code := c.Query("code")
  492. if code == "" {
  493. c.NotFound()
  494. return
  495. }
  496. c.Data["Code"] = code
  497. data, err := tool.ParseToken(code)
  498. if err == nil && data.Valid() == nil {
  499. user, err := database.Handle.Users().GetByID(gocontext.TODO(), data.Id)
  500. if err == nil && user != nil {
  501. // Validate password length.
  502. password := c.Query("password")
  503. if len(password) < 6 {
  504. c.Data["IsResetForm"] = true
  505. c.Data["Err_Password"] = true
  506. c.RenderWithErr(c.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  507. return
  508. }
  509. err := database.Handle.Users().Update(c.Req.Context(), user.ID, database.UpdateUserOptions{Password: &password})
  510. if err != nil {
  511. c.Error(err, "update user")
  512. return
  513. }
  514. log.Trace("User password reset: %s", user.Name)
  515. c.RedirectSubpath("/user/login")
  516. return
  517. } else if user == nil {
  518. log.Error("Failed to get user by id %d: %v", data.Id, err)
  519. }
  520. }
  521. c.Data["IsResetFailed"] = true
  522. c.Success(RESET_PASSWORD)
  523. }