auth.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 middleware
  5. import (
  6. "net/url"
  7. "github.com/go-martini/martini"
  8. "github.com/gogits/gogs/modules/base"
  9. )
  10. type ToggleOptions struct {
  11. SignInRequire bool
  12. SignOutRequire bool
  13. AdminRequire bool
  14. DisableCsrf bool
  15. }
  16. func Toggle(options *ToggleOptions) martini.Handler {
  17. return func(ctx *Context) {
  18. // Cannot view any page before installation.
  19. if !base.InstallLock {
  20. ctx.Redirect("/install")
  21. return
  22. }
  23. // Redirect to dashboard if user tries to visit any non-login page.
  24. if options.SignOutRequire && ctx.IsSigned && ctx.Req.RequestURI != "/" {
  25. ctx.Redirect("/")
  26. return
  27. }
  28. if !options.DisableCsrf && ctx.Req.Method == "POST" && !ctx.CsrfTokenValid() {
  29. ctx.Error(403, "CSRF token does not match")
  30. return
  31. }
  32. if options.SignInRequire {
  33. if !ctx.IsSigned {
  34. ctx.SetCookie("redirect_to", "/"+url.QueryEscape(ctx.Req.RequestURI))
  35. ctx.Redirect("/user/login")
  36. return
  37. } else if !ctx.User.IsActive && base.Service.RegisterEmailConfirm {
  38. ctx.Data["Title"] = "Activate Your Account"
  39. ctx.HTML(200, "user/activate")
  40. return
  41. }
  42. }
  43. if options.AdminRequire {
  44. if !ctx.User.IsAdmin {
  45. ctx.Error(403)
  46. return
  47. }
  48. ctx.Data["PageIsAdmin"] = true
  49. }
  50. }
  51. }