auth.go 14 KB

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