Lex
Lex

Reputation: 396

How to log in as different user to Google API v3?

So I'm trying to create a new calendar, but i want to be able to specify what google account to create it in, assuming i have the credentials for said account, which i do. The code bellow creates it on the currently signed in user, or requires user interaction to allow access. Is there a way to specify an user and run the command on the background. I essentially just want to add a calendar to my account when the program runs, but i cant guarantee that my account will be logged in at the time.

I believe this was possible with the version 2 of the google api through ClientLogin, but i'm trying to use version 3.

import gflags
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
    client_id='MY_CLIENT_KEY',
    client_secret='MY_CLIENT_SECRET',
    scope='https://www.googleapis.com/auth/calendar',
    user_agent='MyApp/v1')
storage = Storage('calendar.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
  credentials = run(FLOW, storage)

http = httplib2.Http()
http = credentials.authorize(http)
service = build(serviceName='calendar', version='v3', http=http)

calendar = {
    'summary': 'Test3',
    'timeZone': 'America/New_York'
}

created_calendar = service.calendars().insert(body=calendar).execute()

Upvotes: 0

Views: 167

Answers (2)

luc
luc

Reputation: 3782

Another option would be to store the OAuth2 refresh token and use it to grab valid access tokens even if the user is not logged in. See my reply to google Calendar api v3 Auth only for first time

Upvotes: 0

Jay Lee
Jay Lee

Reputation: 13528

With V3, you'll need to use a Service Account in order to act as the user. The process is described in the Google Drive documentation, you just need to use Calendar API v3 scopes and references instead of Google Drive API.

Upvotes: 1

Related Questions