auth.go 13 KB

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