def create_fitbit(self, **kwargs): defaults = { 'client_key': self.random_string(25), 'client_secret': self.random_string(25), } defaults.update(kwargs) return Fitbit(**defaults)
def run(self): print('start') try: date_start = self.config.get('variable', 'date_start') date_start = datetime.strptime(date_start, '%Y-%m-%d').date() date_end = self.config.get('variable', 'date_end') date_end = datetime.strptime(date_end, '%Y-%m-%d').date() if self.token: refresh_token = self.config.get( 'connection', 'refresh_token') self.server.fitbit = Fitbit(self.client_id, self.client_secret, access_token=self.token, refresh_token=refresh_token, refresh_cb=self.token_updater) self.test_connection(self.server.fitbit) else: self.server.browser_authorize() self.test_connection(self.server.fitbit) self.token_updater(self.server.fitbit.client.session.token) if date_start and date_end: self.save_all(date_start, date_end) else: self.save_all(self.yesterday, self.today) print('finish') except fitbit.api.exceptions.HTTPTooManyRequests as e: print('too many requests! waiting {0} minutes'.format( e.retry_after_secs % 60)) print('exit') finally: influx.import_data()
def create_fitbit_with_cookies(request): access_token = request.COOKIES.get('token') refresh_token = request.COOKIES.get('refresh') expires_at = request.COOKIES.get('expires_at') # refresh_cb = request.COOKIES.get('refresh_cb') fitbit = Fitbit(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=redirect_uri, timeout=10, access_token=access_token , refresh_token=refresh_token, expires_at=expires_at) return fitbit
def fitbit_login(request): fitbit = Fitbit(CLIENT_ID, CLIENT_SECRET, redirect_uri, timeout=10) url, _ = fitbit.client.authorize_token_url(prompt="login") threading.Timer(1, webbrowser.open, args=(url, )).start() return HttpResponse("")
def __init__(self, fb_client_id, fb_client_secret, redirect_url='http://127.0.0.1:8080'): """Initialize an OAuth2 client using python-fitbit""" self.success = """<h1>Fitbit authentication Successful!</h1>""" self.fitbit = Fitbit(fb_client_id, fb_client_secret, redirect_uri=redirect_url, timeout=15)
def __init__(self, client_id, client_secret, redirect_uri=None): """ Initialize the FitbitOauth2Client """ self._client_id = client_id self._client_secret = client_secret self._redirect_uri = redirect_uri self._fitbit = Fitbit( client_id, client_secret, redirect_uri=redirect_uri, timeout=10, )
def fitbit_registration(): f = Fitbit( current_user.client_id, current_user.client_secret, redirect_uri=os.getenv('REDIRECT_URI'), scope=['activity'], timeout=10, ) url, _ = f.client.authorize_token_url() return render_template('fitbit_registration.html', user=current_user, url=url)
def __init__(self, client_id, client_secret, redirect_uri): """ Initialize the FitbitOauth2Client """ self.success_html = """ <h1>You are now authorized to access the Fitbit API!</h1> <br/><h3>You can close this window</h3>""" self.failure_html = """ <h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s""" self.fitbit = Fitbit( client_id, client_secret, redirect_uri=redirect_uri, timeout=10, )
def __init__(self, credentials='credentials/key_FITBIT.json', redirect_uri='http://127.0.0.1:8080/'): """ Initialize the FitbitOauth2Client """ self.success_html = """ <h1>You are now authorized to access the Fitbit API!</h1> <br/><h3>You can close this window</h3>""" self.failure_html = """ <h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s""" with open(credentials) as raw: crd = json.load(raw) arg = {'redirect_uri': redirect_uri, 'timeout': 100} self.fitbit = Fitbit(crd['id'], crd['key'], **arg)
def __init__(self, credentials='credentials/key_FITBIT.json'): warnings.simplefilter('ignore') server = OAuth2Server(credentials=credentials) server.browser_authorize() cfg = { 'access_token': str(server.fitbit.client.session.token['access_token']), 'refresh_token': str(server.fitbit.client.session.token['refresh_token']) } with open(credentials) as raw: crd = json.load(raw) self.client = Fitbit(crd['id'], crd['key'], oauth2=True, **cfg)
def login(): try: if 'email' in session: email = session['email'] print("email is...") print(email) else: email = '' session['email'] = email if 'access-token' in request.args: access_token = request.args.get('access-token') if 'refresh-token' in request.args: refresh_token = request.args.get('refresh-token') if 'userId' in request.args: user_key = request.args.get('userId') if 'secretKey' in request.args: user_secret = request.args.get('secretKey') global fit fit = Fitbit(user_key, user_secret, access_token=access_token, refresh_token=refresh_token) session['fitbit_keys'] = (email, user_key, user_secret) query = "SELECT userId,Type FROM users WHERE EmailId = :email" data = {"email": email} userId = mysql.query_db(query, data)[0]['userId'] session['user_Id'] = userId session['typeUser'] = mysql.query_db(query, data)[0]['Type'] query1 = "SELECT Weight, Gender, Height, Goal, BMI, Age FROM UserProfile WHERE UserId = :userId" data1 = {"userId": userId} userProf = mysql.query_db(query1, data1)[0] if userProf is not None: session['weight'] = userProf['Weight'] session['height'] = userProf['Height'] session['gender'] = userProf['Gender'] session['goal'] = userProf['Goal'] session['bmi'] = userProf['BMI'] session['age'] = userProf['Age'] else: print("userId is...") session['user_profile'] = fit.user_profile_get() session['functionName'] = 'OnLogin' except Exception as error: logging.exception("message") return redirect(url_for('getDashboardData'))
def __init__(self, client_id, client_secret, redirect_uri='http://127.0.0.1:8080/'): """ Initialize the FitbitOauth2Client """ #The original text that went in success_html >> # "You are now authorized to access the Fitbit API!" self.success_html = """ <h1>Initiating BioThentication process...</h1> <br/><h3>You can close this window</h3>""" self.failure_html = """ <h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s""" self.fitbit = Fitbit( client_id, client_secret, redirect_uri=redirect_uri, timeout=10, )
def set_fitbit_client(self, user_id): """ Set client token properties for data requests :param user_id: Fitbit user_id sent back from authorization process. :type user_id: String """ client_token = FitbitToken.query.filter_by(user_id=user_id).first() access_token = client_token.access_token refresh_token = client_token.refresh_token expires_at = client_token.expires_at self._fitbit = Fitbit(self._client_id, self._client_secret, access_token=access_token, refresh_token=refresh_token, expires_at=expires_at, refresh_cb=self._update_token)
def verify_keys(keys): global global_client_id global global_client_secret # First, make sure we have all properties user_id = keys.get('user_id', None) refresh_token = keys.get('refresh_token', None) access_token = keys.get('access_token', None) expires_at = keys.get('expires_at', None) client_id = keys.get('client_id', None) client_secret = keys.get('client_secret', None) if not (user_id and refresh_token and access_token and expires_at and client_id and client_secret): print( "user_id, refresh_token, access_token, expires_at, client_id, and client_secret are not all present; re-authenticating" ) return False # No good way around this.... global_client_id = client_id global_client_secret = client_secret # This needs a nudge; we don't care about microseconds expires_at = expires_at.split(".")[0] # If we have everything, try using our token # TODO: refresh_cb, and re-use Fitbit object fitbit = Fitbit(client_id, client_secret, timeout=10, access_token=access_token, refresh_token=refresh_token, expires_at=expires_at, refresh_cb=my_refresh_cb) # We always read back 30 days, just to get a window. ed = datetime.datetime.now() st = ed - datetime.timedelta(days=10) # Build up results res = get_all_data(fitbit, st, ed) return res
def __init__(self, client_id, client_secret, redirect_uri='http://127.0.0.1:8080/'): """ http://localhost:3000/auth/fitbit/callback/ """ """ redirect_uri='http://127.0.0.1:8080/'):""" """ Initialize the FitbitOauth2Client """ self.success_html = """ <h1>You are now authorized to access the Fitbit API!</h1> <br/><h3>You can close this window</h3>""" self.failure_html = """ <h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s""" self.fitbit = Fitbit( client_id, client_secret, redirect_uri=redirect_uri, timeout=10, )
def __init__(self, client_id, client_secret, redirect_uri='http://127.0.0.1:8080/'): """ Initialize the FitbitOauth2Client """ self.success_html = """ <script>window.close();</script> """ self.failure_html = """ <script>window.close();</script> """ self.fitbit = Fitbit( client_id, client_secret, redirect_uri=redirect_uri, timeout=10, ) self.redirect_uri = redirect_uri
def main_page(request): access_token = request.COOKIES.get('token') template = loader.get_template('fitbitdata/main_page.html') if not access_token: fitbit = Fitbit(CLIENT_ID, CLIENT_SECRET, redirect_uri, timeout=10) code = request.GET.get('code') tokens = fitbit.client.fetch_access_token(code) access_token = tokens["access_token"] refresh_token = tokens["refresh_token"] expires_at = int(tokens["expires_at"]) lifetime_activity = get_lifetime_activity(access_token) new_user = create_or_update_user(fitbit, access_token) user_posts = Post.objects.filter(user_id=new_user[0]) context = { 'lifetime_distance': lifetime_activity["lifetime"]["total"]["distance"], 'lifetime_floors': lifetime_activity["lifetime"]["total"]["floors"], 'user_posts': user_posts } response = HttpResponse(template.render(context, request)) response.set_cookie(key='token', value=access_token) response.set_cookie(key='refresh', value=refresh_token) response.set_cookie(key='expires_at', value=expires_at) return response else: fitbit = create_fitbit_with_cookies( request) # fitbit.client.access_token = access_token lifetime_distance = get_lifetime_from_cookies(request)[0] lifetime_floors = get_lifetime_from_cookies(request)[1] new_user = create_or_update_user(fitbit, access_token) user_posts = Post.objects.filter(user_id=new_user[0]) context = { 'lifetime_distance': lifetime_distance, 'lifetime_floors': lifetime_floors, 'user_posts': user_posts } response = HttpResponse(template.render(context, request)) return response
def __init__(self, client_id, client_secret, redirect_uri): """ Initialize the FitbitOauth2Client """ self.success_html = """<meta http-equiv="refresh" content="2;URL=\'{}\'"/> <h3>You will be redirected momentarily</h3>""".format(redirect_uri) self.failure_html = """ <h1>ERROR: %s</h1>%s""" self.fitbit = Fitbit( client_id, client_secret, redirect_uri=redirect_uri, timeout=10, ) self.redirect_uri = redirect_uri self.url, _ = self.fitbit.client.authorize_token_url() # Same with redirect_uri hostname and port cherrypy.config.update({'server.socket_host': '0.0.0.0', 'server.socket_port': 8080, 'log.screen': False, 'checker.on': False}) cherrypy.quickstart(self)
def __init__(self, client_id, client_secret, redirect_uri='http://127.0.0.1:%d/' % port): """ Initialize the FitbitOauth2Client """ cherrypy.engine.stop() cherrypy.server.httpserver = None cherrypy.config.update({'server.socket_port': port}) cherrypy.engine.start() self.success_html = """ <h1>You are now authorized to access the Fitbit API!</h1> <br/><h3>You can close this window</h3>""" self.failure_html = """ <h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s""" self.fitbit = Fitbit( client_id, client_secret, redirect_uri=redirect_uri, timeout=10, )
from fitbit.api import Fitbit import json if __name__ == '__main__': with open('config.json', 'rt') as f: config = json.load(f) fitbit = Fitbit(client_id=config['client_id'], client_secret=config['client_secret'], redirect_uri=config['redirect_uri'], timeout=10) url, _ = fitbit.client.authorize_token_url() url = url.replace('response_type=code', 'response_type=token') print('Please visit: {}'.format(url))