config.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 NewGoogleClient(cfg *Config) *oauth2.Config {
  42. return &oauth2.Config{
  43. ClientID: cfg.ClientID,
  44. ClientSecret: cfg.ClientSecret,
  45. Endpoint: oauth2.Endpoint{
  46. AuthURL: "https://accounts.google.com/o/oauth2/v2/auth",
  47. TokenURL: "https://oauth2.googleapis.com/token",
  48. },
  49. RedirectURL: cfg.BaseURL + "/api/oauth/google/callback",
  50. Scopes: cfg.Scopes,
  51. }
  52. }
  53. func CreateRandomState() string {
  54. b := make([]byte, 16)
  55. rand.Read(b)
  56. state := base64.URLEncoding.EncodeToString(b)
  57. return state
  58. }
  59. // GetAccessToken retrieves an access token for a given client. It updates the
  60. // access token in the DB if necessary
  61. func GetAccessToken(
  62. o *integrations.OAuthIntegration,
  63. conf *oauth2.Config,
  64. repo repository.Repository,
  65. ) (string, *time.Time, error) {
  66. tokSource := conf.TokenSource(context.TODO(), &oauth2.Token{
  67. AccessToken: string(o.AccessToken),
  68. RefreshToken: string(o.RefreshToken),
  69. TokenType: "Bearer",
  70. })
  71. token, err := tokSource.Token()
  72. if err != nil {
  73. return "", nil, err
  74. }
  75. if token.AccessToken != string(o.AccessToken) {
  76. o.AccessToken = []byte(token.AccessToken)
  77. o.RefreshToken = []byte(token.RefreshToken)
  78. o, err = repo.OAuthIntegration.UpdateOAuthIntegration(o)
  79. if err != nil {
  80. return "", nil, err
  81. }
  82. }
  83. return token.AccessToken, &token.Expiry, nil
  84. }