Skip to content

Commit

Permalink
Merge pull request #1111 from mozilla/check-for-expired-FXA-access-to…
Browse files Browse the repository at this point in the history
…kens

refresh access tokens automatically, or log the user out
  • Loading branch information
say-yawn authored Sep 17, 2021
2 parents f206dd9 + bf892ab commit 9dd8800
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
25 changes: 25 additions & 0 deletions privaterelay/middleware.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
from datetime import datetime, timezone
import time

import markus
from oauthlib.oauth2.rfc6749.errors import CustomOAuth2Error

from django.contrib.auth import logout
from django.shortcuts import redirect
from django.urls import reverse

from allauth.socialaccount.models import SocialToken
from allauth.socialaccount.providers.fxa.views import (
FirefoxAccountsOAuth2Adapter
)

from .views import _get_oauth2_session, update_social_token

metrics = markus.get_metrics('fx-private-relay')

Expand All @@ -21,6 +33,19 @@ def __call__(self, request):
if not fxa_account:
return self.get_response(request)

social_token = SocialToken.objects.get(account=fxa_account)
# if the user's FXA access token has expired; try to get a new one
if social_token.expires_at < datetime.now(timezone.utc):
try:
client = _get_oauth2_session(fxa_account)
new_token = client.refresh_token(
FirefoxAccountsOAuth2Adapter.access_token_url
)
update_social_token(social_token, new_token)
except CustomOAuth2Error:
logout(request)
return redirect(reverse('home'))

request.fxa_account = fxa_account
return self.get_response(request)

Expand Down
17 changes: 10 additions & 7 deletions privaterelay/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,13 +306,7 @@ def _get_oauth2_session(social_account):
social_token = social_account.socialtoken_set.first()

def _token_updater(new_token):
social_token.token = new_token['access_token']
social_token.token_secret = new_token['refresh_token']
social_token.expires_at = (
datetime.now(timezone.utc) +
timedelta(seconds=int(new_token['expires_in']))
)
social_token.save()
update_social_token(social_token, new_token)

client_id = social_token.app.client_id
client_secret = social_token.app.secret
Expand All @@ -337,3 +331,12 @@ def _token_updater(new_token):
auto_refresh_kwargs=extra, token_updater=_token_updater
)
return client

def update_social_token(existing_social_token, new_oauth2_token):
existing_social_token.token = new_oauth2_token['access_token']
existing_social_token.token_secret = new_oauth2_token['refresh_token']
existing_social_token.expires_at = (
datetime.now(timezone.utc) +
timedelta(seconds=int(new_oauth2_token['expires_in']))
)
existing_social_token.save()

0 comments on commit 9dd8800

Please sign in to comment.