auth.go 14 KB

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