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.

oauth2.go 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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/go-xorm/xorm"
  11. "github.com/lafriks/xormstore"
  12. "github.com/markbates/goth"
  13. "github.com/markbates/goth/gothic"
  14. "github.com/markbates/goth/providers/bitbucket"
  15. "github.com/markbates/goth/providers/discord"
  16. "github.com/markbates/goth/providers/dropbox"
  17. "github.com/markbates/goth/providers/facebook"
  18. "github.com/markbates/goth/providers/gitea"
  19. "github.com/markbates/goth/providers/github"
  20. "github.com/markbates/goth/providers/gitlab"
  21. "github.com/markbates/goth/providers/google"
  22. "github.com/markbates/goth/providers/openidConnect"
  23. "github.com/markbates/goth/providers/twitter"
  24. "github.com/satori/go.uuid"
  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. }