apps.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package mastodon
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "net/url"
  7. "path"
  8. "strings"
  9. )
  10. // AppConfig is a setting for registering applications.
  11. type AppConfig struct {
  12. Server string
  13. ClientName string
  14. // Where the user should be redirected after authorization (for no redirect, use urn:ietf:wg:oauth:2.0:oob)
  15. RedirectURIs string
  16. // This can be a space-separated list of items listed on the /settings/applications/new page of any Mastodon
  17. // instance. "read", "write", and "follow" are top-level scopes that include all the permissions of the more
  18. // specific scopes like "read:favourites", "write:statuses", and "write:follows".
  19. Scopes string
  20. // Optional.
  21. Website string
  22. }
  23. // Application is mastodon application.
  24. type Application struct {
  25. ID string `json:"id"`
  26. RedirectURI string `json:"redirect_uri"`
  27. ClientID string `json:"client_id"`
  28. ClientSecret string `json:"client_secret"`
  29. // AuthURI is not part of the Mastodon API; it is generated by go-mastodon.
  30. AuthURI string `json:"auth_uri,omitempty"`
  31. }
  32. // RegisterApp returns the mastodon application.
  33. func RegisterApp(ctx context.Context, appConfig *AppConfig) (*Application, error) {
  34. params := url.Values{}
  35. params.Set("client_name", appConfig.ClientName)
  36. if appConfig.RedirectURIs == "" {
  37. params.Set("redirect_uris", "urn:ietf:wg:oauth:2.0:oob")
  38. } else {
  39. params.Set("redirect_uris", appConfig.RedirectURIs)
  40. }
  41. params.Set("scopes", appConfig.Scopes)
  42. u, err := url.Parse(appConfig.Server)
  43. if err != nil {
  44. return nil, err
  45. }
  46. u.Path = path.Join(u.Path, "/api/v1/apps")
  47. req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(params.Encode()))
  48. if err != nil {
  49. return nil, err
  50. }
  51. req = req.WithContext(ctx)
  52. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  53. resp, err := httpClient.Do(req)
  54. if err != nil {
  55. return nil, err
  56. }
  57. defer resp.Body.Close()
  58. if resp.StatusCode != http.StatusOK {
  59. return nil, parseAPIError("bad request", resp)
  60. }
  61. var app Application
  62. err = json.NewDecoder(resp.Body).Decode(&app)
  63. if err != nil {
  64. return nil, err
  65. }
  66. u, err = url.Parse(appConfig.Server)
  67. if err != nil {
  68. return nil, err
  69. }
  70. u.Path = path.Join(u.Path, "/oauth/authorize")
  71. u.RawQuery = url.Values{
  72. "scope": {appConfig.Scopes},
  73. "response_type": {"code"},
  74. "redirect_uri": {app.RedirectURI},
  75. "client_id": {app.ClientID},
  76. }.Encode()
  77. app.AuthURI = u.String()
  78. return &app, nil
  79. }