Esempio n. 1
0
    def test_token_bool(self, mock_api):
        token = Token(mock_api, **self.data)

        assert token

        token.access_token = None
        assert not token
Esempio n. 2
0
    def test_token_destroy(self, mock_api):
        token = Token(mock_api, **self.data)
        token.destroy()

        assert token.refresh_token is None
        assert token.token_type is None
        assert token.expires_in == -1

        with pytest.raises(AthomAPISessionError):
            assert token.access_token is None
Esempio n. 3
0
    def test_api_check_authorization_code(self):
        api = AthomCloudAPI(*self.config)
        token = Token(api, **self.oauth)
        api.setToken(token)

        assert api.hasAuthorizationCode()

        token = Token(api)
        api.setToken(token)
        assert not api.hasAuthorizationCode()
Esempio n. 4
0
    def test_generate_token(self, mock_api):
        token = Token.generate_token(mock_api, json.dumps(self.data))

        for key, value in self.data.items():
            assert getattr(token, key) == value

        assert str(token) == self.data['access_token']
Esempio n. 5
0
    def test_token_init(self, mock_api):
        token = Token(mock_api, **self.data)

        for key, value in self.data.items():
            assert getattr(token, key) == value

        assert str(token) == self.data['access_token']
Esempio n. 6
0
    def __init__(self, clientId, clientSecret, redirectUrl, **kwargs):
        self.clientId = clientId
        self.clientSecret = clientSecret
        self.redirectUrl = redirectUrl

        self.storage = kwargs.get('storage', LocalStorage())
        self.autoRefreshTokens = kwargs.get('autoRefreshTokens', True)

        if 'token' in self.storage:
            token_dict = self.storage.get('token')
            self.token = Token(self, **token_dict)
        else:
            self.token = kwargs.get('token', Token(self))

        # Set request.Session for API interaction
        self.s = AthomSession(base='https://api.athom.com', token=self.token)
Esempio n. 7
0
    def test_token_auto_refresh_fail(self, mock_api):
        url = 'https://api.athom.com/oauth2/token'
        oauth_json = {
            "code": "401",
            "error": "invalid_refresh_code",
            "error_description": "Invalid refresh code"
        }

        token = Token(mock_api, **self.data)
        responses.add(responses.POST, url, body=json.dumps(oauth_json), status=401)

        with pytest.raises(AthomAPISessionError):
            token.refresh()

        assert token.refresh_token is None
        assert token.token_type is None
        assert token.expires_in == -1

        with pytest.raises(AthomAPISessionError):
            assert token.access_token is None
Esempio n. 8
0
    def test_token_auto_refresh(self, mock_api):
        url = 'https://api.athom.com/oauth2/token'
        oauth_json = {
            "token_type":"bearer",
            "access_token":"2da881ff599c17128553662e2fb6e09cdbeec3bc",
            "expires_in":3660,
            "refresh_token":"5051b445460ee0680be4c5f39d67edfd2e277656"
        }

        token = Token(mock_api, **self.data)
        responses.add(responses.POST, url, body=json.dumps(oauth_json))

        token.refresh()
        for key, value in oauth_json.items():
            assert getattr(token, key) == value

        request = responses.calls[0].request

        assert request.url == url
        assert request.headers['Content-Type'] == 'application/x-www-form-urlencoded'
        assert 'grant_type=refresh_token' in request.body
        assert 'refresh_token='+self.data['refresh_token'] in request.body
Esempio n. 9
0
    def authenticateWithAuthorizationCode(self, oauth):
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}

        data = {
            'client_id': self.clientId,
            'client_secret': self.clientSecret,
            'grant_type': 'authorization_code',
            'code': oauth
        }

        r = self.s.post('/oauth2/token', data=data, headers=headers)

        self.token = Token.generate_token(self, r.json())
        self.storage.set('token', self.token.jsonify())

        return self.token
Esempio n. 10
0
    def test_api_get_user(self):
        url = 'https://api.athom.com/user/me'

        with open('tests/fixtures/user.json', 'r') as f:
            json_user = f.read()
            user_dict = json.loads(json_user)

        responses.add(responses.GET, url, body=json_user)

        api = AthomCloudAPI(*self.config)
        token = Token(api, **self.oauth)
        api.setToken(token)

        user = api.getUser()

        # Verify the GET request to Athom API
        request = responses.calls[0].request
        assert request.url == url
        assert request.headers['authorization'] == 'Bearer '+self.oauth['access_token']

        # Test user properties
        for column in ['lastname', 'firstname', 'email']:
            assert getattr(user, column) == user_dict[column]

        # Test the device properties
        for index, device in enumerate(user.devices):
            for column in ['name', 'token', 'platform']:
                assert getattr(device, column) == user_dict['devices'][index][column]

        # Test the avatar URL's
        avatar = user_dict['avatar']
        for column in avatar.keys():
            assert getattr(user.avatar, column) == avatar[column]

        # Test Homey object
        homey = user_dict['homeys'][0]
        for column in ['name', 'ipInternal', 'softwareVersion', 'language', 'state', 'role']:
            assert getattr(user.homeys[0], column) == homey[column]
Esempio n. 11
0
 def test_token_jsonify(self, mock_api):
     token = Token(mock_api, **self.data)
     assert self.data == token.jsonify()
Esempio n. 12
0
    def test_api_authentication_fail(self):
        api = AthomCloudAPI(*self.config)
        api.setToken(Token(api))

        with pytest.raises(AthomAPISessionError):
            api.getUser()
Esempio n. 13
0
    def test_set_token(self):
        api = AthomCloudAPI(*self.config)
        token = Token(api)

        api.setToken(token)
        assert api.token == token
Esempio n. 14
0
class AthomCloudAPI:
    def __init__(self, clientId, clientSecret, redirectUrl, **kwargs):
        self.clientId = clientId
        self.clientSecret = clientSecret
        self.redirectUrl = redirectUrl

        self.storage = kwargs.get('storage', LocalStorage())
        self.autoRefreshTokens = kwargs.get('autoRefreshTokens', True)

        if 'token' in self.storage:
            token_dict = self.storage.get('token')
            self.token = Token(self, **token_dict)
        else:
            self.token = kwargs.get('token', Token(self))

        # Set request.Session for API interaction
        self.s = AthomSession(base='https://api.athom.com', token=self.token)

    def authenticateWithAuthorizationCode(self, oauth):
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}

        data = {
            'client_id': self.clientId,
            'client_secret': self.clientSecret,
            'grant_type': 'authorization_code',
            'code': oauth
        }

        r = self.s.post('/oauth2/token', data=data, headers=headers)

        self.token = Token.generate_token(self, r.json())
        self.storage.set('token', self.token.jsonify())

        return self.token

    def getLoginUrl(self, scopes=[]):
        params = {
            'client_id': self.clientId,
            'redirect_uri': self.redirectUrl,
            'response_type': 'code',
            'scopes': ','.join(scopes)
        }

        return create_url('https://api.athom.com/oauth2/authorise', params)

    def getUser(self):
        response = self.s.get('/user/me')
        schema = UserSchema()
        user = schema.loads(response.text)

        # delegationToken is required for homeys/homeyAPI
        user._setDelegationToken(self.token)
        return user

    def getAuthenticatedUser(self, **kwargs):
        if kwargs.get('additionalScopes'):
            #params = { 'additionalScopes': ','.join(kwargs.get('additionalScopes'))}
            response = self.s.get('/user/me')
        else:
            response = self.s.get('/user/me')

        log.info(response.json())
        schema = UserSchema()
        user = schema.loads(response.text)

        # delegationToken is required for homeys/homeyAPI
        user._setDelegationToken(self.token)
        return user

    def hasAuthorizationCode(self):
        return self.token is not None and self.token

    def isLoggedIn(self):
        try:
            return self.getUser() is not None
        except AthomAPISessionError:
            return False

    def refreshTokens(self, **kwargs):
        token = kwargs.get('token', self.token)
        token.refresh()
        return token

    def enableAutoRefreshTokens(self):
        self.autoRefreshTokens = True

    def disableAutoRefreshTokens(self):
        self.autoRefreshTokens = False

    def setToken(self, token):
        self.token = token

    def setConfig(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)