auth.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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/Unknwon/macaron"
  8. "github.com/macaron-contrib/csrf"
  9. "github.com/gogits/gogs/modules/setting"
  10. )
  11. type ToggleOptions struct {
  12. SignInRequire bool
  13. SignOutRequire bool
  14. AdminRequire bool
  15. DisableCsrf bool
  16. }
  17. func Toggle(options *ToggleOptions) macaron.Handler {
  18. return func(ctx *Context) {
  19. // Cannot view any page before installation.
  20. if !setting.InstallLock {
  21. ctx.Redirect(setting.AppSubUrl + "/install")
  22. return
  23. }
  24. // Checking non-logged users landing page.
  25. if !ctx.IsSigned && ctx.Req.RequestURI == "/" && setting.LandingPageUrl != setting.LANDING_PAGE_HOME {
  26. ctx.Redirect(string(setting.LandingPageUrl))
  27. return
  28. }
  29. // Redirect to dashboard if user tries to visit any non-login page.
  30. if options.SignOutRequire && ctx.IsSigned && ctx.Req.RequestURI != "/" {
  31. ctx.Redirect(setting.AppSubUrl + "/")
  32. return
  33. }
  34. if !options.SignOutRequire && !options.DisableCsrf && ctx.Req.Method == "POST" {
  35. csrf.Validate(ctx.Context, ctx.csrf)
  36. if ctx.Written() {
  37. return
  38. }
  39. }
  40. if options.SignInRequire {
  41. if !ctx.IsSigned {
  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. }
  60. func ApiReqToken() macaron.Handler {
  61. return func(ctx *Context) {
  62. if !ctx.IsSigned {
  63. ctx.Error(403)
  64. return
  65. }
  66. }
  67. }
  68. func ApiReqBasicAuth() macaron.Handler {
  69. return func(ctx *Context) {
  70. if !ctx.IsBasicAuth {
  71. ctx.Error(403)
  72. return
  73. }
  74. }
  75. }