auth.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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(setting.AppSubUrl + "/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(setting.AppSubUrl + "/")
  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(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl)
  43. ctx.Redirect(setting.AppSubUrl + "/user/login")
  44. return
  45. } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  46. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  47. ctx.HTML(200, "user/auth/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. }