auth.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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.Session.Delete("socialId")
  132. ctx.Session.Delete("socialName")
  133. ctx.Session.Delete("socialEmail")
  134. ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl)
  135. ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl)
  136. ctx.SetCookie(setting.CSRFCookieName, "", -1, setting.AppSubUrl)
  137. ctx.Redirect(setting.AppSubUrl + "/")
  138. }
  139. func SignUp(ctx *context.Context) {
  140. ctx.Data["Title"] = ctx.Tr("sign_up")
  141. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  142. if setting.Service.DisableRegistration {
  143. ctx.Data["DisableRegistration"] = true
  144. ctx.HTML(200, SIGNUP)
  145. return
  146. }
  147. ctx.HTML(200, SIGNUP)
  148. }
  149. func SignUpPost(ctx *context.Context, cpt *captcha.Captcha, f form.Register) {
  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, SIGNUP)
  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"), SIGNUP, &f)
  163. return
  164. }
  165. if f.Password != f.Retype {
  166. ctx.Data["Err_Password"] = true
  167. ctx.RenderWithErr(ctx.Tr("form.password_not_match"), SIGNUP, &f)
  168. return
  169. }
  170. u := &models.User{
  171. Name: f.UserName,
  172. Email: f.Email,
  173. Passwd: f.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"), SIGNUP, &f)
  181. case models.IsErrEmailAlreadyUsed(err):
  182. ctx.Data["Err_Email"] = true
  183. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), SIGNUP, &f)
  184. case models.IsErrNameReserved(err):
  185. ctx.Data["Err_UserName"] = true
  186. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), SIGNUP, &f)
  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), SIGNUP, &f)
  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. mailer.SendActivateAccountMail(ctx.Context, models.NewMailerUser(u))
  208. ctx.Data["IsSendRegisterMail"] = true
  209. ctx.Data["Email"] = u.Email
  210. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  211. ctx.HTML(200, ACTIVATE)
  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. func Activate(ctx *context.Context) {
  220. code := ctx.Query("code")
  221. if len(code) == 0 {
  222. ctx.Data["IsActivatePage"] = true
  223. if ctx.User.IsActive {
  224. ctx.Error(404)
  225. return
  226. }
  227. // Resend confirmation email.
  228. if setting.Service.RegisterEmailConfirm {
  229. if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) {
  230. ctx.Data["ResendLimited"] = true
  231. } else {
  232. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  233. mailer.SendActivateAccountMail(ctx.Context, models.NewMailerUser(ctx.User))
  234. keyName := "MailResendLimit_" + ctx.User.LowerName
  235. if err := ctx.Cache.Put(keyName, ctx.User.LowerName, 180); err != nil {
  236. log.Error(2, "Set cache '%s' fail: %v", keyName, err)
  237. }
  238. }
  239. } else {
  240. ctx.Data["ServiceNotEnabled"] = true
  241. }
  242. ctx.HTML(200, ACTIVATE)
  243. return
  244. }
  245. // Verify code.
  246. if user := models.VerifyUserActiveCode(code); user != nil {
  247. user.IsActive = true
  248. var err error
  249. if user.Rands, err = models.GetUserSalt(); err != nil {
  250. ctx.Handle(500, "UpdateUser", err)
  251. return
  252. }
  253. if err := models.UpdateUser(user); err != nil {
  254. ctx.Handle(500, "UpdateUser", err)
  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, ACTIVATE)
  265. }
  266. func ActivateEmail(ctx *context.Context) {
  267. code := ctx.Query("code")
  268. email_string := ctx.Query("email")
  269. // Verify code.
  270. if email := models.VerifyActiveEmailCode(code, email_string); email != nil {
  271. if err := email.Activate(); err != nil {
  272. ctx.Handle(500, "ActivateEmail", err)
  273. }
  274. log.Trace("Email activated: %s", email.Email)
  275. ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
  276. }
  277. ctx.Redirect(setting.AppSubUrl + "/user/settings/email")
  278. return
  279. }
  280. func ForgotPasswd(ctx *context.Context) {
  281. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  282. if setting.MailService == nil {
  283. ctx.Data["IsResetDisable"] = true
  284. ctx.HTML(200, FORGOT_PASSWORD)
  285. return
  286. }
  287. ctx.Data["IsResetRequest"] = true
  288. ctx.HTML(200, FORGOT_PASSWORD)
  289. }
  290. func ForgotPasswdPost(ctx *context.Context) {
  291. ctx.Data["Title"] = ctx.Tr("auth.forgot_password")
  292. if setting.MailService == nil {
  293. ctx.Handle(403, "ForgotPasswdPost", nil)
  294. return
  295. }
  296. ctx.Data["IsResetRequest"] = true
  297. email := ctx.Query("email")
  298. ctx.Data["Email"] = email
  299. u, err := models.GetUserByEmail(email)
  300. if err != nil {
  301. if errors.IsUserNotExist(err) {
  302. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  303. ctx.Data["IsResetSent"] = true
  304. ctx.HTML(200, FORGOT_PASSWORD)
  305. return
  306. } else {
  307. ctx.Handle(500, "user.ResetPasswd(check existence)", err)
  308. }
  309. return
  310. }
  311. if !u.IsLocal() {
  312. ctx.Data["Err_Email"] = true
  313. ctx.RenderWithErr(ctx.Tr("auth.non_local_account"), FORGOT_PASSWORD, nil)
  314. return
  315. }
  316. if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
  317. ctx.Data["ResendLimited"] = true
  318. ctx.HTML(200, FORGOT_PASSWORD)
  319. return
  320. }
  321. mailer.SendResetPasswordMail(ctx.Context, models.NewMailerUser(u))
  322. if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  323. log.Error(4, "Set cache(MailResendLimit) fail: %v", err)
  324. }
  325. ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60
  326. ctx.Data["IsResetSent"] = true
  327. ctx.HTML(200, FORGOT_PASSWORD)
  328. }
  329. func ResetPasswd(ctx *context.Context) {
  330. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  331. code := ctx.Query("code")
  332. if len(code) == 0 {
  333. ctx.Error(404)
  334. return
  335. }
  336. ctx.Data["Code"] = code
  337. ctx.Data["IsResetForm"] = true
  338. ctx.HTML(200, RESET_PASSWORD)
  339. }
  340. func ResetPasswdPost(ctx *context.Context) {
  341. ctx.Data["Title"] = ctx.Tr("auth.reset_password")
  342. code := ctx.Query("code")
  343. if len(code) == 0 {
  344. ctx.Error(404)
  345. return
  346. }
  347. ctx.Data["Code"] = code
  348. if u := models.VerifyUserActiveCode(code); u != nil {
  349. // Validate password length.
  350. passwd := ctx.Query("password")
  351. if len(passwd) < 6 {
  352. ctx.Data["IsResetForm"] = true
  353. ctx.Data["Err_Password"] = true
  354. ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
  355. return
  356. }
  357. u.Passwd = passwd
  358. var err error
  359. if u.Rands, err = models.GetUserSalt(); err != nil {
  360. ctx.Handle(500, "UpdateUser", err)
  361. return
  362. }
  363. if u.Salt, err = models.GetUserSalt(); err != nil {
  364. ctx.Handle(500, "UpdateUser", err)
  365. return
  366. }
  367. u.EncodePasswd()
  368. if err := models.UpdateUser(u); err != nil {
  369. ctx.Handle(500, "UpdateUser", err)
  370. return
  371. }
  372. log.Trace("User password reset: %s", u.Name)
  373. ctx.Redirect(setting.AppSubUrl + "/user/login")
  374. return
  375. }
  376. ctx.Data["IsResetFailed"] = true
  377. ctx.HTML(200, RESET_PASSWORD)
  378. }