auth.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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/codegangsta/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. if options.SignOutRequire && ctx.IsSigned && ctx.Req.RequestURI != "/" {
  19. ctx.Redirect("/")
  20. return
  21. }
  22. if !options.DisableCsrf {
  23. if ctx.Req.Method == "POST" {
  24. if !ctx.CsrfTokenValid() {
  25. ctx.Error(403, "CSRF token does not match")
  26. return
  27. }
  28. }
  29. }
  30. if options.SignInRequire {
  31. if !ctx.IsSigned {
  32. ctx.SetCookie("redirect_to", "/"+url.QueryEscape(ctx.Req.RequestURI))
  33. ctx.Redirect("/user/login")
  34. return
  35. } else if !ctx.User.IsActive && base.Service.RegisterEmailConfirm {
  36. ctx.Data["Title"] = "Activate Your Account"
  37. ctx.HTML(200, "user/active")
  38. return
  39. }
  40. }
  41. if options.AdminRequire {
  42. if !ctx.User.IsAdmin {
  43. ctx.Error(403)
  44. return
  45. }
  46. ctx.Data["PageIsAdmin"] = true
  47. }
  48. }
  49. }