auth.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. if err := email.Activate(); err != nil {
  303. ctx.Handle(500, "ActivateEmail", err)
  304. }
  305. log.Trace("Email activated: %s", email.Email)
  306. ctx.Flash.Success(ctx.Tr("settings.activate_email_success"))
  307. }
  308. ctx.Redirect(setting.AppSubUrl + "/user/settings/email")
  309. return
  310. }
  311. func ForgotPasswd(ctx *middleware.Context) {
  312. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  313. if setting.MailService == nil {
  314. ctx.Data["IsResetDisable"] = true
  315. ctx.HTML(200, FORGOT_PASSWORD)
  316. return
  317. }
  318. ctx.Data["IsResetRequest"] = true
  319. ctx.HTML(200, FORGOT_PASSWORD)
  320. }
  321. func ForgotPasswdPost(ctx *middleware.Context) {
  322. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  323. if setting.MailService == nil {
  324. ctx.Handle(403, "user.ForgotPasswdPost", nil)
  325. return
  326. }
  327. ctx.Data["IsResetRequest"] = true
  328. email := ctx.Query("email")
  329. u, err := models.GetUserByEmail(email)
  330. if err != nil {
  331. if err == models.ErrUserNotExist {
  332. ctx.Data["Err_Email"] = true
  333. ctx.RenderWithErr(ctx.Tr("auth.email_not_associate"), FORGOT_PASSWORD, nil)
  334. } else {
  335. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  336. }
  337. return
  338. }
  339. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  340. ctx.Data["ResendLimited"] = true
  341. ctx.HTML(200, FORGOT_PASSWORD)
  342. return
  343. }
  344. mailer.SendResetPasswdMail(ctx.Render, u)
  345. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  346. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  347. }
  348. ctx.Data["Email"] = email
  349. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  350. ctx.Data["IsResetSent"] = true
  351. ctx.HTML(200, FORGOT_PASSWORD)
  352. }
  353. func ResetPasswd(ctx *middleware.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. ctx.Data["IsResetForm"] = true
  362. ctx.HTML(200, RESET_PASSWORD)
  363. }
  364. func ResetPasswdPost(ctx *middleware.Context) {
  365. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  366. code := ctx.Query("code")
  367. if len(code) == 0 {
  368. ctx.Error(404)
  369. return
  370. }
  371. ctx.Data["Code"] = code
  372. if u := models.VerifyUserActiveCode(code); u != nil {
  373. // Validate password length.
  374. passwd := ctx.Query("password")
  375. if len(passwd) < 6 {
  376. ctx.Data["IsResetForm"] = true
  377. ctx.Data["Err_Password"] = true
  378. ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  379. return
  380. }
  381. u.Passwd = passwd
  382. u.Rands = models.GetUserSalt()
  383. u.Salt = models.GetUserSalt()
  384. u.EncodePasswd()
  385. if err := models.UpdateUser(u); err != nil {
  386. ctx.Handle(500, "UpdateUser", err)
  387. return
  388. }
  389. log.Trace("User password reset: %s", u.Name)
  390. ctx.Redirect(setting.AppSubUrl + "/user/login")
  391. return
  392. }
  393. ctx.Data["IsResetFailed"] = true
  394. ctx.HTML(200, RESET_PASSWORD)
  395. }