auth.go 14 KB

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