示例#1
0
def nokia_auth():
    print('First we need your Client ID, Consumer Secret, and Callback URI')
    print(
        'You can find it here: https://account.withings.com/partner/dashboard_oauth2'
    )
    client_id = input('client_id: ')
    consumer_secret = input('consumer_secret: ')
    callback_uri = input('callback_uri: ')

    auth = NokiaAuth(client_id, consumer_secret, callback_uri=callback_uri)
    authorize_url = auth.get_authorize_url()
    print(
        'Now you should open this authorization URL and give the app access: ')
    print(authorize_url)
    auth_url = input('Enter the response URL: ')

    # We have to parse the URL to extract the code from the query string
    u = urlparse(auth_url)
    auth_code = parse_qs(u.query)['code'][0]
    creds = auth.get_credentials(auth_code)

    # Save this so we don't have to do this again
    save_creds(creds)

    # Pass back
    return creds
示例#2
0
 def test_get_credentials(self):
     """ Make sure the get_credentials function works as expected """
     auth = NokiaAuth(self.consumer_key, self.consumer_secret)
     # Returns an authorized NokiaCredentials object
     creds = auth.get_credentials('FAKE_OAUTH_VERIFIER')
     assert isinstance(creds, NokiaCredentials)
     # Check that the attributes of the NokiaCredentials object are
     # correct.
     self.assertEqual(creds.access_token, 'fake_oauth_token')
     self.assertEqual(creds.access_token_secret, 'fake_oauth_token_secret')
     self.assertEqual(creds.consumer_key, self.consumer_key)
     self.assertEqual(creds.consumer_secret, self.consumer_secret)
     self.assertEqual(creds.user_id, 'FAKEID')
 def test_get_credentials(self):
     """ Make sure the get_credentials function works as expected """
     auth = NokiaAuth(*self.auth_args, callback_uri=self.callback_uri)
     # Returns an authorized NokiaCredentials object
     creds = auth.get_credentials('FAKE_CODE')
     assert isinstance(creds, NokiaCredentials)
     # Check that the attributes of the NokiaCredentials object are
     # correct.
     self.assertEqual(creds.access_token, 'fake_access_token')
     self.assertEqual(creds.token_expiry, str(int((
         datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)
     ).total_seconds())))
     self.assertEqual(creds.token_type, 'Bearer')
     self.assertEqual(creds.refresh_token, 'fake_refresh_token')
     self.assertEqual(creds.client_id, self.client_id)
     self.assertEqual(creds.consumer_secret, self.consumer_secret)
     self.assertEqual(creds.user_id, 'fake_user_id')
示例#4
0
 def test_get_credentials(self):
     """ Make sure the get_credentials function works as expected """
     auth = NokiaAuth(*self.auth_args, callback_uri=self.callback_uri)
     # Returns an authorized NokiaCredentials object
     creds = auth.get_credentials('FAKE_CODE')
     assert isinstance(creds, NokiaCredentials)
     # Check that the attributes of the NokiaCredentials object are
     # correct.
     self.assertEqual(creds.access_token, 'fake_access_token')
     self.assertEqual(
         creds.token_expiry,
         str(
             int((datetime.datetime.utcnow() -
                  datetime.datetime(1970, 1, 1)).total_seconds())))
     self.assertEqual(creds.token_type, 'Bearer')
     self.assertEqual(creds.refresh_token, 'fake_refresh_token')
     self.assertEqual(creds.client_id, self.client_id)
     self.assertEqual(creds.consumer_secret, self.consumer_secret)
     self.assertEqual(creds.user_id, 'fake_user_id')
示例#5
0
 def __init__(self):
     try:
         with open('personal_dashboard/nokia_data.pkl',
                   'rb') as pickle_file:
             nokia = pickle.load(pickle_file)
             self.measures = nokia.get_measures()
             measures = nokia.get_measures(limit=1)
             self.weight = round(float(measures[0].weight) * 2.20462, 2)
             pickle_file.close()
     except:
         auth = NokiaAuth(WITHINGS_KEYS['API_KEY'],
                          WITHINGS_KEYS['API_SECRET'])
         authorize_url = auth.get_authorize_url()
         print("Go to %s allow the app and copy your oauth_verifier" %
               authorize_url)
         oauth_verifier = input('Please enter your oauth_verifier: ')
         creds = auth.get_credentials(oauth_verifier)
         client = NokiaApi(creds)
         with open('personal_dashboard/nokia_data.pkl', 'wb') as output:
             pickle.dump(client, output, pickle.HIGHEST_PROTOCOL)
         self.measures = client.get_measures()
         measures = client.get_measures(limit=1)
         #Convert Kg to Lbs
         self.weight = round(float(measures[0].weight) * 2.20462, 2)
示例#6
0
class WebInterface(SmartPluginWebIf):
    def __init__(self, webif_dir, plugin):
        """
        Initialization of instance of class WebInterface

        :param webif_dir: directory where the webinterface of the plugin resides
        :param plugin: instance of the plugin
        :type webif_dir: str
        :type plugin: object
        """
        self.logger = logging.getLogger(__name__)
        self.webif_dir = webif_dir
        self.plugin = plugin
        self._creds = None
        self._auth = None

        self.tplenv = self.init_template_environment()

    def _get_callback_url(self):
        ip = self.plugin.mod_http.get_local_ip_address()
        port = self.plugin.mod_http.get_local_port()
        web_ifs = self.plugin.mod_http.get_webifs_for_plugin(
            self.plugin.get_shortname())
        for web_if in web_ifs:
            if web_if['Instance'] == self.plugin.get_instance_name():
                callback_url = "http://{}:{}{}".format(ip, port,
                                                       web_if['Mount'])
                self.logger.debug(
                    "Plugin '{}': WebIf found, callback is {}".format(
                        self.plugin.get_fullname(), callback_url))
            return callback_url
        self.logger.error(
            "Plugin '{}': Callback URL cannot be established.".format(
                self.plugin.get_fullname()))

    @cherrypy.expose
    def index(self, reload=None, state=None, code=None, error=None):
        """
        Build index.html for cherrypy

        Render the template and return the html file to be delivered to the browser

        :return: contents of the template after beeing rendered
        """
        if self._auth is None:
            self._auth = NokiaAuth(
                self.plugin._client_id,
                self.plugin._consumer_secret,
                callback_uri=self._get_callback_url(),
                scope='user.info,user.metrics,user.activity')

        if not reload and code:
            self.logger.debug("Plugin '{}': Got code as callback: {}".format(
                self.plugin.get_fullname(), code))
            credentials = None
            try:
                credentials = self._auth.get_credentials(code)
            except Exception as e:
                self.logger.error(
                    "Plugin '{}': An error occurred, perhaps code parameter is invalid or too old? Message: {}"
                    .format(self.plugin.get_fullname(), str(e)))
            if credentials is not None:
                self._creds = credentials
                self.logger.debug(
                    "Plugin '{}': New credentials are: access_token {}, token_expiry {}, token_type {}, refresh_token {}"
                    .format(self.plugin.get_fullname(),
                            self._creds.access_token, self._creds.token_expiry,
                            self._creds.token_type, self._creds.refresh_token))
                self.plugin.get_item('access_token')(self._creds.access_token)
                self.plugin.get_item('token_expiry')(self._creds.token_expiry)
                self.plugin.get_item('token_type')(self._creds.token_type)
                self.plugin.get_item('refresh_token')(
                    self._creds.refresh_token)

                self.plugin._client = None

        tmpl = self.tplenv.get_template('index.html')
        return tmpl.render(plugin_shortname=self.plugin.get_shortname(),
                           plugin_version=self.plugin.get_version(),
                           interface=None,
                           item_count=len(self.plugin.get_items()),
                           plugin_info=self.plugin.get_info(),
                           tabcount=2,
                           callback_url=self._get_callback_url(),
                           tab1title="Withings Health Items (%s)" %
                           len(self.plugin.get_items()),
                           tab2title="OAuth2 Data",
                           authorize_url=self._auth.get_authorize_url(),
                           p=self.plugin,
                           token_expiry=datetime.datetime.fromtimestamp(
                               self.plugin.get_item('token_expiry')(),
                               tz=self.plugin.shtime.tzinfo()),
                           now=self.plugin.shtime.now(),
                           code=code,
                           state=state,
                           reload=reload,
                           language=self.plugin.get_sh().get_defaultlanguage())