auth.go 11 KB

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