You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth.go 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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/auth"
  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(setting.AppSubUrl + 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. // Restrict API calls with error message.
  44. if auth.IsAPIPath(ctx.Req.URL.Path) {
  45. ctx.HandleAPI(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. if options.AdminRequire {
  58. if !ctx.User.IsAdmin {
  59. ctx.Error(403)
  60. return
  61. }
  62. ctx.Data["PageIsAdmin"] = true
  63. }
  64. }
  65. }
  66. // Contexter middleware already checks token for user sign in process.
  67. func ApiReqToken() macaron.Handler {
  68. return func(ctx *Context) {
  69. if !ctx.IsSigned {
  70. ctx.Error(403)
  71. return
  72. }
  73. }
  74. }
  75. func ApiReqBasicAuth() macaron.Handler {
  76. return func(ctx *Context) {
  77. if !ctx.IsBasicAuth {
  78. ctx.Error(403)
  79. return
  80. }
  81. }
  82. }