auth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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.LoginSources.List(db.ListLoginSourceOpts{OnlyActivated: true})
  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.LoginSources.List(db.ListLoginSourceOpts{OnlyActivated: true})
  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.TwoFactors.GetByUserID(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.IsErrNameNotAllowed(err):
  295. c.FormErr("UserName")
  296. c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(db.ErrNameNotAllowed).Value()), SIGNUP, &f)
  297. default:
  298. c.Error(err, "create user")
  299. }
  300. return
  301. }
  302. log.Trace("Account created: %s", u.Name)
  303. // Auto-set admin for the only user.
  304. if db.CountUsers() == 1 {
  305. u.IsAdmin = true
  306. u.IsActive = true
  307. if err := db.UpdateUser(u); err != nil {
  308. c.Error(err, "update user")
  309. return
  310. }
  311. }
  312. // Send confirmation email, no need for social account.
  313. if conf.Auth.RegisterEmailConfirm && u.ID > 1 {
  314. email.SendActivateAccountMail(c.Context, db.NewMailerUser(u))
  315. c.Data["IsSendRegisterMail"] = true
  316. c.Data["Email"] = u.Email
  317. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  318. c.Success(ACTIVATE)
  319. if err := c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
  320. log.Error("Failed to put cache key 'mail resend': %v", err)
  321. }
  322. return
  323. }
  324. c.RedirectSubpath("/user/login")
  325. }
  326. func Activate(c *context.Context) {
  327. code := c.Query("code")
  328. if len(code) == 0 {
  329. c.Data["IsActivatePage"] = true
  330. if c.User.IsActive {
  331. c.NotFound()
  332. return
  333. }
  334. // Resend confirmation email.
  335. if conf.Auth.RequireEmailConfirmation {
  336. if c.Cache.IsExist(c.User.MailResendCacheKey()) {
  337. c.Data["ResendLimited"] = true
  338. } else {
  339. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  340. email.SendActivateAccountMail(c.Context, db.NewMailerUser(c.User))
  341. if err := c.Cache.Put(c.User.MailResendCacheKey(), 1, 180); err != nil {
  342. log.Error("Failed to put cache key 'mail resend': %v", err)
  343. }
  344. }
  345. } else {
  346. c.Data["ServiceNotEnabled"] = true
  347. }
  348. c.Success(ACTIVATE)
  349. return
  350. }
  351. // Verify code.
  352. if user := db.VerifyUserActiveCode(code); user != nil {
  353. user.IsActive = true
  354. var err error
  355. if user.Rands, err = db.GetUserSalt(); err != nil {
  356. c.Error(err, "get user salt")
  357. return
  358. }
  359. if err := db.UpdateUser(user); err != nil {
  360. c.Error(err, "update user")
  361. return
  362. }
  363. log.Trace("User activated: %s", user.Name)
  364. _ = c.Session.Set("uid", user.ID)
  365. _ = c.Session.Set("uname", user.Name)
  366. c.RedirectSubpath("/")
  367. return
  368. }
  369. c.Data["IsActivateFailed"] = true
  370. c.Success(ACTIVATE)
  371. }
  372. func ActivateEmail(c *context.Context) {
  373. code := c.Query("code")
  374. emailAddr := c.Query("email")
  375. // Verify code.
  376. if email := db.VerifyActiveEmailCode(code, emailAddr); email != nil {
  377. if err := email.Activate(); err != nil {
  378. c.Error(err, "activate email")
  379. }
  380. log.Trace("Email activated: %s", email.Email)
  381. c.Flash.Success(c.Tr("settings.add_email_success"))
  382. }
  383. c.RedirectSubpath("/user/settings/email")
  384. }
  385. func ForgotPasswd(c *context.Context) {
  386. c.Title("auth.forgot_password")
  387. if !conf.Email.Enabled {
  388. c.Data["IsResetDisable"] = true
  389. c.Success(FORGOT_PASSWORD)
  390. return
  391. }
  392. c.Data["IsResetRequest"] = true
  393. c.Success(FORGOT_PASSWORD)
  394. }
  395. func ForgotPasswdPost(c *context.Context) {
  396. c.Title("auth.forgot_password")
  397. if !conf.Email.Enabled {
  398. c.Status(403)
  399. return
  400. }
  401. c.Data["IsResetRequest"] = true
  402. emailAddr := c.Query("email")
  403. c.Data["Email"] = emailAddr
  404. u, err := db.GetUserByEmail(emailAddr)
  405. if err != nil {
  406. if db.IsErrUserNotExist(err) {
  407. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  408. c.Data["IsResetSent"] = true
  409. c.Success(FORGOT_PASSWORD)
  410. return
  411. }
  412. c.Error(err, "get user by email")
  413. return
  414. }
  415. if !u.IsLocal() {
  416. c.FormErr("Email")
  417. c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
  418. return
  419. }
  420. if c.Cache.IsExist(u.MailResendCacheKey()) {
  421. c.Data["ResendLimited"] = true
  422. c.Success(FORGOT_PASSWORD)
  423. return
  424. }
  425. email.SendResetPasswordMail(c.Context, db.NewMailerUser(u))
  426. if err = c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
  427. log.Error("Failed to put cache key 'mail resend': %v", err)
  428. }
  429. c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
  430. c.Data["IsResetSent"] = true
  431. c.Success(FORGOT_PASSWORD)
  432. }
  433. func ResetPasswd(c *context.Context) {
  434. c.Title("auth.reset_password")
  435. code := c.Query("code")
  436. if len(code) == 0 {
  437. c.NotFound()
  438. return
  439. }
  440. c.Data["Code"] = code
  441. c.Data["IsResetForm"] = true
  442. c.Success(RESET_PASSWORD)
  443. }
  444. func ResetPasswdPost(c *context.Context) {
  445. c.Title("auth.reset_password")
  446. code := c.Query("code")
  447. if len(code) == 0 {
  448. c.NotFound()
  449. return
  450. }
  451. c.Data["Code"] = code
  452. if u := db.VerifyUserActiveCode(code); u != nil {
  453. // Validate password length.
  454. passwd := c.Query("password")
  455. if len(passwd) < 6 {
  456. c.Data["IsResetForm"] = true
  457. c.Data["Err_Password"] = true
  458. c.RenderWithErr(c.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  459. return
  460. }
  461. u.Passwd = passwd
  462. var err error
  463. if u.Rands, err = db.GetUserSalt(); err != nil {
  464. c.Error(err, "get user salt")
  465. return
  466. }
  467. if u.Salt, err = db.GetUserSalt(); err != nil {
  468. c.Error(err, "get user salt")
  469. return
  470. }
  471. u.EncodePassword()
  472. if err := db.UpdateUser(u); err != nil {
  473. c.Error(err, "update user")
  474. return
  475. }
  476. log.Trace("User password reset: %s", u.Name)
  477. c.RedirectSubpath("/user/login")
  478. return
  479. }
  480. c.Data["IsResetFailed"] = true
  481. c.Success(RESET_PASSWORD)
  482. }