You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

462 lines
12 KiB

9 years ago
9 years ago
  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. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/auth"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. )
  16. const (
  17. // tplSignIn template for sign in page
  18. tplSignIn base.TplName = "user/auth/signin"
  19. // tplSignUp template path for sign up page
  20. tplSignUp base.TplName = "user/auth/signup"
  21. // TplActivate template path for activate user
  22. TplActivate base.TplName = "user/auth/activate"
  23. tplForgotPassword base.TplName = "user/auth/forgot_passwd"
  24. tplResetPassword base.TplName = "user/auth/reset_passwd"
  25. )
  26. // AutoSignIn reads cookie and try to auto-login.
  27. func AutoSignIn(ctx *context.Context) (bool, error) {
  28. if !models.HasEngine {
  29. return false, nil
  30. }
  31. uname := ctx.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. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  40. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  41. }
  42. }()
  43. u, err := models.GetUserByName(uname)
  44. if err != nil {
  45. if !models.IsErrUserNotExist(err) {
  46. return false, fmt.Errorf("GetUserByName: %v", err)
  47. }
  48. return false, nil
  49. }
  50. if val, _ := ctx.GetSuperSecureCookie(
  51. base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name {
  52. return false, nil
  53. }
  54. isSucceed = true
  55. ctx.Session.Set("uid", u.ID)
  56. ctx.Session.Set("uname", u.Name)
  57. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  58. return true, nil
  59. }
  60. // SignIn render sign in page
  61. func SignIn(ctx *context.Context) {
  62. ctx.Data["Title"] = ctx.Tr("sign_in")
  63. // Check auto-login.
  64. isSucceed, err := AutoSignIn(ctx)
  65. if err != nil {
  66. ctx.Handle(500, "AutoSignIn", err)
  67. return
  68. }
  69. redirectTo := ctx.Query("redirect_to")
  70. if len(redirectTo) > 0 {
  71. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL)
  72. } else {
  73. redirectTo, _ = url.QueryUnescape(ctx.GetCookie("redirect_to"))
  74. }
  75. if isSucceed {
  76. if len(redirectTo) > 0 {
  77. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  78. ctx.Redirect(redirectTo)
  79. } else {
  80. ctx.Redirect(setting.AppSubURL + "/")
  81. }
  82. return
  83. }
  84. ctx.HTML(200, tplSignIn)
  85. }
  86. // SignInPost response for sign in request
  87. func SignInPost(ctx *context.Context, form auth.SignInForm) {
  88. ctx.Data["Title"] = ctx.Tr("sign_in")
  89. if ctx.HasError() {
  90. ctx.HTML(200, tplSignIn)
  91. return
  92. }
  93. u, err := models.UserSignIn(form.UserName, form.Password)
  94. if err != nil {
  95. if models.IsErrUserNotExist(err) {
  96. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form)
  97. } else {
  98. ctx.Handle(500, "UserSignIn", err)
  99. }
  100. return
  101. }
  102. if form.Remember {
  103. days := 86400 * setting.LogInRememberDays
  104. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL)
  105. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  106. setting.CookieRememberName, u.Name, days, setting.AppSubURL)
  107. }
  108. ctx.Session.Set("uid", u.ID)
  109. ctx.Session.Set("uname", u.Name)
  110. // Clear whatever CSRF has right now, force to generate a new one
  111. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  112. // Register last login
  113. u.SetLastLogin()
  114. if err := models.UpdateUser(u); err != nil {
  115. ctx.Handle(500, "UpdateUser", err)
  116. return
  117. }
  118. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  119. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  120. ctx.Redirect(redirectTo)
  121. return
  122. }
  123. ctx.Redirect(setting.AppSubURL + "/")
  124. }
  125. // SignOut sign out from login status
  126. func SignOut(ctx *context.Context) {
  127. ctx.Session.Delete("uid")
  128. ctx.Session.Delete("uname")
  129. ctx.Session.Delete("socialId")
  130. ctx.Session.Delete("socialName")
  131. ctx.Session.Delete("socialEmail")
  132. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  133. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  134. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  135. ctx.Redirect(setting.AppSubURL + "/")
  136. }
  137. // SignUp render the register page
  138. func SignUp(ctx *context.Context) {
  139. ctx.Data["Title"] = ctx.Tr("sign_up")
  140. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  141. if setting.Service.DisableRegistration {
  142. ctx.Data["DisableRegistration"] = true
  143. ctx.HTML(200, tplSignUp)
  144. return
  145. }
  146. ctx.HTML(200, tplSignUp)
  147. }
  148. // SignUpPost response for sign up information submission
  149. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  150. ctx.Data["Title"] = ctx.Tr("sign_up")
  151. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  152. if setting.Service.DisableRegistration {
  153. ctx.Error(403)
  154. return
  155. }
  156. if ctx.HasError() {
  157. ctx.HTML(200, tplSignUp)
  158. return
  159. }
  160. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  161. ctx.Data["Err_Captcha"] = true
  162. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  163. return
  164. }
  165. if form.Password != form.Retype {
  166. ctx.Data["Err_Password"] = true
  167. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  168. return
  169. }
  170. if len(form.Password) < setting.MinPasswordLength {
  171. ctx.Data["Err_Password"] = true
  172. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
  173. return
  174. }
  175. u := &models.User{
  176. Name: form.UserName,
  177. Email: form.Email,
  178. Passwd: form.Password,
  179. IsActive: !setting.Service.RegisterEmailConfirm,
  180. }
  181. if err := models.CreateUser(u); err != nil {
  182. switch {
  183. case models.IsErrUserAlreadyExist(err):
  184. ctx.Data["Err_UserName"] = true
  185. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  186. case models.IsErrEmailAlreadyUsed(err):
  187. ctx.Data["Err_Email"] = true
  188. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  189. case models.IsErrNameReserved(err):
  190. ctx.Data["Err_UserName"] = true
  191. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  192. case models.IsErrNamePatternNotAllowed(err):
  193. ctx.Data["Err_UserName"] = true
  194. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  195. default:
  196. ctx.Handle(500, "CreateUser", err)
  197. }
  198. return
  199. }
  200. log.Trace("Account created: %s", u.Name)
  201. // Auto-set admin for the only user.
  202. if models.CountUsers() == 1 {
  203. u.IsAdmin = true
  204. u.IsActive = true
  205. if err := models.UpdateUser(u); err != nil {
  206. ctx.Handle(500, "UpdateUser", err)
  207. return
  208. }
  209. }
  210. // Send confirmation email, no need for social account.
  211. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  212. models.SendActivateAccountMail(ctx.Context, u)
  213. ctx.Data["IsSendRegisterMail"] = true
  214. ctx.Data["Email"] = u.Email
  215. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  216. ctx.HTML(200, TplActivate)
  217. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  218. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  219. }
  220. return
  221. }
  222. ctx.Redirect(setting.AppSubURL + "/user/login")
  223. }
  224. // Activate render activate user page
  225. func Activate(ctx *context.Context) {
  226. code := ctx.Query("code")
  227. if len(code) == 0 {
  228. ctx.Data["IsActivatePage"] = true
  229. if ctx.User.IsActive {
  230. ctx.Error(404)
  231. return
  232. }
  233. // Resend confirmation email.
  234. if setting.Service.RegisterEmailConfirm {
  235. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  236. ctx.Data["ResendLimited"] = true
  237. } else {
  238. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  239. models.SendActivateAccountMail(ctx.Context, ctx.User)
  240. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  241. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  242. }
  243. }
  244. } else {
  245. ctx.Data["ServiceNotEnabled"] = true
  246. }
  247. ctx.HTML(200, TplActivate)
  248. return
  249. }
  250. // Verify code.
  251. if user := models.VerifyUserActiveCode(code); user != nil {
  252. user.IsActive = true
  253. var err error
  254. if user.Rands, err = models.GetUserSalt(); err != nil {
  255. ctx.Handle(500, "UpdateUser", err)
  256. return
  257. }
  258. if err := models.UpdateUser(user); err != nil {
  259. if models.IsErrUserNotExist(err) {
  260. ctx.Error(404)
  261. } else {
  262. ctx.Handle(500, "UpdateUser", err)
  263. }
  264. return
  265. }
  266. log.Trace("User activated: %s", user.Name)
  267. ctx.Session.Set("uid", user.ID)
  268. ctx.Session.Set("uname", user.Name)
  269. ctx.Redirect(setting.AppSubURL + "/")
  270. return
  271. }
  272. ctx.Data["IsActivateFailed"] = true
  273. ctx.HTML(200, TplActivate)
  274. }
  275. // ActivateEmail render the activate email page
  276. func ActivateEmail(ctx *context.Context) {
  277. code := ctx.Query("code")
  278. emailStr := ctx.Query("email")
  279. // Verify code.
  280. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  281. if err := email.Activate(); err != nil {
  282. ctx.Handle(500, "ActivateEmail", err)
  283. }
  284. log.Trace("Email activated: %s", email.Email)
  285. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  286. }
  287. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  288. return
  289. }
  290. // ForgotPasswd render the forget pasword page
  291. func ForgotPasswd(ctx *context.Context) {
  292. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  293. if setting.MailService == nil {
  294. ctx.Data["IsResetDisable"] = true
  295. ctx.HTML(200, tplForgotPassword)
  296. return
  297. }
  298. ctx.Data["IsResetRequest"] = true
  299. ctx.HTML(200, tplForgotPassword)
  300. }
  301. // ForgotPasswdPost response for forget password request
  302. func ForgotPasswdPost(ctx *context.Context) {
  303. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  304. if setting.MailService == nil {
  305. ctx.Handle(403, "ForgotPasswdPost", nil)
  306. return
  307. }
  308. ctx.Data["IsResetRequest"] = true
  309. email := ctx.Query("email")
  310. ctx.Data["Email"] = email
  311. u, err := models.GetUserByEmail(email)
  312. if err != nil {
  313. if models.IsErrUserNotExist(err) {
  314. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  315. ctx.Data["IsResetSent"] = true
  316. ctx.HTML(200, tplForgotPassword)
  317. return
  318. }
  319. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  320. return
  321. }
  322. if !u.IsLocal() {
  323. ctx.Data["Err_Email"] = true
  324. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  325. return
  326. }
  327. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  328. ctx.Data["ResendLimited"] = true
  329. ctx.HTML(200, tplForgotPassword)
  330. return
  331. }
  332. models.SendResetPasswordMail(ctx.Context, u)
  333. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  334. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  335. }
  336. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  337. ctx.Data["IsResetSent"] = true
  338. ctx.HTML(200, tplForgotPassword)
  339. }
  340. // ResetPasswd render the reset password page
  341. func ResetPasswd(ctx *context.Context) {
  342. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  343. code := ctx.Query("code")
  344. if len(code) == 0 {
  345. ctx.Error(404)
  346. return
  347. }
  348. ctx.Data["Code"] = code
  349. ctx.Data["IsResetForm"] = true
  350. ctx.HTML(200, tplResetPassword)
  351. }
  352. // ResetPasswdPost response from reset password request
  353. func ResetPasswdPost(ctx *context.Context) {
  354. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  355. code := ctx.Query("code")
  356. if len(code) == 0 {
  357. ctx.Error(404)
  358. return
  359. }
  360. ctx.Data["Code"] = code
  361. if u := models.VerifyUserActiveCode(code); u != nil {
  362. // Validate password length.
  363. passwd := ctx.Query("password")
  364. if len(passwd) < setting.MinPasswordLength {
  365. ctx.Data["IsResetForm"] = true
  366. ctx.Data["Err_Password"] = true
  367. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplResetPassword, nil)
  368. return
  369. }
  370. u.Passwd = passwd
  371. var err error
  372. if u.Rands, err = models.GetUserSalt(); err != nil {
  373. ctx.Handle(500, "UpdateUser", err)
  374. return
  375. }
  376. if u.Salt, err = models.GetUserSalt(); err != nil {
  377. ctx.Handle(500, "UpdateUser", err)
  378. return
  379. }
  380. u.EncodePasswd()
  381. if err := models.UpdateUser(u); err != nil {
  382. ctx.Handle(500, "UpdateUser", err)
  383. return
  384. }
  385. log.Trace("User password reset: %s", u.Name)
  386. ctx.Redirect(setting.AppSubURL + "/user/login")
  387. return
  388. }
  389. ctx.Data["IsResetFailed"] = true
  390. ctx.HTML(200, tplResetPassword)
  391. }