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.

425 lines
11 KiB

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