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.

446 lines
11 KiB

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