本站源代码
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.

251 line
8.0KB

  1. // Copyright 2017 The Gitea 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 oauth2
  5. import (
  6. "math"
  7. "net/http"
  8. "code.gitea.io/gitea/modules/log"
  9. "code.gitea.io/gitea/modules/setting"
  10. "github.com/lafriks/xormstore"
  11. "github.com/markbates/goth"
  12. "github.com/markbates/goth/gothic"
  13. "github.com/markbates/goth/providers/bitbucket"
  14. "github.com/markbates/goth/providers/discord"
  15. "github.com/markbates/goth/providers/dropbox"
  16. "github.com/markbates/goth/providers/facebook"
  17. "github.com/markbates/goth/providers/gitea"
  18. "github.com/markbates/goth/providers/github"
  19. "github.com/markbates/goth/providers/gitlab"
  20. "github.com/markbates/goth/providers/google"
  21. "github.com/markbates/goth/providers/openidConnect"
  22. "github.com/markbates/goth/providers/twitter"
  23. "github.com/satori/go.uuid"
  24. "xorm.io/xorm"
  25. )
  26. var (
  27. sessionUsersStoreKey = "gitea-oauth2-sessions"
  28. providerHeaderKey = "gitea-oauth2-provider"
  29. )
  30. // CustomURLMapping describes the urls values to use when customizing OAuth2 provider URLs
  31. type CustomURLMapping struct {
  32. AuthURL string
  33. TokenURL string
  34. ProfileURL string
  35. EmailURL string
  36. }
  37. // Init initialize the setup of the OAuth2 library
  38. func Init(x *xorm.Engine) error {
  39. store, err := xormstore.NewOptions(x, xormstore.Options{
  40. TableName: "oauth2_session",
  41. }, []byte(sessionUsersStoreKey))
  42. if err != nil {
  43. return err
  44. }
  45. // according to the Goth lib:
  46. // set the maxLength of the cookies stored on the disk to a larger number to prevent issues with:
  47. // securecookie: the value is too long
  48. // when using OpenID Connect , since this can contain a large amount of extra information in the id_token
  49. // Note, when using the FilesystemStore only the session.ID is written to a browser cookie, so this is explicit for the storage on disk
  50. store.MaxLength(math.MaxInt16)
  51. gothic.Store = store
  52. gothic.SetState = func(req *http.Request) string {
  53. return uuid.NewV4().String()
  54. }
  55. gothic.GetProviderName = func(req *http.Request) (string, error) {
  56. return req.Header.Get(providerHeaderKey), nil
  57. }
  58. return nil
  59. }
  60. // Auth OAuth2 auth service
  61. func Auth(provider string, request *http.Request, response http.ResponseWriter) error {
  62. // not sure if goth is thread safe (?) when using multiple providers
  63. request.Header.Set(providerHeaderKey, provider)
  64. // don't use the default gothic begin handler to prevent issues when some error occurs
  65. // normally the gothic library will write some custom stuff to the response instead of our own nice error page
  66. //gothic.BeginAuthHandler(response, request)
  67. url, err := gothic.GetAuthURL(response, request)
  68. if err == nil {
  69. http.Redirect(response, request, url, http.StatusTemporaryRedirect)
  70. }
  71. return err
  72. }
  73. // ProviderCallback handles OAuth callback, resolve to a goth user and send back to original url
  74. // this will trigger a new authentication request, but because we save it in the session we can use that
  75. func ProviderCallback(provider string, request *http.Request, response http.ResponseWriter) (goth.User, error) {
  76. // not sure if goth is thread safe (?) when using multiple providers
  77. request.Header.Set(providerHeaderKey, provider)
  78. user, err := gothic.CompleteUserAuth(response, request)
  79. if err != nil {
  80. return user, err
  81. }
  82. return user, nil
  83. }
  84. // RegisterProvider register a OAuth2 provider in goth lib
  85. func RegisterProvider(providerName, providerType, clientID, clientSecret, openIDConnectAutoDiscoveryURL string, customURLMapping *CustomURLMapping) error {
  86. provider, err := createProvider(providerName, providerType, clientID, clientSecret, openIDConnectAutoDiscoveryURL, customURLMapping)
  87. if err == nil && provider != nil {
  88. goth.UseProviders(provider)
  89. }
  90. return err
  91. }
  92. // RemoveProvider removes the given OAuth2 provider from the goth lib
  93. func RemoveProvider(providerName string) {
  94. delete(goth.GetProviders(), providerName)
  95. }
  96. // used to create different types of goth providers
  97. func createProvider(providerName, providerType, clientID, clientSecret, openIDConnectAutoDiscoveryURL string, customURLMapping *CustomURLMapping) (goth.Provider, error) {
  98. callbackURL := setting.AppURL + "user/oauth2/" + providerName + "/callback"
  99. var provider goth.Provider
  100. var err error
  101. switch providerType {
  102. case "bitbucket":
  103. provider = bitbucket.New(clientID, clientSecret, callbackURL, "account")
  104. case "dropbox":
  105. provider = dropbox.New(clientID, clientSecret, callbackURL)
  106. case "facebook":
  107. provider = facebook.New(clientID, clientSecret, callbackURL, "email")
  108. case "github":
  109. authURL := github.AuthURL
  110. tokenURL := github.TokenURL
  111. profileURL := github.ProfileURL
  112. emailURL := github.EmailURL
  113. if customURLMapping != nil {
  114. if len(customURLMapping.AuthURL) > 0 {
  115. authURL = customURLMapping.AuthURL
  116. }
  117. if len(customURLMapping.TokenURL) > 0 {
  118. tokenURL = customURLMapping.TokenURL
  119. }
  120. if len(customURLMapping.ProfileURL) > 0 {
  121. profileURL = customURLMapping.ProfileURL
  122. }
  123. if len(customURLMapping.EmailURL) > 0 {
  124. emailURL = customURLMapping.EmailURL
  125. }
  126. }
  127. provider = github.NewCustomisedURL(clientID, clientSecret, callbackURL, authURL, tokenURL, profileURL, emailURL)
  128. case "gitlab":
  129. authURL := gitlab.AuthURL
  130. tokenURL := gitlab.TokenURL
  131. profileURL := gitlab.ProfileURL
  132. if customURLMapping != nil {
  133. if len(customURLMapping.AuthURL) > 0 {
  134. authURL = customURLMapping.AuthURL
  135. }
  136. if len(customURLMapping.TokenURL) > 0 {
  137. tokenURL = customURLMapping.TokenURL
  138. }
  139. if len(customURLMapping.ProfileURL) > 0 {
  140. profileURL = customURLMapping.ProfileURL
  141. }
  142. }
  143. provider = gitlab.NewCustomisedURL(clientID, clientSecret, callbackURL, authURL, tokenURL, profileURL, "read_user")
  144. case "gplus": // named gplus due to legacy gplus -> google migration (Google killed Google+). This ensures old connections still work
  145. provider = google.New(clientID, clientSecret, callbackURL)
  146. case "openidConnect":
  147. if provider, err = openidConnect.New(clientID, clientSecret, callbackURL, openIDConnectAutoDiscoveryURL); err != nil {
  148. log.Warn("Failed to create OpenID Connect Provider with name '%s' with url '%s': %v", providerName, openIDConnectAutoDiscoveryURL, err)
  149. }
  150. case "twitter":
  151. provider = twitter.NewAuthenticate(clientID, clientSecret, callbackURL)
  152. case "discord":
  153. provider = discord.New(clientID, clientSecret, callbackURL, discord.ScopeIdentify, discord.ScopeEmail)
  154. case "gitea":
  155. authURL := gitea.AuthURL
  156. tokenURL := gitea.TokenURL
  157. profileURL := gitea.ProfileURL
  158. if customURLMapping != nil {
  159. if len(customURLMapping.AuthURL) > 0 {
  160. authURL = customURLMapping.AuthURL
  161. }
  162. if len(customURLMapping.TokenURL) > 0 {
  163. tokenURL = customURLMapping.TokenURL
  164. }
  165. if len(customURLMapping.ProfileURL) > 0 {
  166. profileURL = customURLMapping.ProfileURL
  167. }
  168. }
  169. provider = gitea.NewCustomisedURL(clientID, clientSecret, callbackURL, authURL, tokenURL, profileURL)
  170. }
  171. // always set the name if provider is created so we can support multiple setups of 1 provider
  172. if err == nil && provider != nil {
  173. provider.SetName(providerName)
  174. }
  175. return provider, err
  176. }
  177. // GetDefaultTokenURL return the default token url for the given provider
  178. func GetDefaultTokenURL(provider string) string {
  179. switch provider {
  180. case "github":
  181. return github.TokenURL
  182. case "gitlab":
  183. return gitlab.TokenURL
  184. case "gitea":
  185. return gitea.TokenURL
  186. }
  187. return ""
  188. }
  189. // GetDefaultAuthURL return the default authorize url for the given provider
  190. func GetDefaultAuthURL(provider string) string {
  191. switch provider {
  192. case "github":
  193. return github.AuthURL
  194. case "gitlab":
  195. return gitlab.AuthURL
  196. case "gitea":
  197. return gitea.AuthURL
  198. }
  199. return ""
  200. }
  201. // GetDefaultProfileURL return the default profile url for the given provider
  202. func GetDefaultProfileURL(provider string) string {
  203. switch provider {
  204. case "github":
  205. return github.ProfileURL
  206. case "gitlab":
  207. return gitlab.ProfileURL
  208. case "gitea":
  209. return gitea.ProfileURL
  210. }
  211. return ""
  212. }
  213. // GetDefaultEmailURL return the default email url for the given provider
  214. func GetDefaultEmailURL(provider string) string {
  215. if provider == "github" {
  216. return github.EmailURL
  217. }
  218. return ""
  219. }
上海开阖软件有限公司 沪ICP备12045867号-1