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

auth.go 5.8 kB

3 years ago
11 years ago
11 years ago
11 years ago
11 years ago
3 years ago
11 years ago
11 years ago
11 years ago
11 years ago
3 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
4 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package context
  6. import (
  7. "encoding/base64"
  8. "net/http"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/auth"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "gitea.com/macaron/csrf"
  15. "gitea.com/macaron/macaron"
  16. marc_auth "github.com/go-macaron/auth"
  17. )
  18. // ToggleOptions contains required or check options
  19. type ToggleOptions struct {
  20. SignInRequired bool
  21. SignOutRequired bool
  22. AdminRequired bool
  23. DisableCSRF bool
  24. BasicAuthRequired bool
  25. OperationRequired bool
  26. }
  27. // Toggle returns toggle options as middleware
  28. func Toggle(options *ToggleOptions) macaron.Handler {
  29. return func(ctx *Context) {
  30. // Cannot view any page before installation.
  31. if !setting.InstallLock {
  32. ctx.Redirect(setting.AppSubURL + "/install")
  33. return
  34. }
  35. // Check prohibit login users.
  36. if ctx.IsSigned {
  37. if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  38. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  39. ctx.HTML(200, "user/auth/activate")
  40. return
  41. } else if !ctx.User.IsActive || ctx.User.ProhibitLogin {
  42. log.Info("Failed authentication attempt for %s from %s", ctx.User.Name, ctx.RemoteAddr())
  43. ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
  44. ctx.HTML(200, "user/auth/prohibit_login")
  45. return
  46. }
  47. if ctx.User.MustChangePassword {
  48. if ctx.Req.URL.Path != "/user/settings/change_password" {
  49. ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
  50. ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password"
  51. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  52. ctx.Redirect(setting.AppSubURL + "/user/settings/change_password")
  53. return
  54. }
  55. } else if ctx.Req.URL.Path == "/user/settings/change_password" {
  56. // make sure that the form cannot be accessed by users who don't need this
  57. ctx.Redirect(setting.AppSubURL + "/")
  58. return
  59. }
  60. if ctx.QueryBool("course") {
  61. ctx.Redirect(setting.AppSubURL + "/" + setting.Course.OrgName)
  62. return
  63. }
  64. }
  65. // Redirect to dashboard if user tries to visit any non-login page.
  66. if options.SignOutRequired && ctx.IsSigned && ctx.Req.URL.RequestURI() != "/" {
  67. ctx.Redirect(setting.AppSubURL + "/")
  68. return
  69. }
  70. if !options.SignOutRequired && !options.DisableCSRF && ctx.Req.Method == "POST" && !auth.IsAPIPath(ctx.Req.URL.Path) {
  71. csrf.Validate(ctx.Context, ctx.csrf)
  72. if ctx.Written() {
  73. return
  74. }
  75. }
  76. if options.SignInRequired {
  77. if !ctx.IsSigned {
  78. // Restrict API calls with error message.
  79. if auth.IsAPIPath(ctx.Req.URL.Path) {
  80. ctx.JSON(403, map[string]string{
  81. "message": "Only signed in user is allowed to call APIs.",
  82. })
  83. return
  84. }
  85. tempUrl := ctx.Req.URL.RequestURI()
  86. if strings.Contains(tempUrl, "action/star?") || strings.Contains(tempUrl, "action/watch?") {
  87. redirectForStarAndWatch(ctx, tempUrl)
  88. } else {
  89. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  90. }
  91. ctx.Redirect(setting.AppSubURL + "/user/login")
  92. return
  93. } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
  94. ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
  95. ctx.HTML(200, "user/auth/activate")
  96. return
  97. }
  98. if ctx.IsSigned && auth.IsAPIPath(ctx.Req.URL.Path) && ctx.IsBasicAuth {
  99. twofa, err := models.GetTwoFactorByUID(ctx.User.ID)
  100. if err != nil {
  101. if models.IsErrTwoFactorNotEnrolled(err) {
  102. return // No 2FA enrollment for this user
  103. }
  104. ctx.Error(500)
  105. return
  106. }
  107. otpHeader := ctx.Req.Header.Get("X-Gitea-OTP")
  108. ok, err := twofa.ValidateTOTP(otpHeader)
  109. if err != nil {
  110. ctx.Error(500)
  111. return
  112. }
  113. if !ok {
  114. ctx.JSON(403, map[string]string{
  115. "message": "Only signed in user is allowed to call APIs.",
  116. })
  117. return
  118. }
  119. }
  120. }
  121. // Redirect to log in page if auto-signin info is provided and has not signed in.
  122. if !options.SignOutRequired && !ctx.IsSigned && !auth.IsAPIPath(ctx.Req.URL.Path) &&
  123. len(ctx.GetCookie(setting.CookieUserName)) > 0 {
  124. ctx.SetCookie("redirect_to", setting.AppSubURL+ctx.Req.URL.RequestURI(), 0, setting.AppSubURL)
  125. ctx.Redirect(setting.AppSubURL + "/user/login")
  126. return
  127. }
  128. if options.AdminRequired {
  129. if !ctx.User.IsAdmin {
  130. ctx.Error(403)
  131. return
  132. }
  133. ctx.Data["PageIsAdmin"] = true
  134. }
  135. if options.BasicAuthRequired {
  136. if !basicAuth(ctx) {
  137. basicUnauthorized(ctx.Resp)
  138. return
  139. }
  140. }
  141. if options.OperationRequired {
  142. if !ctx.User.IsOperator {
  143. ctx.Error(403)
  144. return
  145. }
  146. ctx.Data["PageIsOperation"] = true
  147. }
  148. }
  149. }
  150. func redirectForStarAndWatch(ctx *Context, tempUrl string) {
  151. splits := strings.Split(tempUrl, "?")
  152. if len(splits) > 1 {
  153. redirectArguments := strings.Split(splits[1], "=")
  154. if len(redirectArguments) > 0 && redirectArguments[0] == "redirect_to" {
  155. ctx.SetCookie("redirect_to", setting.AppSubURL+strings.Replace(redirectArguments[1], "%2f", "/", -1), 0, setting.AppSubURL)
  156. }
  157. }
  158. }
  159. func basicAuth(ctx *Context) bool {
  160. var siteAuth = base64.StdEncoding.EncodeToString([]byte(setting.CBAuthUser + ":" + setting.CBAuthPassword))
  161. auth := ctx.Req.Header.Get("Authorization")
  162. if !marc_auth.SecureCompare(auth, "Basic "+siteAuth) {
  163. return false
  164. }
  165. return true
  166. }
  167. func basicUnauthorized(res http.ResponseWriter) {
  168. res.Header().Set("WWW-Authenticate", "Basic realm=\""+marc_auth.BasicRealm+"\"")
  169. http.Error(res, "Not Authorized", http.StatusUnauthorized)
  170. }