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.

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