auth.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 context
  5. import (
  6. "net/url"
  7. "github.com/go-macaron/csrf"
  8. "gopkg.in/macaron.v1"
  9. "github.com/gogits/gogs/modules/auth"
  10. "github.com/gogits/gogs/modules/setting"
  11. )
  12. type ToggleOptions struct {
  13. SignInRequired bool
  14. SignOutRequired bool
  15. AdminRequired 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(setting.AppSubUrl + string(setting.LandingPageUrl))
  28. return
  29. }
  30. // Redirect to dashboard if user tries to visit any non-login page.
  31. if options.SignOutRequired && ctx.IsSigned && ctx.Req.RequestURI != "/" {
  32. ctx.Redirect(setting.AppSubUrl + "/")
  33. return
  34. }
  35. if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" && !auth.IsAPIPath(ctx.Req.URL.Path) {
  36. csrf.Validate(ctx.Context, ctx.csrf)
  37. if ctx.Written() {
  38. return
  39. }
  40. }
  41. if options.SignInRequired {
  42. if !ctx.IsSigned {
  43. // Restrict API calls with error message.
  44. if auth.IsAPIPath(ctx.Req.URL.Path) {
  45. ctx.APIError(403, "", "Only signed in user is allowed to call APIs.")
  46. return
  47. }
  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. // Redirect to log in page if auto-signin info is provided and has not signed in.
  58. if !options.SignOutRequired && !ctx.IsSigned && !auth.IsAPIPath(ctx.Req.URL.Path) &&
  59. len(ctx.GetCookie(setting.CookieUserName)) > 0 {
  60. ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl)
  61. ctx.Redirect(setting.AppSubUrl + "/user/login")
  62. return
  63. }
  64. if options.AdminRequired {
  65. if !ctx.User.IsAdmin {
  66. ctx.Error(403)
  67. return
  68. }
  69. ctx.Data["PageIsAdmin"] = true
  70. }
  71. }
  72. }