auth.go 10 KB

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