Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

auth.go 12KB

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. "fmt"
  7. "net/url"
  8. "github.com/go-macaron/captcha"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/auth"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. )
  16. const (
  17. // tplSignIn template for sign in page
  18. tplSignIn base.TplName = "user/auth/signin"
  19. // tplSignUp template path for sign up page
  20. tplSignUp base.TplName = "user/auth/signup"
  21. // TplActivate template path for activate user
  22. TplActivate base.TplName = "user/auth/activate"
  23. tplForgotPassword base.TplName = "user/auth/forgot_passwd"
  24. tplResetPassword base.TplName = "user/auth/reset_passwd"
  25. )
  26. // AutoSignIn reads cookie and try to auto-login.
  27. func AutoSignIn(ctx *context.Context) (bool, error) {
  28. if !models.HasEngine {
  29. return false, nil
  30. }
  31. uname := ctx.GetCookie(setting.CookieUserName)
  32. if len(uname) == 0 {
  33. return false, nil
  34. }
  35. isSucceed := false
  36. defer func() {
  37. if !isSucceed {
  38. log.Trace("auto-login cookie cleared: %s", uname)
  39. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  40. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  41. }
  42. }()
  43. u, err := models.GetUserByName(uname)
  44. if err != nil {
  45. if !models.IsErrUserNotExist(err) {
  46. return false, fmt.Errorf("GetUserByName: %v", err)
  47. }
  48. return false, nil
  49. }
  50. if val, _ := ctx.GetSuperSecureCookie(
  51. base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name {
  52. return false, nil
  53. }
  54. isSucceed = true
  55. ctx.Session.Set("uid", u.ID)
  56. ctx.Session.Set("uname", u.Name)
  57. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  58. return true, nil
  59. }
  60. // SignIn render sign in page
  61. func SignIn(ctx *context.Context) {
  62. ctx.Data["Title"] = ctx.Tr("sign_in")
  63. // Check auto-login.
  64. isSucceed, err := AutoSignIn(ctx)
  65. if err != nil {
  66. ctx.Handle(500, "AutoSignIn", err)
  67. return
  68. }
  69. redirectTo := ctx.Query("redirect_to")
  70. if len(redirectTo) > 0 {
  71. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL)
  72. } else {
  73. redirectTo, _ = url.QueryUnescape(ctx.GetCookie("redirect_to"))
  74. }
  75. if isSucceed {
  76. if len(redirectTo) > 0 {
  77. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  78. ctx.Redirect(redirectTo)
  79. } else {
  80. ctx.Redirect(setting.AppSubURL + "/")
  81. }
  82. return
  83. }
  84. ctx.HTML(200, tplSignIn)
  85. }
  86. // SignInPost response for sign in request
  87. func SignInPost(ctx *context.Context, form auth.SignInForm) {
  88. ctx.Data["Title"] = ctx.Tr("sign_in")
  89. if ctx.HasError() {
  90. ctx.HTML(200, tplSignIn)
  91. return
  92. }
  93. u, err := models.UserSignIn(form.UserName, form.Password)
  94. if err != nil {
  95. if models.IsErrUserNotExist(err) {
  96. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form)
  97. } else {
  98. ctx.Handle(500, "UserSignIn", err)
  99. }
  100. return
  101. }
  102. if form.Remember {
  103. days := 86400 * setting.LogInRememberDays
  104. ctx.SetCookie(setting.CookieUserName, u.Name, days, setting.AppSubURL)
  105. ctx.SetSuperSecureCookie(base.EncodeMD5(u.Rands+u.Passwd),
  106. setting.CookieRememberName, u.Name, days, setting.AppSubURL)
  107. }
  108. ctx.Session.Set("uid", u.ID)
  109. ctx.Session.Set("uname", u.Name)
  110. // Clear whatever CSRF has right now, force to generate a new one
  111. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  112. // Register last login
  113. u.SetLastLogin()
  114. if err := models.UpdateUser(u); err != nil {
  115. ctx.Handle(500, "UpdateUser", err)
  116. return
  117. }
  118. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  119. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL)
  120. ctx.Redirect(redirectTo)
  121. return
  122. }
  123. ctx.Redirect(setting.AppSubURL + "/")
  124. }
  125. // SignOut sign out from login status
  126. func SignOut(ctx *context.Context) {
  127. ctx.Session.Delete("uid")
  128. ctx.Session.Delete("uname")
  129. ctx.Session.Delete("socialId")
  130. ctx.Session.Delete("socialName")
  131. ctx.Session.Delete("socialEmail")
  132. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubURL)
  133. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubURL)
  134. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubURL)
  135. ctx.Redirect(setting.AppSubURL + "/")
  136. }
  137. // SignUp render the register page
  138. func SignUp(ctx *context.Context) {
  139. ctx.Data["Title"] = ctx.Tr("sign_up")
  140. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  141. if setting.Service.DisableRegistration {
  142. ctx.Data["DisableRegistration"] = true
  143. ctx.HTML(200, tplSignUp)
  144. return
  145. }
  146. ctx.HTML(200, tplSignUp)
  147. }
  148. // SignUpPost response for sign up information submission
  149. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, form auth.RegisterForm) {
  150. ctx.Data["Title"] = ctx.Tr("sign_up")
  151. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  152. if setting.Service.DisableRegistration {
  153. ctx.Error(403)
  154. return
  155. }
  156. if ctx.HasError() {
  157. ctx.HTML(200, tplSignUp)
  158. return
  159. }
  160. if setting.Service.EnableCaptcha && !cpt.VerifyReq(ctx.Req) {
  161. ctx.Data["Err_Captcha"] = true
  162. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form)
  163. return
  164. }
  165. if form.Password != form.Retype {
  166. ctx.Data["Err_Password"] = true
  167. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
  168. return
  169. }
  170. u := &models.User{
  171. Name: form.UserName,
  172. Email: form.Email,
  173. Passwd: form.Password,
  174. IsActive: !setting.Service.RegisterEmailConfirm,
  175. }
  176. if err := models.CreateUser(u); err != nil {
  177. switch {
  178. case models.IsErrUserAlreadyExist(err):
  179. ctx.Data["Err_UserName"] = true
  180. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUp, &form)
  181. case models.IsErrEmailAlreadyUsed(err):
  182. ctx.Data["Err_Email"] = true
  183. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUp, &form)
  184. case models.IsErrNameReserved(err):
  185. ctx.Data["Err_UserName"] = true
  186. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUp, &form)
  187. case models.IsErrNamePatternNotAllowed(err):
  188. ctx.Data["Err_UserName"] = true
  189. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUp, &form)
  190. default:
  191. ctx.Handle(500, "CreateUser", err)
  192. }
  193. return
  194. }
  195. log.Trace("Account created: %s", u.Name)
  196. // Auto-set admin for the only user.
  197. if models.CountUsers() == 1 {
  198. u.IsAdmin = true
  199. u.IsActive = true
  200. if err := models.UpdateUser(u); err != nil {
  201. ctx.Handle(500, "UpdateUser", err)
  202. return
  203. }
  204. }
  205. // Send confirmation email, no need for social account.
  206. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  207. models.SendActivateAccountMail(ctx.Context, u)
  208. ctx.Data["IsSendRegisterMail"] = true
  209. ctx.Data["Email"] = u.Email
  210. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  211. ctx.HTML(200, TplActivate)
  212. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  213. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  214. }
  215. return
  216. }
  217. ctx.Redirect(setting.AppSubURL + "/user/login")
  218. }
  219. // Activate render activate user page
  220. func Activate(ctx *context.Context) {
  221. code := ctx.Query("code")
  222. if len(code) == 0 {
  223. ctx.Data["IsActivatePage"] = true
  224. if ctx.User.IsActive {
  225. ctx.Error(404)
  226. return
  227. }
  228. // Resend confirmation email.
  229. if setting.Service.RegisterEmailConfirm {
  230. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  231. ctx.Data["ResendLimited"] = true
  232. } else {
  233. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  234. models.SendActivateAccountMail(ctx.Context, ctx.User)
  235. if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil {
  236. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  237. }
  238. }
  239. } else {
  240. ctx.Data["ServiceNotEnabled"] = true
  241. }
  242. ctx.HTML(200, TplActivate)
  243. return
  244. }
  245. // Verify code.
  246. if user := models.VerifyUserActiveCode(code); user != nil {
  247. user.IsActive = true
  248. user.Rands = models.GetUserSalt()
  249. if err := models.UpdateUser(user); err != nil {
  250. if models.IsErrUserNotExist(err) {
  251. ctx.Error(404)
  252. } else {
  253. ctx.Handle(500, "UpdateUser", err)
  254. }
  255. return
  256. }
  257. log.Trace("User activated: %s", user.Name)
  258. ctx.Session.Set("uid", user.ID)
  259. ctx.Session.Set("uname", user.Name)
  260. ctx.Redirect(setting.AppSubURL + "/")
  261. return
  262. }
  263. ctx.Data["IsActivateFailed"] = true
  264. ctx.HTML(200, TplActivate)
  265. }
  266. // ActivateEmail render the activate email page
  267. func ActivateEmail(ctx *context.Context) {
  268. code := ctx.Query("code")
  269. emailStr := ctx.Query("email")
  270. // Verify code.
  271. if email := models.VerifyActiveEmailCode(code, emailStr); email != nil {
  272. if err := email.Activate(); err != nil {
  273. ctx.Handle(500, "ActivateEmail", err)
  274. }
  275. log.Trace("Email activated: %s", email.Email)
  276. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  277. }
  278. ctx.Redirect(setting.AppSubURL + "/user/settings/email")
  279. return
  280. }
  281. // ForgotPasswd render the forget pasword page
  282. func ForgotPasswd(ctx *context.Context) {
  283. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  284. if setting.MailService == nil {
  285. ctx.Data["IsResetDisable"] = true
  286. ctx.HTML(200, tplForgotPassword)
  287. return
  288. }
  289. ctx.Data["IsResetRequest"] = true
  290. ctx.HTML(200, tplForgotPassword)
  291. }
  292. // ForgotPasswdPost response for forget password request
  293. func ForgotPasswdPost(ctx *context.Context) {
  294. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  295. if setting.MailService == nil {
  296. ctx.Handle(403, "ForgotPasswdPost", nil)
  297. return
  298. }
  299. ctx.Data["IsResetRequest"] = true
  300. email := ctx.Query("email")
  301. ctx.Data["Email"] = email
  302. u, err := models.GetUserByEmail(email)
  303. if err != nil {
  304. if models.IsErrUserNotExist(err) {
  305. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  306. ctx.Data["IsResetSent"] = true
  307. ctx.HTML(200, tplForgotPassword)
  308. return
  309. }
  310. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  311. return
  312. }
  313. if !u.IsLocal() {
  314. ctx.Data["Err_Email"] = true
  315. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), tplForgotPassword, nil)
  316. return
  317. }
  318. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  319. ctx.Data["ResendLimited"] = true
  320. ctx.HTML(200, tplForgotPassword)
  321. return
  322. }
  323. models.SendResetPasswordMail(ctx.Context, u)
  324. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  325. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  326. }
  327. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  328. ctx.Data["IsResetSent"] = true
  329. ctx.HTML(200, tplForgotPassword)
  330. }
  331. // ResetPasswd render the reset password page
  332. func ResetPasswd(ctx *context.Context) {
  333. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  334. code := ctx.Query("code")
  335. if len(code) == 0 {
  336. ctx.Error(404)
  337. return
  338. }
  339. ctx.Data["Code"] = code
  340. ctx.Data["IsResetForm"] = true
  341. ctx.HTML(200, tplResetPassword)
  342. }
  343. // ResetPasswdPost response fro reset password request
  344. func ResetPasswdPost(ctx *context.Context) {
  345. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  346. code := ctx.Query("code")
  347. if len(code) == 0 {
  348. ctx.Error(404)
  349. return
  350. }
  351. ctx.Data["Code"] = code
  352. if u := models.VerifyUserActiveCode(code); u != nil {
  353. // Validate password length.
  354. passwd := ctx.Query("password")
  355. if len(passwd) < 6 {
  356. ctx.Data["IsResetForm"] = true
  357. ctx.Data["Err_Password"] = true
  358. ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), tplResetPassword, nil)
  359. return
  360. }
  361. u.Passwd = passwd
  362. u.Rands = models.GetUserSalt()
  363. u.Salt = models.GetUserSalt()
  364. u.EncodePasswd()
  365. if err := models.UpdateUser(u); err != nil {
  366. ctx.Handle(500, "UpdateUser", err)
  367. return
  368. }
  369. log.Trace("User password reset: %s", u.Name)
  370. ctx.Redirect(setting.AppSubURL + "/user/login")
  371. return
  372. }
  373. ctx.Data["IsResetFailed"] = true
  374. ctx.HTML(200, tplResetPassword)
  375. }