1
0

auth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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/urlutil"
  19. "gogs.io/gogs/internal/userutil"
  20. )
  21. const (
  22. tmplUserAuthLogin = "user/auth/login"
  23. tmplUserAuthTwoFactor = "user/auth/two_factor"
  24. tmplUserAuthTwoFactorRecoveryCode = "user/auth/two_factor_recovery_code"
  25. tmplUserAuthSignup = "user/auth/signup"
  26. TmplUserAuthActivate = "user/auth/activate"
  27. tmplUserAuthForgotPassword = "user/auth/forgot_passwd"
  28. tmplUserAuthResetPassword = "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, errors.Newf("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 urlutil.IsSameSite(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(tmplUserAuthLogin)
  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 urlutil.IsSameSite(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(tmplUserAuthLogin)
  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"), tmplUserAuthLogin, &f)
  147. case database.IsErrLoginSourceMismatch(err):
  148. c.FormErr("LoginSource")
  149. c.RenderWithErr(c.Tr("form.auth_source_mismatch"), tmplUserAuthLogin, &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(tmplUserAuthTwoFactor)
  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(tmplUserAuthTwoFactorRecoveryCode)
  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.Handle.TwoFactors().UseRecoveryCode(c.Req.Context(), 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. if conf.Auth.CustomLogoutURL != "" {
  251. c.Redirect(conf.Auth.CustomLogoutURL)
  252. return
  253. }
  254. c.RedirectSubpath("/")
  255. }
  256. func SignUp(c *context.Context) {
  257. c.Title("sign_up")
  258. c.Data["EnableCaptcha"] = conf.Auth.EnableRegistrationCaptcha
  259. if conf.Auth.DisableRegistration {
  260. c.Data["DisableRegistration"] = true
  261. c.Success(tmplUserAuthSignup)
  262. return
  263. }
  264. c.Success(tmplUserAuthSignup)
  265. }
  266. func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
  267. c.Title("sign_up")
  268. c.Data["EnableCaptcha"] = conf.Auth.EnableRegistrationCaptcha
  269. if conf.Auth.DisableRegistration {
  270. c.Status(http.StatusForbidden)
  271. return
  272. }
  273. if c.HasError() {
  274. c.Success(tmplUserAuthSignup)
  275. return
  276. }
  277. if conf.Auth.EnableRegistrationCaptcha && !cpt.VerifyReq(c.Req) {
  278. c.FormErr("Captcha")
  279. c.RenderWithErr(c.Tr("form.captcha_incorrect"), tmplUserAuthSignup, &f)
  280. return
  281. }
  282. if f.Password != f.Retype {
  283. c.FormErr("Password")
  284. c.RenderWithErr(c.Tr("form.password_not_match"), tmplUserAuthSignup, &f)
  285. return
  286. }
  287. user, err := database.Handle.Users().Create(
  288. c.Req.Context(),
  289. f.UserName,
  290. f.Email,
  291. database.CreateUserOptions{
  292. Password: f.Password,
  293. Activated: !conf.Auth.RequireEmailConfirmation,
  294. },
  295. )
  296. if err != nil {
  297. switch {
  298. case database.IsErrUserAlreadyExist(err):
  299. c.FormErr("UserName")
  300. c.RenderWithErr(c.Tr("form.username_been_taken"), tmplUserAuthSignup, &f)
  301. case database.IsErrEmailAlreadyUsed(err):
  302. c.FormErr("Email")
  303. c.RenderWithErr(c.Tr("form.email_been_used"), tmplUserAuthSignup, &f)
  304. case database.IsErrNameNotAllowed(err):
  305. c.FormErr("UserName")
  306. c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplUserAuthSignup, &f)
  307. default:
  308. c.Error(err, "create user")
  309. }
  310. return
  311. }
  312. log.Trace("Account created: %s", user.Name)
  313. // FIXME: Count has pretty bad performance implication in large instances, we
  314. // should have a dedicate method to check whether the "user" table is empty.
  315. //
  316. // Auto-set admin for the only user.
  317. if database.Handle.Users().Count(c.Req.Context()) == 1 {
  318. v := true
  319. err := database.Handle.Users().Update(
  320. c.Req.Context(),
  321. user.ID,
  322. database.UpdateUserOptions{
  323. IsActivated: &v,
  324. IsAdmin: &v,
  325. },
  326. )
  327. if err != nil {
  328. c.Error(err, "update user")
  329. return
  330. }
  331. }
  332. // Send confirmation email.
  333. if conf.Auth.RequireEmailConfirmation && user.ID > 1 {
  334. email.SendActivateAccountMail(c.Context, database.NewMailerUser(user))
  335. c.Data["IsSendRegisterMail"] = true
  336. c.Data["Email"] = user.Email
  337. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  338. c.Success(TmplUserAuthActivate)
  339. if err := c.Cache.Put(userutil.MailResendCacheKey(user.ID), 1, 180); err != nil {
  340. log.Error("Failed to put cache key 'mail resend': %v", err)
  341. }
  342. return
  343. }
  344. c.RedirectSubpath("/user/login")
  345. }
  346. // parseUserFromCode returns user by username encoded in code.
  347. // It returns nil if code or username is invalid.
  348. func parseUserFromCode(code string) (user *database.User) {
  349. if len(code) <= tool.TimeLimitCodeLength {
  350. return nil
  351. }
  352. // Use tail hex username to query user
  353. hexStr := code[tool.TimeLimitCodeLength:]
  354. if b, err := hex.DecodeString(hexStr); err == nil {
  355. if user, err = database.Handle.Users().GetByUsername(gocontext.TODO(), string(b)); user != nil {
  356. return user
  357. } else if !database.IsErrUserNotExist(err) {
  358. log.Error("Failed to get user by name %q: %v", string(b), err)
  359. }
  360. }
  361. return nil
  362. }
  363. // verify active code when active account
  364. func verifyUserActiveCode(code string) (user *database.User) {
  365. minutes := conf.Auth.ActivateCodeLives
  366. if user = parseUserFromCode(code); user != nil {
  367. // time limit code
  368. prefix := code[:tool.TimeLimitCodeLength]
  369. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Password + user.Rands
  370. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  371. return user
  372. }
  373. }
  374. return nil
  375. }
  376. // verify active code when active account
  377. func verifyActiveEmailCode(code, email string) *database.EmailAddress {
  378. minutes := conf.Auth.ActivateCodeLives
  379. if user := parseUserFromCode(code); user != nil {
  380. // time limit code
  381. prefix := code[:tool.TimeLimitCodeLength]
  382. data := com.ToStr(user.ID) + email + user.LowerName + user.Password + user.Rands
  383. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  384. emailAddress, err := database.Handle.Users().GetEmail(gocontext.TODO(), user.ID, email, false)
  385. if err == nil {
  386. return emailAddress
  387. }
  388. }
  389. }
  390. return nil
  391. }
  392. func Activate(c *context.Context) {
  393. code := c.Query("code")
  394. if code == "" {
  395. c.Data["IsActivatePage"] = true
  396. if c.User.IsActive {
  397. c.NotFound()
  398. return
  399. }
  400. // Resend confirmation email.
  401. if conf.Auth.RequireEmailConfirmation {
  402. if c.Cache.IsExist(userutil.MailResendCacheKey(c.User.ID)) {
  403. c.Data["ResendLimited"] = true
  404. } else {
  405. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  406. email.SendActivateAccountMail(c.Context, database.NewMailerUser(c.User))
  407. if err := c.Cache.Put(userutil.MailResendCacheKey(c.User.ID), 1, 180); err != nil {
  408. log.Error("Failed to put cache key 'mail resend': %v", err)
  409. }
  410. }
  411. } else {
  412. c.Data["ServiceNotEnabled"] = true
  413. }
  414. c.Success(TmplUserAuthActivate)
  415. return
  416. }
  417. // Verify code.
  418. if user := verifyUserActiveCode(code); user != nil {
  419. v := true
  420. err := database.Handle.Users().Update(
  421. c.Req.Context(),
  422. user.ID,
  423. database.UpdateUserOptions{
  424. GenerateNewRands: true,
  425. IsActivated: &v,
  426. },
  427. )
  428. if err != nil {
  429. c.Error(err, "update user")
  430. return
  431. }
  432. log.Trace("User activated: %s", user.Name)
  433. _ = c.Session.Set("uid", user.ID)
  434. _ = c.Session.Set("uname", user.Name)
  435. c.RedirectSubpath("/")
  436. return
  437. }
  438. c.Data["IsActivateFailed"] = true
  439. c.Success(TmplUserAuthActivate)
  440. }
  441. func ActivateEmail(c *context.Context) {
  442. code := c.Query("code")
  443. emailAddr := c.Query("email")
  444. // Verify code.
  445. if email := verifyActiveEmailCode(code, emailAddr); email != nil {
  446. err := database.Handle.Users().MarkEmailActivated(c.Req.Context(), email.UserID, email.Email)
  447. if err != nil {
  448. c.Error(err, "activate email")
  449. return
  450. }
  451. log.Trace("Email activated: %s", email.Email)
  452. c.Flash.Success(c.Tr("settings.add_email_success"))
  453. }
  454. c.RedirectSubpath("/user/settings/email")
  455. }
  456. func ForgotPasswd(c *context.Context) {
  457. c.Title("auth.forgot_password")
  458. if !conf.Email.Enabled {
  459. c.Data["IsResetDisable"] = true
  460. c.Success(tmplUserAuthForgotPassword)
  461. return
  462. }
  463. c.Data["IsResetRequest"] = true
  464. c.Success(tmplUserAuthForgotPassword)
  465. }
  466. func ForgotPasswdPost(c *context.Context) {
  467. c.Title("auth.forgot_password")
  468. if !conf.Email.Enabled {
  469. c.Status(403)
  470. return
  471. }
  472. c.Data["IsResetRequest"] = true
  473. emailAddr := c.Query("email")
  474. c.Data["Email"] = emailAddr
  475. u, err := database.Handle.Users().GetByEmail(c.Req.Context(), emailAddr)
  476. if err != nil {
  477. if database.IsErrUserNotExist(err) {
  478. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  479. c.Data["IsResetSent"] = true
  480. c.Success(tmplUserAuthForgotPassword)
  481. return
  482. }
  483. c.Error(err, "get user by email")
  484. return
  485. }
  486. if !u.IsLocal() {
  487. c.FormErr("Email")
  488. c.RenderWithErr(c.Tr("auth.non_local_account"), tmplUserAuthForgotPassword, nil)
  489. return
  490. }
  491. if c.Cache.IsExist(userutil.MailResendCacheKey(u.ID)) {
  492. c.Data["ResendLimited"] = true
  493. c.Success(tmplUserAuthForgotPassword)
  494. return
  495. }
  496. email.SendResetPasswordMail(c.Context, database.NewMailerUser(u))
  497. if err = c.Cache.Put(userutil.MailResendCacheKey(u.ID), 1, 180); err != nil {
  498. log.Error("Failed to put cache key 'mail resend': %v", err)
  499. }
  500. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  501. c.Data["IsResetSent"] = true
  502. c.Success(tmplUserAuthForgotPassword)
  503. }
  504. func ResetPasswd(c *context.Context) {
  505. c.Title("auth.reset_password")
  506. code := c.Query("code")
  507. if code == "" {
  508. c.NotFound()
  509. return
  510. }
  511. c.Data["Code"] = code
  512. c.Data["IsResetForm"] = true
  513. c.Success(tmplUserAuthResetPassword)
  514. }
  515. func ResetPasswdPost(c *context.Context) {
  516. c.Title("auth.reset_password")
  517. code := c.Query("code")
  518. if code == "" {
  519. c.NotFound()
  520. return
  521. }
  522. c.Data["Code"] = code
  523. if u := verifyUserActiveCode(code); u != nil {
  524. // Validate password length.
  525. password := c.Query("password")
  526. if len(password) < 6 {
  527. c.Data["IsResetForm"] = true
  528. c.Data["Err_Password"] = true
  529. c.RenderWithErr(c.Tr("auth.password_too_short"), tmplUserAuthResetPassword, nil)
  530. return
  531. }
  532. err := database.Handle.Users().Update(c.Req.Context(), u.ID, database.UpdateUserOptions{Password: &password})
  533. if err != nil {
  534. c.Error(err, "update user")
  535. return
  536. }
  537. log.Trace("User password reset: %s", u.Name)
  538. c.RedirectSubpath("/user/login")
  539. return
  540. }
  541. c.Data["IsResetFailed"] = true
  542. c.Success(tmplUserAuthResetPassword)
  543. }