auth.go 16 KB

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