auth.go 11 KB

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