auth.go 11 KB

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