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.7KB

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