path.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package token
  2. import (
  3. "fmt"
  4. "net/url"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. homedir "github.com/mitchellh/go-homedir"
  9. "github.com/cloudflare/cloudflared/config"
  10. )
  11. // GenerateSSHCertFilePathFromURL will return a file path for creating short lived certificates
  12. func GenerateSSHCertFilePathFromURL(url *url.URL, suffix string) (string, error) {
  13. configPath, err := getConfigPath()
  14. if err != nil {
  15. return "", err
  16. }
  17. name := strings.Replace(fmt.Sprintf("%s%s-%s", url.Hostname(), url.EscapedPath(), suffix), "/", "-", -1)
  18. return filepath.Join(configPath, name), nil
  19. }
  20. // GenerateAppTokenFilePathFromURL will return a filepath for given Access org token
  21. func GenerateAppTokenFilePathFromURL(appDomain, aud string, suffix string) (string, error) {
  22. configPath, err := getConfigPath()
  23. if err != nil {
  24. return "", err
  25. }
  26. name := fmt.Sprintf("%s-%s-%s", appDomain, aud, suffix)
  27. name = strings.Replace(strings.Replace(name, "/", "-", -1), "*", "-", -1)
  28. return filepath.Join(configPath, name), nil
  29. }
  30. // generateOrgTokenFilePathFromURL will return a filepath for given Access application token
  31. func generateOrgTokenFilePathFromURL(authDomain string) (string, error) {
  32. configPath, err := getConfigPath()
  33. if err != nil {
  34. return "", err
  35. }
  36. name := strings.Replace(fmt.Sprintf("%s-org-token", authDomain), "/", "-", -1)
  37. return filepath.Join(configPath, name), nil
  38. }
  39. func getConfigPath() (string, error) {
  40. configPath, err := homedir.Expand(config.DefaultConfigSearchDirectories()[0])
  41. if err != nil {
  42. return "", err
  43. }
  44. ok, err := config.FileExists(configPath)
  45. if !ok && err == nil {
  46. // create config directory if doesn't already exist
  47. err = os.Mkdir(configPath, 0700)
  48. }
  49. return configPath, err
  50. }