auth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. log "gopkg.in/clog.v1"
  10. "github.com/gogs/gogs/models"
  11. "github.com/gogs/gogs/models/errors"
  12. "github.com/gogs/gogs/pkg/context"
  13. "github.com/gogs/gogs/pkg/form"
  14. "github.com/gogs/gogs/pkg/mailer"
  15. "github.com/gogs/gogs/pkg/setting"
  16. "github.com/gogs/gogs/pkg/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 !models.HasEngine {
  30. return false, nil
  31. }
  32. uname := c.GetCookie(setting.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(setting.CookieUserName, "", -1, setting.AppSubURL)
  41. c.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  42. c.SetCookie(setting.LoginStatusCookieName, "", -1, setting.AppSubURL)
  43. }
  44. }()
  45. u, err := models.GetUserByName(uname)
  46. if err != nil {
  47. if !errors.IsUserNotExist(err) {
  48. return false, fmt.Errorf("GetUserByName: %v", err)
  49. }
  50. return false, nil
  51. }
  52. if val, ok := c.GetSuperSecureCookie(u.Rands+u.Passwd, setting.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(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  59. if setting.EnableLoginStatusCookie {
  60. c.SetCookie(setting.LoginStatusCookieName, "true", 0, setting.AppSubURL)
  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.ServerError("AutoLogin", err)
  70. return
  71. }
  72. redirectTo := c.Query("redirect_to")
  73. if len(redirectTo) > 0 {
  74. c.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL)
  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.SubURLRedirect("/")
  83. }
  84. c.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  85. return
  86. }
  87. // Display normal login page
  88. loginSources, err := models.ActivatedLoginSources()
  89. if err != nil {
  90. c.ServerError("ActivatedLoginSources", err)
  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 *models.User, remember bool) {
  104. if remember {
  105. days := 86400 * setting.LoginRememberDays
  106. c.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL, "", setting.CookieSecure, true)
  107. c.SetSuperSecureCookie(u.Rands+u.Passwd, setting.CookieRememberName, u.Name, days, setting.AppSubURL, "", setting.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(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  115. if setting.EnableLoginStatusCookie {
  116. c.SetCookie(setting.LoginStatusCookieName, "true", 0, setting.AppSubURL)
  117. }
  118. redirectTo, _ := url.QueryUnescape(c.GetCookie("redirect_to"))
  119. c.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  120. if tool.IsSameSiteURLPath(redirectTo) {
  121. c.Redirect(redirectTo)
  122. return
  123. }
  124. c.SubURLRedirect("/")
  125. }
  126. func LoginPost(c *context.Context, f form.SignIn) {
  127. c.Title("sign_in")
  128. loginSources, err := models.ActivatedLoginSources()
  129. if err != nil {
  130. c.ServerError("ActivatedLoginSources", err)
  131. return
  132. }
  133. c.Data["LoginSources"] = loginSources
  134. if c.HasError() {
  135. c.Success(LOGIN)
  136. return
  137. }
  138. u, err := models.UserLogin(f.UserName, f.Password, f.LoginSource)
  139. if err != nil {
  140. switch err.(type) {
  141. case errors.UserNotExist:
  142. c.FormErr("UserName", "Password")
  143. c.RenderWithErr(c.Tr("form.username_password_incorrect"), LOGIN, &f)
  144. case errors.LoginSourceMismatch:
  145. c.FormErr("LoginSource")
  146. c.RenderWithErr(c.Tr("form.auth_source_mismatch"), LOGIN, &f)
  147. default:
  148. c.ServerError("UserLogin", err)
  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.SubURLRedirect("/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 := models.GetTwoFactorByUserID(userID)
  181. if err != nil {
  182. c.ServerError("GetTwoFactorByUserID", err)
  183. return
  184. }
  185. passcode := c.Query("passcode")
  186. valid, err := t.ValidateTOTP(passcode)
  187. if err != nil {
  188. c.ServerError("ValidateTOTP", err)
  189. return
  190. } else if !valid {
  191. c.Flash.Error(c.Tr("settings.two_factor_invalid_passcode"))
  192. c.SubURLRedirect("/user/login/two_factor")
  193. return
  194. }
  195. u, err := models.GetUserByID(userID)
  196. if err != nil {
  197. c.ServerError("GetUserByID", err)
  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.SubURLRedirect("/user/login/two_factor")
  204. return
  205. }
  206. if err = c.Cache.Put(u.TwoFactorCacheKey(passcode), 1, 60); err != nil {
  207. log.Error(2, "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 := models.UseRecoveryCode(userID, c.Query("recovery_code")); err != nil {
  226. if errors.IsTwoFactorRecoveryCodeNotFound(err) {
  227. c.Flash.Error(c.Tr("auth.login_two_factor_invalid_recovery_code"))
  228. c.SubURLRedirect("/user/login/two_factor_recovery_code")
  229. } else {
  230. c.ServerError("UseRecoveryCode", err)
  231. }
  232. return
  233. }
  234. u, err := models.GetUserByID(userID)
  235. if err != nil {
  236. c.ServerError("GetUserByID", err)
  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(setting.CookieUserName, "", -1, setting.AppSubURL)
  245. c.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  246. c.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  247. c.SubURLRedirect("/")
  248. }
  249. func SignUp(c *context.Context) {
  250. c.Title("sign_up")
  251. c.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  252. if setting.Service.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"] = setting.Service.EnableCaptcha
  262. if setting.Service.DisableRegistration {
  263. c.Status(403)
  264. return
  265. }
  266. if c.HasError() {
  267. c.Success(SIGNUP)
  268. return
  269. }
  270. if setting.Service.EnableCaptcha && !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 := &models.User{
  281. Name: f.UserName,
  282. Email: f.Email,
  283. Passwd: f.Password,
  284. IsActive: !setting.Service.RegisterEmailConfirm,
  285. }
  286. if err := models.CreateUser(u); err != nil {
  287. switch {
  288. case models.IsErrUserAlreadyExist(err):
  289. c.FormErr("UserName")
  290. c.RenderWithErr(c.Tr("form.username_been_taken"), SIGNUP, &f)
  291. case models.IsErrEmailAlreadyUsed(err):
  292. c.FormErr("Email")
  293. c.RenderWithErr(c.Tr("form.email_been_used"), SIGNUP, &f)
  294. case models.IsErrNameReserved(err):
  295. c.FormErr("UserName")
  296. c.RenderWithErr(c.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f)
  297. case models.IsErrNamePatternNotAllowed(err):
  298. c.FormErr("UserName")
  299. c.RenderWithErr(c.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), SIGNUP, &f)
  300. default:
  301. c.ServerError("CreateUser", err)
  302. }
  303. return
  304. }
  305. log.Trace("Account created: %s", u.Name)
  306. // Auto-set admin for the only user.
  307. if models.CountUsers() == 1 {
  308. u.IsAdmin = true
  309. u.IsActive = true
  310. if err := models.UpdateUser(u); err != nil {
  311. c.ServerError("UpdateUser", err)
  312. return
  313. }
  314. }
  315. // Send confirmation email, no need for social account.
  316. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  317. mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(u))
  318. c.Data["IsSendRegisterMail"] = true
  319. c.Data["Email"] = u.Email
  320. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  321. c.Success(ACTIVATE)
  322. if err := c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
  323. log.Error(2, "Failed to put cache key 'mail resend': %v", err)
  324. }
  325. return
  326. }
  327. c.SubURLRedirect("/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 setting.Service.RegisterEmailConfirm {
  339. if c.Cache.IsExist(c.User.MailResendCacheKey()) {
  340. c.Data["ResendLimited"] = true
  341. } else {
  342. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  343. mailer.SendActivateAccountMail(c.Context, models.NewMailerUser(c.User))
  344. if err := c.Cache.Put(c.User.MailResendCacheKey(), 1, 180); err != nil {
  345. log.Error(2, "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 := models.VerifyUserActiveCode(code); user != nil {
  356. user.IsActive = true
  357. var err error
  358. if user.Rands, err = models.GetUserSalt(); err != nil {
  359. c.ServerError("GetUserSalt", err)
  360. return
  361. }
  362. if err := models.UpdateUser(user); err != nil {
  363. c.ServerError("UpdateUser", err)
  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.SubURLRedirect("/")
  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. email_string := c.Query("email")
  378. // Verify code.
  379. if email := models.VerifyActiveEmailCode(code, email_string); email != nil {
  380. if err := email.Activate(); err != nil {
  381. c.ServerError("ActivateEmail", err)
  382. }
  383. log.Trace("Email activated: %s", email.Email)
  384. c.Flash.Success(c.Tr("settings.add_email_success"))
  385. }
  386. c.SubURLRedirect("/user/settings/email")
  387. return
  388. }
  389. func ForgotPasswd(c *context.Context) {
  390. c.Title("auth.forgot_password")
  391. if setting.MailService == nil {
  392. c.Data["IsResetDisable"] = true
  393. c.Success(FORGOT_PASSWORD)
  394. return
  395. }
  396. c.Data["IsResetRequest"] = true
  397. c.Success(FORGOT_PASSWORD)
  398. }
  399. func ForgotPasswdPost(c *context.Context) {
  400. c.Title("auth.forgot_password")
  401. if setting.MailService == nil {
  402. c.Status(403)
  403. return
  404. }
  405. c.Data["IsResetRequest"] = true
  406. email := c.Query("email")
  407. c.Data["Email"] = email
  408. u, err := models.GetUserByEmail(email)
  409. if err != nil {
  410. if errors.IsUserNotExist(err) {
  411. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  412. c.Data["IsResetSent"] = true
  413. c.Success(FORGOT_PASSWORD)
  414. return
  415. } else {
  416. c.ServerError("GetUserByEmail", err)
  417. }
  418. return
  419. }
  420. if !u.IsLocal() {
  421. c.FormErr("Email")
  422. c.RenderWithErr(c.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
  423. return
  424. }
  425. if c.Cache.IsExist(u.MailResendCacheKey()) {
  426. c.Data["ResendLimited"] = true
  427. c.Success(FORGOT_PASSWORD)
  428. return
  429. }
  430. mailer.SendResetPasswordMail(c.Context, models.NewMailerUser(u))
  431. if err = c.Cache.Put(u.MailResendCacheKey(), 1, 180); err != nil {
  432. log.Error(2, "Failed to put cache key 'mail resend': %v", err)
  433. }
  434. c.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  435. c.Data["IsResetSent"] = true
  436. c.Success(FORGOT_PASSWORD)
  437. }
  438. func ResetPasswd(c *context.Context) {
  439. c.Title("auth.reset_password")
  440. code := c.Query("code")
  441. if len(code) == 0 {
  442. c.NotFound()
  443. return
  444. }
  445. c.Data["Code"] = code
  446. c.Data["IsResetForm"] = true
  447. c.Success(RESET_PASSWORD)
  448. }
  449. func ResetPasswdPost(c *context.Context) {
  450. c.Title("auth.reset_password")
  451. code := c.Query("code")
  452. if len(code) == 0 {
  453. c.NotFound()
  454. return
  455. }
  456. c.Data["Code"] = code
  457. if u := models.VerifyUserActiveCode(code); u != nil {
  458. // Validate password length.
  459. passwd := c.Query("password")
  460. if len(passwd) < 6 {
  461. c.Data["IsResetForm"] = true
  462. c.Data["Err_Password"] = true
  463. c.RenderWithErr(c.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  464. return
  465. }
  466. u.Passwd = passwd
  467. var err error
  468. if u.Rands, err = models.GetUserSalt(); err != nil {
  469. c.ServerError("GetUserSalt", err)
  470. return
  471. }
  472. if u.Salt, err = models.GetUserSalt(); err != nil {
  473. c.ServerError("GetUserSalt", err)
  474. return
  475. }
  476. u.EncodePasswd()
  477. if err := models.UpdateUser(u); err != nil {
  478. c.ServerError("UpdateUser", err)
  479. return
  480. }
  481. log.Trace("User password reset: %s", u.Name)
  482. c.SubURLRedirect("/user/login")
  483. return
  484. }
  485. c.Data["IsResetFailed"] = true
  486. c.Success(RESET_PASSWORD)
  487. }