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.

225 lines
6.7 KiB

Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package internal contains support packages for oauth2 package.
  5. package internal
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime"
  12. "net/http"
  13. "net/url"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "golang.org/x/net/context"
  18. )
  19. // Token represents the crendentials used to authorize
  20. // the requests to access protected resources on the OAuth 2.0
  21. // provider's backend.
  22. //
  23. // This type is a mirror of oauth2.Token and exists to break
  24. // an otherwise-circular dependency. Other internal packages
  25. // should convert this Token into an oauth2.Token before use.
  26. type Token struct {
  27. // AccessToken is the token that authorizes and authenticates
  28. // the requests.
  29. AccessToken string
  30. // TokenType is the type of token.
  31. // The Type method returns either this or "Bearer", the default.
  32. TokenType string
  33. // RefreshToken is a token that's used by the application
  34. // (as opposed to the user) to refresh the access token
  35. // if it expires.
  36. RefreshToken string
  37. // Expiry is the optional expiration time of the access token.
  38. //
  39. // If zero, TokenSource implementations will reuse the same
  40. // token forever and RefreshToken or equivalent
  41. // mechanisms for that TokenSource will not be used.
  42. Expiry time.Time
  43. // Raw optionally contains extra metadata from the server
  44. // when updating a token.
  45. Raw interface{}
  46. }
  47. // tokenJSON is the struct representing the HTTP response from OAuth2
  48. // providers returning a token in JSON form.
  49. type tokenJSON struct {
  50. AccessToken string `json:"access_token"`
  51. TokenType string `json:"token_type"`
  52. RefreshToken string `json:"refresh_token"`
  53. ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number
  54. Expires expirationTime `json:"expires"` // broken Facebook spelling of expires_in
  55. }
  56. func (e *tokenJSON) expiry() (t time.Time) {
  57. if v := e.ExpiresIn; v != 0 {
  58. return time.Now().Add(time.Duration(v) * time.Second)
  59. }
  60. if v := e.Expires; v != 0 {
  61. return time.Now().Add(time.Duration(v) * time.Second)
  62. }
  63. return
  64. }
  65. type expirationTime int32
  66. func (e *expirationTime) UnmarshalJSON(b []byte) error {
  67. var n json.Number
  68. err := json.Unmarshal(b, &n)
  69. if err != nil {
  70. return err
  71. }
  72. i, err := n.Int64()
  73. if err != nil {
  74. return err
  75. }
  76. *e = expirationTime(i)
  77. return nil
  78. }
  79. var brokenAuthHeaderProviders = []string{
  80. "https://accounts.google.com/",
  81. "https://api.dropbox.com/",
  82. "https://api.dropboxapi.com/",
  83. "https://api.instagram.com/",
  84. "https://api.netatmo.net/",
  85. "https://api.odnoklassniki.ru/",
  86. "https://api.pushbullet.com/",
  87. "https://api.soundcloud.com/",
  88. "https://api.twitch.tv/",
  89. "https://app.box.com/",
  90. "https://connect.stripe.com/",
  91. "https://login.microsoftonline.com/",
  92. "https://login.salesforce.com/",
  93. "https://oauth.sandbox.trainingpeaks.com/",
  94. "https://oauth.trainingpeaks.com/",
  95. "https://oauth.vk.com/",
  96. "https://openapi.baidu.com/",
  97. "https://slack.com/",
  98. "https://test-sandbox.auth.corp.google.com",
  99. "https://test.salesforce.com/",
  100. "https://user.gini.net/",
  101. "https://www.douban.com/",
  102. "https://www.googleapis.com/",
  103. "https://www.linkedin.com/",
  104. "https://www.strava.com/oauth/",
  105. "https://www.wunderlist.com/oauth/",
  106. "https://api.patreon.com/",
  107. }
  108. func RegisterBrokenAuthHeaderProvider(tokenURL string) {
  109. brokenAuthHeaderProviders = append(brokenAuthHeaderProviders, tokenURL)
  110. }
  111. // providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL
  112. // implements the OAuth2 spec correctly
  113. // See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
  114. // In summary:
  115. // - Reddit only accepts client secret in the Authorization header
  116. // - Dropbox accepts either it in URL param or Auth header, but not both.
  117. // - Google only accepts URL param (not spec compliant?), not Auth header
  118. // - Stripe only accepts client secret in Auth header with Bearer method, not Basic
  119. func providerAuthHeaderWorks(tokenURL string) bool {
  120. for _, s := range brokenAuthHeaderProviders {
  121. if strings.HasPrefix(tokenURL, s) {
  122. // Some sites fail to implement the OAuth2 spec fully.
  123. return false
  124. }
  125. }
  126. // Assume the provider implements the spec properly
  127. // otherwise. We can add more exceptions as they're
  128. // discovered. We will _not_ be adding configurable hooks
  129. // to this package to let users select server bugs.
  130. return true
  131. }
  132. func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error) {
  133. hc, err := ContextClient(ctx)
  134. if err != nil {
  135. return nil, err
  136. }
  137. v.Set("client_id", clientID)
  138. bustedAuth := !providerAuthHeaderWorks(tokenURL)
  139. if bustedAuth && clientSecret != "" {
  140. v.Set("client_secret", clientSecret)
  141. }
  142. req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode()))
  143. if err != nil {
  144. return nil, err
  145. }
  146. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  147. if !bustedAuth {
  148. req.SetBasicAuth(clientID, clientSecret)
  149. }
  150. r, err := hc.Do(req)
  151. if err != nil {
  152. return nil, err
  153. }
  154. defer r.Body.Close()
  155. body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
  156. if err != nil {
  157. return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
  158. }
  159. if code := r.StatusCode; code < 200 || code > 299 {
  160. return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", r.Status, body)
  161. }
  162. var token *Token
  163. content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
  164. switch content {
  165. case "application/x-www-form-urlencoded", "text/plain":
  166. vals, err := url.ParseQuery(string(body))
  167. if err != nil {
  168. return nil, err
  169. }
  170. token = &Token{
  171. AccessToken: vals.Get("access_token"),
  172. TokenType: vals.Get("token_type"),
  173. RefreshToken: vals.Get("refresh_token"),
  174. Raw: vals,
  175. }
  176. e := vals.Get("expires_in")
  177. if e == "" {
  178. // TODO(jbd): Facebook's OAuth2 implementation is broken and
  179. // returns expires_in field in expires. Remove the fallback to expires,
  180. // when Facebook fixes their implementation.
  181. e = vals.Get("expires")
  182. }
  183. expires, _ := strconv.Atoi(e)
  184. if expires != 0 {
  185. token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
  186. }
  187. default:
  188. var tj tokenJSON
  189. if err = json.Unmarshal(body, &tj); err != nil {
  190. return nil, err
  191. }
  192. token = &Token{
  193. AccessToken: tj.AccessToken,
  194. TokenType: tj.TokenType,
  195. RefreshToken: tj.RefreshToken,
  196. Expiry: tj.expiry(),
  197. Raw: make(map[string]interface{}),
  198. }
  199. json.Unmarshal(body, &token.Raw) // no error checks for optional fields
  200. }
  201. // Don't overwrite `RefreshToken` with an empty value
  202. // if this was a token refreshing request.
  203. if token.RefreshToken == "" {
  204. token.RefreshToken = v.Get("refresh_token")
  205. }
  206. return token, nil
  207. }