config.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package oauth
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/base64"
  6. "time"
  7. "github.com/porter-dev/porter/internal/models/integrations"
  8. "github.com/porter-dev/porter/internal/repository"
  9. "golang.org/x/oauth2"
  10. )
  11. type Config struct {
  12. ClientID string
  13. ClientSecret string
  14. Scopes []string
  15. BaseURL string
  16. }
  17. func NewGithubClient(cfg *Config) *oauth2.Config {
  18. return &oauth2.Config{
  19. ClientID: cfg.ClientID,
  20. ClientSecret: cfg.ClientSecret,
  21. Endpoint: oauth2.Endpoint{
  22. AuthURL: "https://github.com/login/oauth/authorize",
  23. TokenURL: "https://github.com/login/oauth/access_token",
  24. },
  25. RedirectURL: cfg.BaseURL + "/api/oauth/github/callback",
  26. Scopes: cfg.Scopes,
  27. }
  28. }
  29. func NewDigitalOceanClient(cfg *Config) *oauth2.Config {
  30. return &oauth2.Config{
  31. ClientID: cfg.ClientID,
  32. ClientSecret: cfg.ClientSecret,
  33. Endpoint: oauth2.Endpoint{
  34. AuthURL: "https://cloud.digitalocean.com/v1/oauth/authorize",
  35. TokenURL: "https://cloud.digitalocean.com/v1/oauth/token",
  36. },
  37. RedirectURL: cfg.BaseURL + "/api/oauth/digitalocean/callback",
  38. Scopes: cfg.Scopes,
  39. }
  40. }
  41. func CreateRandomState() string {
  42. b := make([]byte, 16)
  43. rand.Read(b)
  44. state := base64.URLEncoding.EncodeToString(b)
  45. return state
  46. }
  47. // GetAccessToken retrieves an access token for a given client. It updates the
  48. // access token in the DB if necessary
  49. func GetAccessToken(
  50. o *integrations.OAuthIntegration,
  51. conf *oauth2.Config,
  52. repo repository.Repository,
  53. ) (string, *time.Time, error) {
  54. tokSource := conf.TokenSource(context.TODO(), &oauth2.Token{
  55. AccessToken: string(o.AccessToken),
  56. RefreshToken: string(o.RefreshToken),
  57. TokenType: "Bearer",
  58. })
  59. token, err := tokSource.Token()
  60. if err != nil {
  61. return "", nil, err
  62. }
  63. if token.AccessToken != string(o.AccessToken) {
  64. o.AccessToken = []byte(token.AccessToken)
  65. o.RefreshToken = []byte(token.RefreshToken)
  66. o, err = repo.OAuthIntegration.UpdateOAuthIntegration(o)
  67. if err != nil {
  68. return "", nil, err
  69. }
  70. }
  71. return token.AccessToken, &token.Expiry, nil
  72. }