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

188 lines
5.1KB

  1. // Package gitlab implements the OAuth2 protocol for authenticating users through gitlab.
  2. // This package can be used as a reference implementation of an OAuth2 provider for Goth.
  3. package gitlab
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "fmt"
  13. "github.com/markbates/goth"
  14. "golang.org/x/oauth2"
  15. )
  16. // These vars define the Authentication, Token, and Profile URLS for Gitlab. If
  17. // using Gitlab CE or EE, you should change these values before calling New.
  18. //
  19. // Examples:
  20. // gitlab.AuthURL = "https://gitlab.acme.com/oauth/authorize
  21. // gitlab.TokenURL = "https://gitlab.acme.com/oauth/token
  22. // gitlab.ProfileURL = "https://gitlab.acme.com/api/v3/user
  23. var (
  24. AuthURL = "https://gitlab.com/oauth/authorize"
  25. TokenURL = "https://gitlab.com/oauth/token"
  26. ProfileURL = "https://gitlab.com/api/v3/user"
  27. )
  28. // Provider is the implementation of `goth.Provider` for accessing Gitlab.
  29. type Provider struct {
  30. ClientKey string
  31. Secret string
  32. CallbackURL string
  33. HTTPClient *http.Client
  34. config *oauth2.Config
  35. providerName string
  36. authURL string
  37. tokenURL string
  38. profileURL string
  39. }
  40. // New creates a new Gitlab provider and sets up important connection details.
  41. // You should always call `gitlab.New` to get a new provider. Never try to
  42. // create one manually.
  43. func New(clientKey, secret, callbackURL string, scopes ...string) *Provider {
  44. return NewCustomisedURL(clientKey, secret, callbackURL, AuthURL, TokenURL, ProfileURL, scopes...)
  45. }
  46. // NewCustomisedURL is similar to New(...) but can be used to set custom URLs to connect to
  47. func NewCustomisedURL(clientKey, secret, callbackURL, authURL, tokenURL, profileURL string, scopes ...string) *Provider {
  48. p := &Provider{
  49. ClientKey: clientKey,
  50. Secret: secret,
  51. CallbackURL: callbackURL,
  52. providerName: "gitlab",
  53. profileURL: profileURL,
  54. }
  55. p.config = newConfig(p, authURL, tokenURL, scopes)
  56. return p
  57. }
  58. // Name is the name used to retrieve this provider later.
  59. func (p *Provider) Name() string {
  60. return p.providerName
  61. }
  62. // SetName is to update the name of the provider (needed in case of multiple providers of 1 type)
  63. func (p *Provider) SetName(name string) {
  64. p.providerName = name
  65. }
  66. func (p *Provider) Client() *http.Client {
  67. return goth.HTTPClientWithFallBack(p.HTTPClient)
  68. }
  69. // Debug is a no-op for the gitlab package.
  70. func (p *Provider) Debug(debug bool) {}
  71. // BeginAuth asks Gitlab for an authentication end-point.
  72. func (p *Provider) BeginAuth(state string) (goth.Session, error) {
  73. return &Session{
  74. AuthURL: p.config.AuthCodeURL(state),
  75. }, nil
  76. }
  77. // FetchUser will go to Gitlab and access basic information about the user.
  78. func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
  79. sess := session.(*Session)
  80. user := goth.User{
  81. AccessToken: sess.AccessToken,
  82. Provider: p.Name(),
  83. RefreshToken: sess.RefreshToken,
  84. ExpiresAt: sess.ExpiresAt,
  85. }
  86. if user.AccessToken == "" {
  87. // data is not yet retrieved since accessToken is still empty
  88. return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName)
  89. }
  90. response, err := p.Client().Get(p.profileURL + "?access_token=" + url.QueryEscape(sess.AccessToken))
  91. if err != nil {
  92. if response != nil {
  93. response.Body.Close()
  94. }
  95. return user, err
  96. }
  97. defer response.Body.Close()
  98. if response.StatusCode != http.StatusOK {
  99. return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode)
  100. }
  101. bits, err := ioutil.ReadAll(response.Body)
  102. if err != nil {
  103. return user, err
  104. }
  105. err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData)
  106. if err != nil {
  107. return user, err
  108. }
  109. err = userFromReader(bytes.NewReader(bits), &user)
  110. return user, err
  111. }
  112. func newConfig(provider *Provider, authURL, tokenURL string, scopes []string) *oauth2.Config {
  113. c := &oauth2.Config{
  114. ClientID: provider.ClientKey,
  115. ClientSecret: provider.Secret,
  116. RedirectURL: provider.CallbackURL,
  117. Endpoint: oauth2.Endpoint{
  118. AuthURL: authURL,
  119. TokenURL: tokenURL,
  120. },
  121. Scopes: []string{},
  122. }
  123. if len(scopes) > 0 {
  124. for _, scope := range scopes {
  125. c.Scopes = append(c.Scopes, scope)
  126. }
  127. }
  128. return c
  129. }
  130. func userFromReader(r io.Reader, user *goth.User) error {
  131. u := struct {
  132. Name string `json:"name"`
  133. Email string `json:"email"`
  134. NickName string `json:"username"`
  135. ID int `json:"id"`
  136. AvatarURL string `json:"avatar_url"`
  137. }{}
  138. err := json.NewDecoder(r).Decode(&u)
  139. if err != nil {
  140. return err
  141. }
  142. user.Email = u.Email
  143. user.Name = u.Name
  144. user.NickName = u.NickName
  145. user.UserID = strconv.Itoa(u.ID)
  146. user.AvatarURL = u.AvatarURL
  147. return nil
  148. }
  149. //RefreshTokenAvailable refresh token is provided by auth provider or not
  150. func (p *Provider) RefreshTokenAvailable() bool {
  151. return true
  152. }
  153. //RefreshToken get new access token based on the refresh token
  154. func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
  155. token := &oauth2.Token{RefreshToken: refreshToken}
  156. ts := p.config.TokenSource(goth.ContextForClient(p.Client()), token)
  157. newToken, err := ts.Token()
  158. if err != nil {
  159. return nil, err
  160. }
  161. return newToken, err
  162. }
上海开阖软件有限公司 沪ICP备12045867号-1