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.

69 lines
1.5 KiB

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