Example #1
0
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'))
Example #2
0
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("")
Example #4
0
    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)
Example #5
0
    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)
Example #6
0
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)
Example #7
0
    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,
        )
Example #8
0
    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)
Example #9
0
class FitbitGetter:
    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)

    @staticmethod
    def format_time(str_time, day):

        arg = dict(
            zip(['hour', 'minute', 'second'],
                np.asarray(str_time.split(':')).astype('int')))
        return datetime.datetime(year=day.year,
                                 month=day.month,
                                 day=day.day,
                                 **arg)

    def heartrate(self, date, days=2, detail_level='1sec'):

        t, v = [], []

        for shift in np.arange(days + 1)[::-1]:
            dte = date - datetime.timedelta(days=int(shift))
            arg = {
                'base_date': dte.strftime("%Y-%m-%d"),
                'detail_level': detail_level
            }
            req = self.client.intraday_time_series('activities/heart', **arg)
            req = req['activities-heart-intraday']['dataset']
            t += [self.format_time(r['time'], dte) for r in req]
            v += [r['value'] for r in req]

        return np.asarray(t), np.asarray(v)
    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 __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,
        )
Example #12
0
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
Example #13
0
    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
Example #15
0
    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)
Example #16
0
    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,
        )
Example #17
0
class OAuth2Server:
    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 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 fetch_access_token(self, code):
        """
        Once the user has agreed to provide Fitbit data to the application, this method will use the
        authorization code passed back from that process to retrieve the user's access token information

        :param code: Authorization code sent to the application after the user has authorize the use of Fitbit data.
        :type code: String
        :return: An access token for the user.
        :rtype: OAuth2Token
        """
        token = self._fitbit.client.fetch_access_token(code)
        self._update_token(token)

        return token

    def subscribe(self, user_id):
        """
        Allows the app to begin receiving push updates when a user syncs their Fitbit device

        :param user_id: The Fitbit user's identifier
        :type user_id: String
        """
        self._fitbit.subscription(user_id,
                                  '2')  # TODO: make subscriptionId a config

    def get_authorize_url(self):
        """
        Gets a url to which authorizations request can be sent

        :return: Fitbit authorization url
        :rtype: String
        """
        url, _ = self._fitbit.client.authorize_token_url()
        return url

    def get_activities(self, user_id, date):
        url = "{0}/{1}/user/{2}/activities/date/{date}.json".format(
            *self._fitbit._get_common_args(user_id),
            date=self._fitbit._get_date_string(date))
        return self._fitbit.make_request(url)

    def get_sleep(self, user_id, date):
        url = "{0}/1.2/user/{1}/sleep/date/{date}.json".format(
            self._fitbit.API_ENDPOINT,
            user_id,
            date=self._fitbit._get_date_string(date))
        return self._fitbit.make_request(url)

    def get_bmi(self, user_id, date):
        return self._fitbit.time_series('body/bmi',
                                        user_id=user_id,
                                        end_date=date)

    def get_body_fat_percent(self, user_id, date):
        return self._fitbit.time_series('body/fat',
                                        user_id=user_id,
                                        end_date=date)

    def get_weight(self, user_id, date):
        return self._fitbit.time_series('body/weight',
                                        user_id=user_id,
                                        end_date=date)

    @staticmethod
    def _update_token(token):
        user_token = FitbitToken.query.filter_by(
            user_id=token['user_id']).first()
        if user_token is None:
            user_token = FitbitToken()
            db.session.add(user_token)

        for key in token.keys():
            setattr(user_token, key, token[key])

        db.session.commit()
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))