auth working, getting user data a problem
This commit is contained in:
168
rowers/polarstuff.py
Normal file
168
rowers/polarstuff.py
Normal file
@@ -0,0 +1,168 @@
|
||||
# All the functionality needed to connect to Strava
|
||||
|
||||
# Python
|
||||
import oauth2 as oauth
|
||||
import cgi
|
||||
import requests
|
||||
import requests.auth
|
||||
import json
|
||||
from django.utils import timezone
|
||||
from datetime import datetime
|
||||
import numpy as np
|
||||
from dateutil import parser
|
||||
import time
|
||||
import math
|
||||
from math import sin,cos,atan2,sqrt
|
||||
import os,sys
|
||||
import gzip
|
||||
import base64
|
||||
|
||||
# Django
|
||||
from django.shortcuts import render_to_response
|
||||
from django.http import HttpResponseRedirect, HttpResponse,JsonResponse
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import authenticate, login, logout
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.decorators import login_required
|
||||
|
||||
# Project
|
||||
# from .models import Profile
|
||||
from rowingdata import rowingdata
|
||||
import pandas as pd
|
||||
from rowers.models import Rower,Workout
|
||||
from rowers.models import checkworkoutuser
|
||||
import dataprep
|
||||
from dataprep import columndict
|
||||
|
||||
import stravalib
|
||||
from stravalib.exc import ActivityUploadFailed,TimeoutExceeded
|
||||
|
||||
from rowsandall_app.settings import (
|
||||
POLAR_CLIENT_ID, POLAR_REDIRECT_URI, POLAR_CLIENT_SECRET,
|
||||
)
|
||||
|
||||
# Custom exception handler, returns a 401 HTTP message
|
||||
# with exception details in the json data
|
||||
def custom_exception_handler(exc,message):
|
||||
|
||||
response = {
|
||||
"errors": [
|
||||
{
|
||||
"code": str(exc),
|
||||
"detail": message,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
res = HttpResponse(message)
|
||||
res.status_code = 401
|
||||
res.json = json.dumps(response)
|
||||
|
||||
return res
|
||||
|
||||
# Custom error class - to raise a NoTokenError
|
||||
class PolarNoTokenError(Exception):
|
||||
def __init__(self,value):
|
||||
self.value=value
|
||||
|
||||
def __str__(self):
|
||||
return repr(self.value)
|
||||
|
||||
|
||||
# Exchange access code for long-lived access token
|
||||
def get_token(code):
|
||||
|
||||
post_data = {"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": POLAR_REDIRECT_URI,
|
||||
}
|
||||
|
||||
auth_string = '{id}:{secret}'.format(
|
||||
id= POLAR_CLIENT_ID,
|
||||
secret=POLAR_CLIENT_SECRET
|
||||
)
|
||||
|
||||
headers = { 'Authorization': 'Basic %s' % base64.b64encode(auth_string) }
|
||||
|
||||
response = requests.post("https://polarremote.com/v2/oauth2/token",
|
||||
data=post_data,
|
||||
headers=headers)
|
||||
|
||||
|
||||
try:
|
||||
token_json = response.json()
|
||||
thetoken = token_json['access_token']
|
||||
expires_in = token_json['expires_in']
|
||||
user_id = token_json['x_user_id']
|
||||
except KeyError:
|
||||
thetoken = 0
|
||||
expires_in = 0
|
||||
|
||||
return [thetoken,expires_in,user_id]
|
||||
|
||||
# Make authorization URL including random string
|
||||
def make_authorization_url(request):
|
||||
# Generate a random string for the state parameter
|
||||
# Save it for use later to prevent xsrf attacks
|
||||
from uuid import uuid4
|
||||
state = str(uuid4())
|
||||
|
||||
params = {"client_id": POLAR_CLIENT_ID,
|
||||
"response_type": "code",
|
||||
"redirect_uri": POLAR_REDIRECT_URI,
|
||||
"scope":"write"}
|
||||
import urllib
|
||||
url = "https://flow.polar.com/oauth2/authorization" +urllib.urlencode(params)
|
||||
|
||||
return HttpResponseRedirect(url)
|
||||
|
||||
def get_polar_workout_list(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.polartoken == '') or (r.polartoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (timezone.now()>r.polartokenexpirydate):
|
||||
s = "Token expired. Needs to refresh"
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
authorizationstring = str('Bearer ' + r.polartoken)
|
||||
headers = {'Authorization':authorizationstring,
|
||||
'Accept': 'application/json'}
|
||||
|
||||
url = 'https://polaraccesslink.com/v3/users/{userid}/exercise-transactions'.format(
|
||||
userid = r.polaruserid
|
||||
)
|
||||
|
||||
response = requests.post(url, headers=headers)
|
||||
|
||||
return response
|
||||
|
||||
def get_polar_user_info(user):
|
||||
r = Rower.objects.get(user=user)
|
||||
if (r.polartoken == '') or (r.polartoken is None):
|
||||
s = "Token doesn't exist. Need to authorize"
|
||||
return custom_exception_handler(401,s)
|
||||
elif (timezone.now()>r.polartokenexpirydate):
|
||||
s = "Token expired. Needs to refresh"
|
||||
return custom_exception_handler(401,s)
|
||||
else:
|
||||
authorizationstring = str('Bearer ' + r.polartoken)
|
||||
headers = {
|
||||
'Authorization':authorizationstring,
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
|
||||
params = {
|
||||
'user-id': r.polaruserid
|
||||
}
|
||||
|
||||
url = 'https://polaraccesslink.com/v3/users/{userid}'.format(
|
||||
userid = r.polaruserid
|
||||
)
|
||||
|
||||
|
||||
print url
|
||||
response = requests.get(url, headers=headers)
|
||||
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user