auth.go 14 KB

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