auth.go 16 KB

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