John R Perry
John R Perry

Reputation: 4202

How to get or create credentials from authenticated user in django-allauth

I think I might be missing something obvious, but I cannot figure out the answer to my question.

I have setup django-allauth on my project, added Google auth, enabled the API, ran the server, and successfully used the app for authentication.

Here's where I'm getting stuck:

Once the user is authenticated, I'm wanting the user to be able to view their calendar but I cannot figure out how to build the credentials using the credentials of the already authenticated user.

I know that in order to get the calendar, I have to run:

service = build('calendar', 'v3', credentials=creds)
calendar = service.calendars().get(calendarId='primary').execute()
print(calendar['summary'])

but I cannot figure out how to build the value for credentials

Any help would be so greatly appreciated.

Upvotes: 3

Views: 770

Answers (1)

John R Perry
John R Perry

Reputation: 4202

I was able to find the answer.

  1. django-auth creates an instance of a SocialToken when a user is authenticated.
  2. That token can be found by passing request.user to the model object's get method.
  3. Once you have the token, the token's fields are passed to the parameters of the constructor to create the credential object that is necessary for the build function.

Example:

from google.oauth2.credentials import Credentials

social_token = SocialToken.objects.get(account__user=request.user)
creds = Credentials(token=social_token.token,
                    refresh_token=social_token.token_secret,
                    client_id=social_token.app.client_id,
                    client_secret=social_token.app.secret)
service = build('calendar', 'v3', credentials=creds)
calendar = service.calendars().get(calendarId='primary').execute()

Upvotes: 3

Related Questions