auth.go 16 KB

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