gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package auth
  5. import (
  6. "fmt"
  7. "net/http"
  8. "regexp"
  9. "strings"
  10. "sync"
  11. user_model "code.gitea.io/gitea/models/user"
  12. "code.gitea.io/gitea/modules/auth/webauthn"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/optional"
  15. "code.gitea.io/gitea/modules/session"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/web/middleware"
  18. gitea_context "code.gitea.io/gitea/services/context"
  19. user_service "code.gitea.io/gitea/services/user"
  20. )
  21. type globalVarsStruct struct {
  22. gitRawOrAttachPathRe *regexp.Regexp
  23. lfsPathRe *regexp.Regexp
  24. archivePathRe *regexp.Regexp
  25. feedPathRe *regexp.Regexp
  26. feedRefPathRe *regexp.Regexp
  27. }
  28. var globalVars = sync.OnceValue(func() *globalVarsStruct {
  29. return &globalVarsStruct{
  30. gitRawOrAttachPathRe: regexp.MustCompile(`^/[-.\w]+/[-.\w]+/(?:(?:git-(?:(?:upload)|(?:receive))-pack$)|(?:info/refs$)|(?:HEAD$)|(?:objects/)|(?:raw/)|(?:releases/download/)|(?:attachments/))`),
  31. lfsPathRe: regexp.MustCompile(`^/[-.\w]+/[-.\w]+/info/lfs/`),
  32. archivePathRe: regexp.MustCompile(`^/[-.\w]+/[-.\w]+/archive/`),
  33. feedPathRe: regexp.MustCompile(`^/[-.\w]+(/[-.\w]+)?\.(rss|atom)$`), // "/owner.rss" or "/owner/repo.atom"
  34. feedRefPathRe: regexp.MustCompile(`^/[-.\w]+/[-.\w]+/(rss|atom)/`), // "/owner/repo/rss/branch/..."
  35. }
  36. })
  37. // Init should be called exactly once when the application starts to allow plugins
  38. // to allocate necessary resources
  39. func Init() {
  40. webauthn.Init()
  41. }
  42. type authPathDetector struct {
  43. req *http.Request
  44. vars *globalVarsStruct
  45. }
  46. func newAuthPathDetector(req *http.Request) *authPathDetector {
  47. return &authPathDetector{req: req, vars: globalVars()}
  48. }
  49. // isAPIPath returns true if the specified URL is an API path
  50. func (a *authPathDetector) isAPIPath() bool {
  51. return strings.HasPrefix(a.req.URL.Path, "/api/")
  52. }
  53. // isAttachmentDownload check if request is a file download (GET) with URL to an attachment
  54. func (a *authPathDetector) isAttachmentDownload() bool {
  55. return strings.HasPrefix(a.req.URL.Path, "/attachments/") && a.req.Method == http.MethodGet
  56. }
  57. func (a *authPathDetector) isFeedRequest(req *http.Request) bool {
  58. if !setting.Other.EnableFeed {
  59. return false
  60. }
  61. if req.Method != http.MethodGet {
  62. return false
  63. }
  64. return a.vars.feedPathRe.MatchString(req.URL.Path) || a.vars.feedRefPathRe.MatchString(req.URL.Path)
  65. }
  66. // isContainerPath checks if the request targets the container endpoint
  67. func (a *authPathDetector) isContainerPath() bool {
  68. return strings.HasPrefix(a.req.URL.Path, "/v2/")
  69. }
  70. func (a *authPathDetector) isGitRawOrAttachPath() bool {
  71. return a.vars.gitRawOrAttachPathRe.MatchString(a.req.URL.Path)
  72. }
  73. func (a *authPathDetector) isGitRawOrAttachOrLFSPath() bool {
  74. if a.isGitRawOrAttachPath() {
  75. return true
  76. }
  77. if setting.LFS.StartServer {
  78. return a.vars.lfsPathRe.MatchString(a.req.URL.Path)
  79. }
  80. return false
  81. }
  82. func (a *authPathDetector) isArchivePath() bool {
  83. return a.vars.archivePathRe.MatchString(a.req.URL.Path)
  84. }
  85. func (a *authPathDetector) isAuthenticatedTokenRequest() bool {
  86. switch a.req.URL.Path {
  87. case "/login/oauth/userinfo", "/login/oauth/introspect":
  88. return true
  89. }
  90. return false
  91. }
  92. // handleSignIn clears existing session variables and stores new ones for the specified user object
  93. func handleSignIn(resp http.ResponseWriter, req *http.Request, sess SessionStore, user *user_model.User) {
  94. // We need to regenerate the session...
  95. newSess, err := session.RegenerateSession(resp, req)
  96. if err != nil {
  97. log.Error(fmt.Sprintf("Error regenerating session: %v", err))
  98. } else {
  99. sess = newSess
  100. }
  101. _ = sess.Delete("openid_verified_uri")
  102. _ = sess.Delete("openid_signin_remember")
  103. _ = sess.Delete("openid_determined_email")
  104. _ = sess.Delete("openid_determined_username")
  105. _ = sess.Delete("twofaUid")
  106. _ = sess.Delete("twofaRemember")
  107. _ = sess.Delete("webauthnAssertion")
  108. _ = sess.Delete("linkAccount")
  109. err = sess.Set("uid", user.ID)
  110. if err != nil {
  111. log.Error(fmt.Sprintf("Error setting session: %v", err))
  112. }
  113. err = sess.Set("uname", user.Name)
  114. if err != nil {
  115. log.Error(fmt.Sprintf("Error setting session: %v", err))
  116. }
  117. // Language setting of the user overwrites the one previously set
  118. // If the user does not have a locale set, we save the current one.
  119. if len(user.Language) == 0 {
  120. lc := middleware.Locale(resp, req)
  121. opts := &user_service.UpdateOptions{
  122. Language: optional.Some(lc.Language()),
  123. }
  124. if err := user_service.UpdateUser(req.Context(), user, opts); err != nil {
  125. log.Error(fmt.Sprintf("Error updating user language [user: %d, locale: %s]", user.ID, user.Language))
  126. return
  127. }
  128. }
  129. middleware.SetLocaleCookie(resp, user.Language, 0)
  130. // force to generate a new CSRF token
  131. if ctx := gitea_context.GetWebContext(req.Context()); ctx != nil {
  132. ctx.Csrf.PrepareForSessionUser(ctx)
  133. }
  134. }