auth.go 14 KB

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