auth.go 14 KB

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