You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth.go 1.5KB

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