auth.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. // Checking non-logged users landing page.
  26. if !ctx.IsSigned && ctx.Req.RequestURI == "/" && setting.LandingPageUrl != setting.LANDING_PAGE_HOME {
  27. ctx.Redirect(string(setting.LandingPageUrl))
  28. return
  29. }
  30. // Redirect to dashboard if user tries to visit any non-login page.
  31. if options.SignOutRequire && ctx.IsSigned && ctx.Req.RequestURI != "/" {
  32. ctx.Redirect(setting.AppSubUrl + "/")
  33. return
  34. }
  35. if !options.SignOutRequire && !options.DisableCsrf && ctx.Req.Method == "POST" {
  36. csrf.Validate(ctx.Context, ctx.csrf)
  37. if ctx.Written() {
  38. return
  39. }
  40. }
  41. if options.SignInRequire {
  42. if !ctx.IsSigned {
  43. // Ignore watch repository operation.
  44. if strings.HasSuffix(ctx.Req.RequestURI, "watch") {
  45. return
  46. }
  47. println(url.QueryEscape(setting.AppSubUrl + ctx.Req.RequestURI))
  48. ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl)
  49. ctx.Redirect(setting.AppSubUrl + "/user/login")
  50. return
  51. } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  52. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  53. ctx.HTML(200, "user/auth/activate")
  54. return
  55. }
  56. }
  57. if options.AdminRequire {
  58. if !ctx.User.IsAdmin {
  59. ctx.Error(403)
  60. return
  61. }
  62. ctx.Data["PageIsAdmin"] = true
  63. }
  64. }
  65. }
  66. func ApiReqToken() macaron.Handler {
  67. return func(ctx *Context) {
  68. if !ctx.IsSigned {
  69. ctx.Error(403)
  70. return
  71. }
  72. }
  73. }
  74. func ApiReqBasicAuth() macaron.Handler {
  75. return func(ctx *Context) {
  76. if !ctx.IsBasicAuth {
  77. ctx.Error(403)
  78. return
  79. }
  80. }
  81. }