auth.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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/http"
  7. "net/url"
  8. "github.com/go-macaron/csrf"
  9. "gopkg.in/macaron.v1"
  10. "gogs.io/gogs/internal/auth"
  11. "gogs.io/gogs/internal/conf"
  12. )
  13. type ToggleOptions struct {
  14. SignInRequired bool
  15. SignOutRequired bool
  16. AdminRequired bool
  17. DisableCSRF bool
  18. }
  19. func Toggle(options *ToggleOptions) macaron.Handler {
  20. return func(c *Context) {
  21. // Cannot view any page before installation.
  22. if !conf.Security.InstallLock {
  23. c.RedirectSubpath("/install")
  24. return
  25. }
  26. // Check prohibit login users.
  27. if c.IsLogged && c.User.ProhibitLogin {
  28. c.Data["Title"] = c.Tr("auth.prohibit_login")
  29. c.Success("user/auth/prohibit_login")
  30. return
  31. }
  32. // Check non-logged users landing page.
  33. if !c.IsLogged && c.Req.RequestURI == "/" && conf.Server.LandingURL != "/" {
  34. c.RedirectSubpath(conf.Server.LandingURL)
  35. return
  36. }
  37. // Redirect to dashboard if user tries to visit any non-login page.
  38. if options.SignOutRequired && c.IsLogged && c.Req.RequestURI != "/" {
  39. c.RedirectSubpath("/")
  40. return
  41. }
  42. if !options.SignOutRequired && !options.DisableCSRF && c.Req.Method == "POST" && !auth.IsAPIPath(c.Req.URL.Path) {
  43. csrf.Validate(c.Context, c.csrf)
  44. if c.Written() {
  45. return
  46. }
  47. }
  48. if options.SignInRequired {
  49. if !c.IsLogged {
  50. // Restrict API calls with error message.
  51. if auth.IsAPIPath(c.Req.URL.Path) {
  52. c.JSON(http.StatusForbidden, map[string]string{
  53. "message": "Only authenticated user is allowed to call APIs.",
  54. })
  55. return
  56. }
  57. c.SetCookie("redirect_to", url.QueryEscape(conf.Server.Subpath+c.Req.RequestURI), 0, conf.Server.Subpath)
  58. c.RedirectSubpath("/user/login")
  59. return
  60. } else if !c.User.IsActive && conf.Auth.RequireEmailConfirmation {
  61. c.Title("auth.active_your_account")
  62. c.Success("user/auth/activate")
  63. return
  64. }
  65. }
  66. // Redirect to log in page if auto-signin info is provided and has not signed in.
  67. if !options.SignOutRequired && !c.IsLogged && !auth.IsAPIPath(c.Req.URL.Path) &&
  68. len(c.GetCookie(conf.Security.CookieUsername)) > 0 {
  69. c.SetCookie("redirect_to", url.QueryEscape(conf.Server.Subpath+c.Req.RequestURI), 0, conf.Server.Subpath)
  70. c.RedirectSubpath("/user/login")
  71. return
  72. }
  73. if options.AdminRequired {
  74. if !c.User.IsAdmin {
  75. c.Status(http.StatusForbidden)
  76. return
  77. }
  78. c.PageIs("Admin")
  79. }
  80. }
  81. }