Alex Luis Arias
Alex Luis Arias

Reputation: 1394

Golang gads Package Authentication without File

I'm trying to use a google adwords api golang package I found. However, this package only has methods/functions for authenticating against a file that contains all the credentials. I am very new to Golang so I'm not sure how to go about creating a new function to authenticate using string variables that contain the necessary information.

The package can be found at: https://github.com/emiddleton/gads

I did some digging to see if I can figure it out. I found an example for the structure of the file that contains the information. Here's an example:

 {
     "oauth2.Config": {
         "ClientID": "4585432543254323-f4qfewtg2qtg5esy24t45h.apps.googleusercontent.com",
         "ClientSecret": "fa74ehgyjhtrrjtbrsu56hHjhhrtger",
         "Endpoint": {
             "AuthURL": "https://accounts.google.com/o/oauth2/auth",
             "TokenURL": "https://accounts.google.com/o/oauth2/token"
         },
         "RedirectURL": "oob",
         "Scopes": [
             "https://adwords.google.com/api/adwords"
         ]
     },
     "oauth2.Token": {
         "access_token": "jfdsalkfjdskalfjdaksfdasfdsahrtsrgf",
         "token_type": "Bearer",
         "refresh_token": "g65wurefej87ruy4fcyfdsafdsafdsafsdaf4fu",
         "expiry": "2015-03-05T00:13:23.382907238+09:00"
     },
     "gads.Auth": {
         "CustomerId": "INSERT_YOUR_CLIENT_CUSTOMER_ID_HERE",
         "DeveloperToken": "INSERT_YOUR_DEVELOPER_TOKEN_HERE",
         "UserAgent": "tests (Golang 1.4 github.com/emiddleton/gads)"
     }
 }

It's a JSON object. I see the package is using the following function to bring in the information:

func NewCredentialsFromFile(pathToFile string, ctx context.Context) (ac AuthConfig, err error) {
    data, err := ioutil.ReadFile(pathToFile)
    if err != nil {
        return ac, err
    }
    if err := json.Unmarshal(data, &ac); err != nil {
        return ac, err
    }
    ac.file = pathToFile
    ac.tokenSource = ac.OAuth2Config.TokenSource(ctx, ac.OAuth2Token)
    ac.Auth.Client = ac.OAuth2Config.Client(ctx, ac.OAuth2Token)
    return ac, err

Where pathToFile is is already defined. The path would be to the json file that would be placed in the user's home directory.

What would be the best way to add another function that does not rely on using a file for the credentials?

Upvotes: 1

Views: 298

Answers (1)

RickyA
RickyA

Reputation: 16029

Assuming you have the credentials in a string as json, make the AuthConfig in your code like:

func NewCredentialsFromStr(config string, ctx context.Context) (ac gads.AuthConfig, err error) {
    if err := json.Unmarshal(config, &ac); err != nil {
        return ac, err
    }
    ac.file = pathToFile
    ac.tokenSource = ac.OAuth2Config.TokenSource(ctx, ac.OAuth2Token)
    ac.Auth.Client = ac.OAuth2Config.Client(ctx, ac.OAuth2Token)
    return ac, err
}

Upvotes: 2

Related Questions