auth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. "fmt"
  7. "net/http"
  8. "net/url"
  9. "github.com/go-macaron/captcha"
  10. "github.com/pkg/errors"
  11. log "unknwon.dev/clog/v2"
  12. "gogs.io/gogs/internal/auth"
  13. "gogs.io/gogs/internal/conf"
  14. "gogs.io/gogs/internal/context"
  15. "gogs.io/gogs/internal/db"
  16. "gogs.io/gogs/internal/email"
  17. "gogs.io/gogs/internal/form"
  18. "gogs.io/gogs/internal/tool"
  19. "gogs.io/gogs/internal/userutil"
  20. )
  21. const (
  22. LOGIN = "user/auth/login"
  23. TWO_FACTOR = "user/auth/two_factor"
  24. TWO_FACTOR_RECOVERY_CODE = "user/auth/two_factor_recovery_code"
  25. SIGNUP = "user/auth/signup"
  26. ACTIVATE = "user/auth/activate"
  27. FORGOT_PASSWORD = "user/auth/forgot_passwd"
  28. RESET_PASSWORD = "user/auth/reset_passwd"
  29. )
  30. // AutoLogin reads cookie and try to auto-login.
  31. func AutoLogin(c *context.Context) (bool, error) {
  32. if !db.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 := db.GetUserByName(uname)
  49. if err != nil {
  50. if !db.IsErrUserNotExist(err) {
  51. return false, fmt.Errorf("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 tool.IsSameSiteURLPath(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 := db.LoginSources.List(c.Req.Context(), db.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(LOGIN)
  105. }
  106. func afterLogin(c *context.Context, u *db.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 tool.IsSameSiteURLPath(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 := db.LoginSources.List(c.Req.Context(), db.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(LOGIN)
  139. return
  140. }
  141. u, err := db.Users.Authenticate(c.Req.Context(), f.UserName, f.Password, f.LoginSource)
  142. if err != nil {
  143. switch errors.Cause(err).(type) {
  144. case auth.ErrBadCredentials:
  145. c.FormErr("UserName", "Password")
  146. c.RenderWithErr(c.Tr("form.username_password_incorrect"), LOGIN, &f)
  147. case db.ErrLoginSourceMismatch:
  148. c.FormErr("LoginSource")
  149. c.RenderWithErr(c.Tr("form.auth_source_mismatch"), LOGIN, &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 !db.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(TWO_FACTOR)
  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 := db.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 := db.GetUserByID(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(TWO_FACTOR_RECOVERY_CODE)
  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 := db.UseRecoveryCode(userID, c.Query("recovery_code")); err != nil {
  229. if db.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 := db.GetUserByID(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. c.RedirectSubpath("/")
  251. }
  252. func SignUp(c *context.Context) {
  253. c.Title("sign_up")
  254. c.Data["EnableCaptcha"] = conf.Auth.EnableRegistrationCaptcha
  255. if conf.Auth.DisableRegistration {
  256. c.Data["DisableRegistration"] = true
  257. c.Success(SIGNUP)
  258. return
  259. }
  260. c.Success(SIGNUP)
  261. }
  262. func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
  263. c.Title("sign_up")
  264. c.Data["EnableCaptcha"] = conf.Auth.EnableRegistrationCaptcha
  265. if conf.Auth.DisableRegistration {
  266. c.Status(http.StatusForbidden)
  267. return
  268. }
  269. if c.HasError() {
  270. c.Success(SIGNUP)
  271. return
  272. }
  273. if conf.Auth.EnableRegistrationCaptcha && !cpt.VerifyReq(c.Req) {
  274. c.FormErr("Captcha")
  275. c.RenderWithErr(c.Tr("form.captcha_incorrect"), SIGNUP, &f)
  276. return
  277. }
  278. if f.Password != f.Retype {
  279. c.FormErr("Password")
  280. c.RenderWithErr(c.Tr("form.password_not_match"), SIGNUP, &f)
  281. return
  282. }
  283. user, err := db.Users.Create(
  284. c.Req.Context(),
  285. f.UserName,
  286. f.Email,
  287. db.CreateUserOptions{
  288. Password: f.Password,
  289. Activated: !conf.Auth.RequireEmailConfirmation,
  290. },
  291. )
  292. if err != nil {
  293. switch {
  294. case db.IsErrUserAlreadyExist(err):
  295. c.FormErr("UserName")
  296. c.RenderWithErr(c.Tr("form.username_been_taken"), SIGNUP, &f)
  297. case db.IsErrEmailAlreadyUsed(err):
  298. c.FormErr("Email")
  299. c.RenderWithErr(c.Tr("form.email_been_used"), SIGNUP, &f)
  300. case db.IsErrNameNotAllowed(err):
  301. c.FormErr("UserName")
  302. c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(db.ErrNameNotAllowed).Value()), SIGNUP, &f)
  303. default:
  304. c.Error(err, "create user")
  305. }
  306. return
  307. }
  308. log.Trace("Account created: %s", user.Name)
  309. // Auto-set admin for the only user.
  310. if db.CountUsers() == 1 {
  311. user.IsAdmin = true
  312. user.IsActive = true
  313. if err := db.UpdateUser(user); err != nil {
  314. c.Error(err, "update user")
  315. return
  316. }
  317. }
  318. // Send confirmation email.
  319. if conf.Auth.RequireEmailConfirmation && user.ID > 1 {
  320. email.SendActivateAccountMail(c.Context, db.NewMailerUser(user))
  321. c.Data["IsSendRegisterMail"] = true
  322. c.Data["Email"] = user.Email
  323. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  324. c.Success(ACTIVATE)
  325. if err := c.Cache.Put(userutil.MailResendCacheKey(user.ID), 1, 180); err != nil {
  326. log.Error("Failed to put cache key 'mail resend': %v", err)
  327. }
  328. return
  329. }
  330. c.RedirectSubpath("/user/login")
  331. }
  332. func Activate(c *context.Context) {
  333. code := c.Query("code")
  334. if code == "" {
  335. c.Data["IsActivatePage"] = true
  336. if c.User.IsActive {
  337. c.NotFound()
  338. return
  339. }
  340. // Resend confirmation email.
  341. if conf.Auth.RequireEmailConfirmation {
  342. if c.Cache.IsExist(userutil.MailResendCacheKey(c.User.ID)) {
  343. c.Data["ResendLimited"] = true
  344. } else {
  345. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  346. email.SendActivateAccountMail(c.Context, db.NewMailerUser(c.User))
  347. if err := c.Cache.Put(userutil.MailResendCacheKey(c.User.ID), 1, 180); err != nil {
  348. log.Error("Failed to put cache key 'mail resend': %v", err)
  349. }
  350. }
  351. } else {
  352. c.Data["ServiceNotEnabled"] = true
  353. }
  354. c.Success(ACTIVATE)
  355. return
  356. }
  357. // Verify code.
  358. if user := db.VerifyUserActiveCode(code); user != nil {
  359. user.IsActive = true
  360. var err error
  361. if user.Rands, err = userutil.RandomSalt(); err != nil {
  362. c.Error(err, "get user salt")
  363. return
  364. }
  365. if err := db.UpdateUser(user); err != nil {
  366. c.Error(err, "update user")
  367. return
  368. }
  369. log.Trace("User activated: %s", user.Name)
  370. _ = c.Session.Set("uid", user.ID)
  371. _ = c.Session.Set("uname", user.Name)
  372. c.RedirectSubpath("/")
  373. return
  374. }
  375. c.Data["IsActivateFailed"] = true
  376. c.Success(ACTIVATE)
  377. }
  378. func ActivateEmail(c *context.Context) {
  379. code := c.Query("code")
  380. emailAddr := c.Query("email")
  381. // Verify code.
  382. if email := db.VerifyActiveEmailCode(code, emailAddr); email != nil {
  383. if err := email.Activate(); err != nil {
  384. c.Error(err, "activate email")
  385. }
  386. log.Trace("Email activated: %s", email.Email)
  387. c.Flash.Success(c.Tr("settings.add_email_success"))
  388. }
  389. c.RedirectSubpath("/user/settings/email")
  390. }
  391. func ForgotPasswd(c *context.Context) {
  392. c.Title("auth.forgot_password")
  393. if !conf.Email.Enabled {
  394. c.Data["IsResetDisable"] = true
  395. c.Success(FORGOT_PASSWORD)
  396. return
  397. }
  398. c.Data["IsResetRequest"] = true
  399. c.Success(FORGOT_PASSWORD)
  400. }
  401. func ForgotPasswdPost(c *context.Context) {
  402. c.Title("auth.forgot_password")
  403. if !conf.Email.Enabled {
  404. c.Status(403)
  405. return
  406. }
  407. c.Data["IsResetRequest"] = true
  408. emailAddr := c.Query("email")
  409. c.Data["Email"] = emailAddr
  410. u, err := db.GetUserByEmail(emailAddr)
  411. if err != nil {
  412. if db.IsErrUserNotExist(err) {
  413. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  414. c.Data["IsResetSent"] = true
  415. c.Success(FORGOT_PASSWORD)
  416. return
  417. }
  418. c.Error(err, "get user by email")
  419. return
  420. }
  421. if !u.IsLocal() {
  422. c.FormErr("Email")
  423. c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
  424. return
  425. }
  426. if c.Cache.IsExist(userutil.MailResendCacheKey(u.ID)) {
  427. c.Data["ResendLimited"] = true
  428. c.Success(FORGOT_PASSWORD)
  429. return
  430. }
  431. email.SendResetPasswordMail(c.Context, db.NewMailerUser(u))
  432. if err = c.Cache.Put(userutil.MailResendCacheKey(u.ID), 1, 180); err != nil {
  433. log.Error("Failed to put cache key 'mail resend': %v", err)
  434. }
  435. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  436. c.Data["IsResetSent"] = true
  437. c.Success(FORGOT_PASSWORD)
  438. }
  439. func ResetPasswd(c *context.Context) {
  440. c.Title("auth.reset_password")
  441. code := c.Query("code")
  442. if code == "" {
  443. c.NotFound()
  444. return
  445. }
  446. c.Data["Code"] = code
  447. c.Data["IsResetForm"] = true
  448. c.Success(RESET_PASSWORD)
  449. }
  450. func ResetPasswdPost(c *context.Context) {
  451. c.Title("auth.reset_password")
  452. code := c.Query("code")
  453. if code == "" {
  454. c.NotFound()
  455. return
  456. }
  457. c.Data["Code"] = code
  458. if u := db.VerifyUserActiveCode(code); u != nil {
  459. // Validate password length.
  460. passwd := c.Query("password")
  461. if len(passwd) < 6 {
  462. c.Data["IsResetForm"] = true
  463. c.Data["Err_Password"] = true
  464. c.RenderWithErr(c.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  465. return
  466. }
  467. u.Password = passwd
  468. var err error
  469. if u.Rands, err = userutil.RandomSalt(); err != nil {
  470. c.Error(err, "get user salt")
  471. return
  472. }
  473. if u.Salt, err = userutil.RandomSalt(); err != nil {
  474. c.Error(err, "get user salt")
  475. return
  476. }
  477. u.Password = userutil.EncodePassword(u.Password, u.Salt)
  478. if err := db.UpdateUser(u); err != nil {
  479. c.Error(err, "update user")
  480. return
  481. }
  482. log.Trace("User password reset: %s", u.Name)
  483. c.RedirectSubpath("/user/login")
  484. return
  485. }
  486. c.Data["IsResetFailed"] = true
  487. c.Success(RESET_PASSWORD)
  488. }