auth_utils.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. ACCESS_TOKEN_URI = settings.HOST_URI + '/token'
  8. def get_auth_header():
  9. # Make a header with access key for making request in google-my-business server.
  10. access_token = get(ACCESS_TOKEN_URI).text
  11. headers = {
  12. 'authorization': 'Bearer ' + access_token,
  13. 'content-type': 'application/json'
  14. }
  15. return headers
  16. def has_expired(credentials):
  17. expiry_time = credentials['expiry']
  18. now = str(timezone.datetime.now())
  19. return now > expiry_time
  20. def get_access_token(request):
  21. if 'credentials' in request.session and not has_expired(request.session['credentials']):
  22. cred = request.session['credentials']
  23. return cred['access_token']
  24. access_token, expires_in = refresh_access_token()
  25. expired_at = timezone.datetime.now() + timezone.timedelta(seconds=expires_in)
  26. expiry = str(expired_at)
  27. credentials = {
  28. 'access_token': access_token,
  29. 'expiry': expiry
  30. }
  31. request.session['credentials'] = credentials
  32. return credentials['access_token']
  33. def refresh_access_token():
  34. user = User.objects.filter(username='admin@ercare').first()
  35. uid = user.id
  36. user = UserModel.objects.filter(pk=uid).first()
  37. if user:
  38. refresh_token = user.refresh_token
  39. else:
  40. return None
  41. client_id = settings.CLIENT_ID
  42. client_secret = settings.CLIENT_SECRET
  43. token_uri = settings.TOKEN_URI
  44. params = {
  45. "grant_type": "refresh_token",
  46. "client_id": client_id,
  47. "client_secret": client_secret,
  48. "refresh_token": refresh_token
  49. }
  50. response = post(token_uri, data=params).json()
  51. access_token = response.get('access_token')
  52. expires_in = response.get('expires_in')
  53. return access_token, expires_in
  54. def get_google_account_id(access_token):
  55. uri = 'https://mybusiness.googleapis.com/v4/accounts'
  56. headers = {
  57. 'authorization': 'Bearer '+access_token,
  58. 'content-type': 'application/json'
  59. }
  60. res = get(uri, headers=headers).json()
  61. accounts_name = res['accounts'][0]['name']
  62. id = accounts_name.split('/')[-1]
  63. return id
  64. def get_gmb_id():
  65. user = User.objects.get(username='admin@ercare')
  66. gmb_id = UserModel.objects.get(user=user).gmb_account_id
  67. return user, gmb_id