auth.go 16 KB

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