auth.go 11 KB

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