auth.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl)
  48. ctx.Redirect(setting.AppSubUrl + "/user/login")
  49. return
  50. } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  51. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  52. ctx.HTML(200, "user/auth/activate")
  53. return
  54. }
  55. }
  56. if options.AdminRequire {
  57. if !ctx.User.IsAdmin {
  58. ctx.Error(403)
  59. return
  60. }
  61. ctx.Data["PageIsAdmin"] = true
  62. }
  63. }
  64. }
  65. func ApiReqToken() macaron.Handler {
  66. return func(ctx *Context) {
  67. if !ctx.IsSigned {
  68. ctx.Error(403)
  69. return
  70. }
  71. }
  72. }
  73. func ApiReqBasicAuth() macaron.Handler {
  74. return func(ctx *Context) {
  75. if !ctx.IsBasicAuth {
  76. ctx.Error(403)
  77. return
  78. }
  79. }
  80. }