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. user.IsAdmin = true
  317. user.IsActive = true
  318. if err := db.UpdateUser(user); 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, db.NewMailerUser(user))
  326. c.Data["IsSendRegisterMail"] = true
  327. c.Data["Email"] = user.Email
  328. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  329. c.Success(ACTIVATE)
  330. if err := c.Cache.Put(userutil.MailResendCacheKey(user.ID), 1, 180); err != nil {
  331. log.Error("Failed to put cache key 'mail resend': %v", err)
  332. }
  333. return
  334. }
  335. c.RedirectSubpath("/user/login")
  336. }
  337. // parseUserFromCode returns user by username encoded in code.
  338. // It returns nil if code or username is invalid.
  339. func parseUserFromCode(code string) (user *db.User) {
  340. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  341. return nil
  342. }
  343. // Use tail hex username to query user
  344. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  345. if b, err := hex.DecodeString(hexStr); err == nil {
  346. if user, err = db.Users.GetByUsername(gocontext.TODO(), string(b)); user != nil {
  347. return user
  348. } else if !db.IsErrUserNotExist(err) {
  349. log.Error("Failed to get user by name %q: %v", string(b), err)
  350. }
  351. }
  352. return nil
  353. }
  354. // verify active code when active account
  355. func verifyUserActiveCode(code string) (user *db.User) {
  356. minutes := conf.Auth.ActivateCodeLives
  357. if user = parseUserFromCode(code); user != nil {
  358. // time limit code
  359. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  360. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Password + user.Rands
  361. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  362. return user
  363. }
  364. }
  365. return nil
  366. }
  367. // verify active code when active account
  368. func verifyActiveEmailCode(code, email string) *db.EmailAddress {
  369. minutes := conf.Auth.ActivateCodeLives
  370. if user := parseUserFromCode(code); user != nil {
  371. // time limit code
  372. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  373. data := com.ToStr(user.ID) + email + user.LowerName + user.Password + user.Rands
  374. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  375. emailAddress, err := db.EmailAddresses.GetByEmail(gocontext.TODO(), email, false)
  376. if err == nil {
  377. return emailAddress
  378. }
  379. }
  380. }
  381. return nil
  382. }
  383. func Activate(c *context.Context) {
  384. code := c.Query("code")
  385. if code == "" {
  386. c.Data["IsActivatePage"] = true
  387. if c.User.IsActive {
  388. c.NotFound()
  389. return
  390. }
  391. // Resend confirmation email.
  392. if conf.Auth.RequireEmailConfirmation {
  393. if c.Cache.IsExist(userutil.MailResendCacheKey(c.User.ID)) {
  394. c.Data["ResendLimited"] = true
  395. } else {
  396. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  397. email.SendActivateAccountMail(c.Context, db.NewMailerUser(c.User))
  398. if err := c.Cache.Put(userutil.MailResendCacheKey(c.User.ID), 1, 180); err != nil {
  399. log.Error("Failed to put cache key 'mail resend': %v", err)
  400. }
  401. }
  402. } else {
  403. c.Data["ServiceNotEnabled"] = true
  404. }
  405. c.Success(ACTIVATE)
  406. return
  407. }
  408. // Verify code.
  409. if user := verifyUserActiveCode(code); user != nil {
  410. user.IsActive = true
  411. var err error
  412. if user.Rands, err = userutil.RandomSalt(); err != nil {
  413. c.Error(err, "get user salt")
  414. return
  415. }
  416. if err := db.UpdateUser(user); err != nil {
  417. c.Error(err, "update user")
  418. return
  419. }
  420. log.Trace("User activated: %s", user.Name)
  421. _ = c.Session.Set("uid", user.ID)
  422. _ = c.Session.Set("uname", user.Name)
  423. c.RedirectSubpath("/")
  424. return
  425. }
  426. c.Data["IsActivateFailed"] = true
  427. c.Success(ACTIVATE)
  428. }
  429. func ActivateEmail(c *context.Context) {
  430. code := c.Query("code")
  431. emailAddr := c.Query("email")
  432. // Verify code.
  433. if email := verifyActiveEmailCode(code, emailAddr); email != nil {
  434. if err := email.Activate(); err != nil {
  435. c.Error(err, "activate email")
  436. }
  437. log.Trace("Email activated: %s", email.Email)
  438. c.Flash.Success(c.Tr("settings.add_email_success"))
  439. }
  440. c.RedirectSubpath("/user/settings/email")
  441. }
  442. func ForgotPasswd(c *context.Context) {
  443. c.Title("auth.forgot_password")
  444. if !conf.Email.Enabled {
  445. c.Data["IsResetDisable"] = true
  446. c.Success(FORGOT_PASSWORD)
  447. return
  448. }
  449. c.Data["IsResetRequest"] = true
  450. c.Success(FORGOT_PASSWORD)
  451. }
  452. func ForgotPasswdPost(c *context.Context) {
  453. c.Title("auth.forgot_password")
  454. if !conf.Email.Enabled {
  455. c.Status(403)
  456. return
  457. }
  458. c.Data["IsResetRequest"] = true
  459. emailAddr := c.Query("email")
  460. c.Data["Email"] = emailAddr
  461. u, err := db.Users.GetByEmail(c.Req.Context(), emailAddr)
  462. if err != nil {
  463. if db.IsErrUserNotExist(err) {
  464. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  465. c.Data["IsResetSent"] = true
  466. c.Success(FORGOT_PASSWORD)
  467. return
  468. }
  469. c.Error(err, "get user by email")
  470. return
  471. }
  472. if !u.IsLocal() {
  473. c.FormErr("Email")
  474. c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
  475. return
  476. }
  477. if c.Cache.IsExist(userutil.MailResendCacheKey(u.ID)) {
  478. c.Data["ResendLimited"] = true
  479. c.Success(FORGOT_PASSWORD)
  480. return
  481. }
  482. email.SendResetPasswordMail(c.Context, db.NewMailerUser(u))
  483. if err = c.Cache.Put(userutil.MailResendCacheKey(u.ID), 1, 180); err != nil {
  484. log.Error("Failed to put cache key 'mail resend': %v", err)
  485. }
  486. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  487. c.Data["IsResetSent"] = true
  488. c.Success(FORGOT_PASSWORD)
  489. }
  490. func ResetPasswd(c *context.Context) {
  491. c.Title("auth.reset_password")
  492. code := c.Query("code")
  493. if code == "" {
  494. c.NotFound()
  495. return
  496. }
  497. c.Data["Code"] = code
  498. c.Data["IsResetForm"] = true
  499. c.Success(RESET_PASSWORD)
  500. }
  501. func ResetPasswdPost(c *context.Context) {
  502. c.Title("auth.reset_password")
  503. code := c.Query("code")
  504. if code == "" {
  505. c.NotFound()
  506. return
  507. }
  508. c.Data["Code"] = code
  509. if u := verifyUserActiveCode(code); u != nil {
  510. // Validate password length.
  511. passwd := c.Query("password")
  512. if len(passwd) < 6 {
  513. c.Data["IsResetForm"] = true
  514. c.Data["Err_Password"] = true
  515. c.RenderWithErr(c.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  516. return
  517. }
  518. u.Password = passwd
  519. var err error
  520. if u.Rands, err = userutil.RandomSalt(); err != nil {
  521. c.Error(err, "get user salt")
  522. return
  523. }
  524. if u.Salt, err = userutil.RandomSalt(); err != nil {
  525. c.Error(err, "get user salt")
  526. return
  527. }
  528. u.Password = userutil.EncodePassword(u.Password, u.Salt)
  529. if err := db.UpdateUser(u); 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. }