client.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Oauth2 google api for Drive api
  2. package gdrivefs
  3. import (
  4. "context"
  5. "fmt"
  6. drive "google.golang.org/api/drive/v3"
  7. "dev.hexasoftware.com/hxs/cloudmount/internal/core"
  8. "golang.org/x/oauth2"
  9. )
  10. func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
  11. authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
  12. fmt.Printf(
  13. `Go to the following link in your browser:
  14. ----------------------------------------------------------------------------------------------
  15. %v
  16. ----------------------------------------------------------------------------------------------
  17. type the authorization code: `, authURL)
  18. var code string
  19. if _, err := fmt.Scan(&code); err != nil {
  20. log.Fatalf("Unable to read authorization code %v", err)
  21. }
  22. tok, err := config.Exchange(oauth2.NoContext, code)
  23. if err != nil {
  24. log.Fatalf("Unable to retrieve token from web: %v", err)
  25. }
  26. return tok
  27. }
  28. // Init driveService
  29. func (d *GDriveFS) initClient() {
  30. //configPath := d.config.HomeDir
  31. ctx := context.Background() // Context from GDriveFS
  32. log.Println("Initializing gdrive service")
  33. log.Println("Source config:", d.config.Source)
  34. err := core.ParseConfig(d.config.Source, d.serviceConfig)
  35. //b, err := ioutil.ReadFile(d.config.Source)
  36. //b, err := ioutil.ReadFile(filepath.Join(configPath, "client_secret.json"))
  37. if err != nil {
  38. log.Fatalf("Unable to read client secret file: %v", err)
  39. }
  40. config := &oauth2.Config{
  41. ClientID: d.serviceConfig.ClientSecret.ClientID,
  42. ClientSecret: d.serviceConfig.ClientSecret.ClientSecret,
  43. RedirectURL: "urn:ietf:wg:oauth:2.0:oob", //d.serviceConfig.ClientSecret.RedirectURIs[0],
  44. Scopes: []string{drive.DriveScope},
  45. Endpoint: oauth2.Endpoint{
  46. AuthURL: "https://accounts.google.com/o/oauth2/auth", //d.serviceConfig.ClientSecret.AuthURI,
  47. TokenURL: "https://accounts.google.com/o/oauth2/token", //d.serviceConfig.ClientSecret.TokenURI,
  48. },
  49. }
  50. // We can deal with oauthToken here too
  51. if d.serviceConfig.Auth == nil {
  52. tok := getTokenFromWeb(config)
  53. d.serviceConfig.Auth = tok
  54. core.SaveConfig(d.config.Source, d.serviceConfig)
  55. }
  56. /*config, err := google.ConfigFromJSON(b, drive.DriveScope)
  57. if err != nil {
  58. log.Fatalf("Unable to parse client secret file: %v", err)
  59. }*/
  60. client := config.Client(ctx, d.serviceConfig.Auth)
  61. d.client, err = drive.New(client)
  62. if err != nil {
  63. log.Fatalf("Unable to retrieve drive Client: %v", err)
  64. }
  65. }