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.

mastodon.go 4.9KB

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