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.

469 lines
12 KiB

10 years ago
10 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. "net/url"
  7. "strings"
  8. "github.com/macaron-contrib/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/log"
  13. "github.com/gogits/gogs/modules/mailer"
  14. "github.com/gogits/gogs/modules/middleware"
  15. "github.com/gogits/gogs/modules/setting"
  16. )
  17. const (
  18. SIGNIN base.TplName = "user/auth/signin"
  19. SIGNUP base.TplName = "user/auth/signup"
  20. ACTIVATE base.TplName = "user/auth/activate"
  21. FORGOT_PASSWORD base.TplName = "user/auth/forgot_passwd"
  22. RESET_PASSWORD base.TplName = "user/auth/reset_passwd"
  23. )
  24. func SignIn(ctx *middleware.Context) {
  25. ctx.Data["Title"] = ctx.Tr("sign_in")
  26. if _, ok := ctx.Session.Get("socialId").(int64); ok {
  27. ctx.Data["IsSocialLogin"] = true
  28. ctx.HTML(200, SIGNIN)
  29. return
  30. }
  31. if setting.OauthService != nil {
  32. ctx.Data["OauthEnabled"] = true
  33. ctx.Data["OauthService"] = setting.OauthService
  34. }
  35. // Check auto-login.
  36. uname := ctx.GetCookie(setting.CookieUserName)
  37. if len(uname) == 0 {
  38. ctx.HTML(200, SIGNIN)
  39. return
  40. }
  41. isSucceed := false
  42. defer func() {
  43. if !isSucceed {
  44. log.Trace("auto-login cookie cleared: %s", uname)
  45. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl)
  46. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl)
  47. return
  48. }
  49. }()
  50. u, err := models.GetUserByName(uname)
  51. if err != nil {
  52. if err != models.ErrUserNotExist {
  53. ctx.Handle(500, "GetUserByName", err)
  54. } else {
  55. ctx.HTML(200, SIGNIN)
  56. }
  57. return
  58. }
  59. if val, _ := ctx.GetSuperSecureCookie(
  60. base.EncodeMd5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name {
  61. ctx.HTML(200, SIGNIN)
  62. return
  63. }
  64. isSucceed = true
  65. ctx.Session.Set("uid", u.Id)
  66. ctx.Session.Set("uname", u.Name)
  67. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  68. ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl)
  69. ctx.Redirect(redirectTo)
  70. return
  71. }
  72. ctx.Redirect(setting.AppSubUrl + "/")
  73. }
  74. func SignInPost(ctx *middleware.Context, form auth.SignInForm) {
  75. ctx.Data["Title"] = ctx.Tr("sign_in")
  76. sid, isOauth := ctx.Session.Get("socialId").(int64)
  77. if isOauth {
  78. ctx.Data["IsSocialLogin"] = true
  79. } else if setting.OauthService != nil {
  80. ctx.Data["OauthEnabled"] = true
  81. ctx.Data["OauthService"] = setting.OauthService
  82. }
  83. if ctx.HasError() {
  84. ctx.HTML(200, SIGNIN)
  85. return
  86. }
  87. u, err := models.UserSignIn(form.UserName, form.Password)
  88. if err != nil {
  89. if err == models.ErrUserNotExist {
  90. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), SIGNIN, &form)
  91. } else {
  92. ctx.Handle(500, "UserSignIn", err)
  93. }
  94. return
  95. }
  96. if form.Remember {
  97. days := 86400 * setting.LogInRememberDays
  98. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubUrl)
  99. ctx.SetSuperSecureCookie(base.EncodeMd5(u.Rands+u.Passwd),
  100. setting.CookieRememberName, u.Name, days, setting.AppSubUrl)
  101. }
  102. // Bind with social account.
  103. if isOauth {
  104. if err = models.BindUserOauth2(u.Id, sid); err != nil {
  105. if err == models.ErrOauth2RecordNotExist {
  106. ctx.Handle(404, "GetOauth2ById", err)
  107. } else {
  108. ctx.Handle(500, "GetOauth2ById", err)
  109. }
  110. return
  111. }
  112. ctx.Session.Delete("socialId")
  113. log.Trace("%s OAuth binded: %s -> %d", ctx.Req.RequestURI, form.UserName, sid)
  114. }
  115. ctx.Session.Set("uid", u.Id)
  116. ctx.Session.Set("uname", u.Name)
  117. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  118. ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl)
  119. ctx.Redirect(redirectTo)
  120. return
  121. }
  122. ctx.Redirect(setting.AppSubUrl + "/")
  123. }
  124. func SignOut(ctx *middleware.Context) {
  125. ctx.Session.Delete("uid")
  126. ctx.Session.Delete("uname")
  127. ctx.Session.Delete("socialId")
  128. ctx.Session.Delete("socialName")
  129. ctx.Session.Delete("socialEmail")
  130. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl)
  131. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl)
  132. ctx.Redirect(setting.AppSubUrl + "/")
  133. }
  134. func oauthSignUp(ctx *middleware.Context, sid int64) {
  135. ctx.Data["Title"] = ctx.Tr("sign_up")
  136. if _, err := models.GetOauth2ById(sid); err != nil {
  137. if err == models.ErrOauth2RecordNotExist {
  138. ctx.Handle(404, "GetOauth2ById", err)
  139. } else {
  140. ctx.Handle(500, "GetOauth2ById", err)
  141. }
  142. return
  143. }
  144. ctx.Data["IsSocialLogin"] = true
  145. ctx.Data["uname"] = strings.Replace(ctx.Session.Get("socialName").(string), " ", "", -1)
  146. ctx.Data["email"] = ctx.Session.Get("socialEmail")
  147. log.Trace("social ID: %v", ctx.Session.Get("socialId"))
  148. ctx.HTML(200, SIGNUP)
  149. }
  150. func SignUp(ctx *middleware.Context) {
  151. ctx.Data["Title"] = ctx.Tr("sign_up")
  152. if setting.Service.DisableRegistration {
  153. ctx.Data["DisableRegistration"] = true
  154. ctx.HTML(200, SIGNUP)
  155. return
  156. }
  157. if sid, ok := ctx.Session.Get("socialId").(int64); ok {
  158. oauthSignUp(ctx, sid)
  159. return
  160. }
  161. ctx.HTML(200, SIGNUP)
  162. }
  163. func SignUpPost(ctx *middleware.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  164. ctx.Data["Title"] = ctx.Tr("sign_up")
  165. if setting.Service.DisableRegistration {
  166. ctx.Error(403)
  167. return
  168. }
  169. isOauth := false
  170. sid, isOauth := ctx.Session.Get("socialId").(int64)
  171. if isOauth {
  172. ctx.Data["IsSocialLogin"] = true
  173. }
  174. // May redirect from home page.
  175. if ctx.Query("from") == "home" {
  176. // Clear input error box.
  177. ctx.Data["Err_UserName"] = false
  178. ctx.Data["Err_Email"] = false
  179. // Make the best guess.
  180. uname := ctx.Query("uname")
  181. i := strings.Index(uname, "@")
  182. if i > -1 {
  183. ctx.Data["email"] = uname
  184. ctx.Data["uname"] = uname[:i]
  185. } else {
  186. ctx.Data["uname"] = uname
  187. }
  188. ctx.Data["password"] = ctx.Query("password")
  189. ctx.HTML(200, SIGNUP)
  190. return
  191. }
  192. if ctx.HasError() {
  193. ctx.HTML(200, SIGNUP)
  194. return
  195. }
  196. if !cpt.VerifyReq(ctx.Req) {
  197. ctx.Data["Err_Captcha"] = true
  198. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), SIGNUP, &form)
  199. return
  200. } else if form.Password != form.Retype {
  201. ctx.Data["Err_Password"] = true
  202. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &form)
  203. return
  204. }
  205. u := &models.User{
  206. Name: form.UserName,
  207. Email: form.Email,
  208. Passwd: form.Password,
  209. IsActive: !setting.Service.RegisterEmailConfirm || isOauth,
  210. }
  211. if err := models.CreateUser(u); err != nil {
  212. switch err {
  213. case models.ErrUserAlreadyExist:
  214. ctx.Data["Err_UserName"] = true
  215. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SIGNUP, &form)
  216. case models.ErrEmailAlreadyUsed:
  217. ctx.Data["Err_Email"] = true
  218. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &form)
  219. case models.ErrUserNameIllegal:
  220. ctx.Data["Err_UserName"] = true
  221. ctx.RenderWithErr(ctx.Tr("form.illegal_username"), SIGNUP, &form)
  222. default:
  223. ctx.Handle(500, "CreateUser", err)
  224. }
  225. return
  226. }
  227. log.Trace("Account created: %s", u.Name)
  228. // Bind social account.
  229. if isOauth {
  230. if err := models.BindUserOauth2(u.Id, sid); err != nil {
  231. ctx.Handle(500, "BindUserOauth2", err)
  232. return
  233. }
  234. ctx.Session.Delete("socialId")
  235. log.Trace("%s OAuth binded: %s -> %d", ctx.Req.RequestURI, form.UserName, sid)
  236. }
  237. // Send confirmation e-mail, no need for social account.
  238. if !isOauth && setting.Service.RegisterEmailConfirm && u.Id > 1 {
  239. mailer.SendRegisterMail(ctx.Render, u)
  240. ctx.Data["IsSendRegisterMail"] = true
  241. ctx.Data["Email"] = u.Email
  242. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  243. ctx.HTML(200, ACTIVATE)
  244. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  245. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  246. }
  247. return
  248. }
  249. ctx.Redirect(setting.AppSubUrl + "/user/login")
  250. }
  251. func Activate(ctx *middleware.Context) {
  252. code := ctx.Query("code")
  253. if len(code) == 0 {
  254. ctx.Data["IsActivatePage"] = true
  255. if ctx.User.IsActive {
  256. ctx.Error(404)
  257. return
  258. }
  259. // Resend confirmation e-mail.
  260. if setting.Service.RegisterEmailConfirm {
  261. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  262. ctx.Data["ResendLimited"] = true
  263. } else {
  264. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  265. mailer.SendActiveMail(ctx.Render, ctx.User)
  266. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  267. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  268. }
  269. }
  270. } else {
  271. ctx.Data["ServiceNotEnabled"] = true
  272. }
  273. ctx.HTML(200, ACTIVATE)
  274. return
  275. }
  276. // Verify code.
  277. if user := models.VerifyUserActiveCode(code); user != nil {
  278. user.IsActive = true
  279. user.Rands = models.GetUserSalt()
  280. if err := models.UpdateUser(user); err != nil {
  281. if err == models.ErrUserNotExist {
  282. ctx.Error(404)
  283. } else {
  284. ctx.Handle(500, "UpdateUser", err)
  285. }
  286. return
  287. }
  288. log.Trace("User activated: %s", user.Name)
  289. ctx.Session.Set("uid", user.Id)
  290. ctx.Session.Set("uname", user.Name)
  291. ctx.Redirect(setting.AppSubUrl + "/")
  292. return
  293. }
  294. ctx.Data["IsActivateFailed"] = true
  295. ctx.HTML(200, ACTIVATE)
  296. }
  297. func ActivateEmail(ctx *middleware.Context) {
  298. code := ctx.Query("code")
  299. email_string := ctx.Query("email")
  300. // Verify code.
  301. if email := models.VerifyActiveEmailCode(code, email_string); email != nil {
  302. err := email.Activate()
  303. if err != nil {
  304. ctx.Handle(500, "ActivateEmail", err)
  305. }
  306. log.Trace("Email activated: %s", email.Email)
  307. ctx.Flash.Success(ctx.Tr("settings.activate_email_success"))
  308. }
  309. ctx.Redirect(setting.AppSubUrl + "/user/settings/email")
  310. return
  311. }
  312. func ForgotPasswd(ctx *middleware.Context) {
  313. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  314. if setting.MailService == nil {
  315. ctx.Data["IsResetDisable"] = true
  316. ctx.HTML(200, FORGOT_PASSWORD)
  317. return
  318. }
  319. ctx.Data["IsResetRequest"] = true
  320. ctx.HTML(200, FORGOT_PASSWORD)
  321. }
  322. func ForgotPasswdPost(ctx *middleware.Context) {
  323. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  324. if setting.MailService == nil {
  325. ctx.Handle(403, "user.ForgotPasswdPost", nil)
  326. return
  327. }
  328. ctx.Data["IsResetRequest"] = true
  329. email := ctx.Query("email")
  330. u, err := models.GetUserByEmail(email)
  331. if err != nil {
  332. if err == models.ErrUserNotExist {
  333. ctx.Data["Err_Email"] = true
  334. ctx.RenderWithErr(ctx.Tr("auth.email_not_associate"), FORGOT_PASSWORD, nil)
  335. } else {
  336. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  337. }
  338. return
  339. }
  340. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  341. ctx.Data["ResendLimited"] = true
  342. ctx.HTML(200, FORGOT_PASSWORD)
  343. return
  344. }
  345. mailer.SendResetPasswdMail(ctx.Render, u)
  346. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  347. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  348. }
  349. ctx.Data["Email"] = email
  350. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  351. ctx.Data["IsResetSent"] = true
  352. ctx.HTML(200, FORGOT_PASSWORD)
  353. }
  354. func ResetPasswd(ctx *middleware.Context) {
  355. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  356. code := ctx.Query("code")
  357. if len(code) == 0 {
  358. ctx.Error(404)
  359. return
  360. }
  361. ctx.Data["Code"] = code
  362. ctx.Data["IsResetForm"] = true
  363. ctx.HTML(200, RESET_PASSWORD)
  364. }
  365. func ResetPasswdPost(ctx *middleware.Context) {
  366. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  367. code := ctx.Query("code")
  368. if len(code) == 0 {
  369. ctx.Error(404)
  370. return
  371. }
  372. ctx.Data["Code"] = code
  373. if u := models.VerifyUserActiveCode(code); u != nil {
  374. // Validate password length.
  375. passwd := ctx.Query("password")
  376. if len(passwd) < 6 {
  377. ctx.Data["IsResetForm"] = true
  378. ctx.Data["Err_Password"] = true
  379. ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  380. return
  381. }
  382. u.Passwd = passwd
  383. u.Rands = models.GetUserSalt()
  384. u.Salt = models.GetUserSalt()
  385. u.EncodePasswd()
  386. if err := models.UpdateUser(u); err != nil {
  387. ctx.Handle(500, "UpdateUser", err)
  388. return
  389. }
  390. log.Trace("User password reset: %s", u.Name)
  391. ctx.Redirect(setting.AppSubUrl + "/user/login")
  392. return
  393. }
  394. ctx.Data["IsResetFailed"] = true
  395. ctx.HTML(200, RESET_PASSWORD)
  396. }