utils.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from django.contrib.auth.models import User
  2. from django.utils import timezone
  3. from requests import post
  4. from django.conf import settings
  5. from .models import UserModel
  6. from requests import get
  7. def has_expired(credentials):
  8. expiry_time = credentials['expiry']
  9. now = str(timezone.datetime.now())
  10. return now > expiry_time
  11. def get_access_token(request):
  12. if 'credentials' in request.session and not has_expired(request.session['credentials']):
  13. cred = request.session['credentials']
  14. return cred['access_token']
  15. access_token, expires_in = refresh_access_token()
  16. expired_at = timezone.datetime.now() + timezone.timedelta(seconds=expires_in)
  17. expiry = str(expired_at)
  18. credentials = {
  19. 'access_token': access_token,
  20. 'expiry': expiry
  21. }
  22. request.session['credentials'] = credentials
  23. return credentials['access_token']
  24. def refresh_access_token():
  25. user = User.objects.filter(username='admin@ercare').first()
  26. uid = user.id
  27. user = UserModel.objects.filter(pk=uid).first()
  28. if user:
  29. refresh_token = user.refresh_token
  30. else:
  31. return None
  32. client_id = settings.CLIENT_ID
  33. client_secret = settings.CLIENT_SECRET
  34. token_uri = settings.TOKEN_URI
  35. params = {
  36. "grant_type": "refresh_token",
  37. "client_id": client_id,
  38. "client_secret": client_secret,
  39. "refresh_token": refresh_token
  40. }
  41. response = post(token_uri, data=params).json()
  42. access_token = response['access_token']
  43. expires_in = response['expires_in']
  44. return access_token, expires_in
  45. def get_google_account_id(access_token):
  46. uri = 'https://mybusiness.googleapis.com/v4/accounts'
  47. headers = {
  48. 'authorization': 'Bearer '+access_token,
  49. 'content-type': 'application/json'
  50. }
  51. res = get(uri, headers=headers).json()
  52. accounts_name = res['accounts'][0]['name']
  53. id = accounts_name.split('/')[-1]
  54. return id