Skip to content

Feat/graph session scopes #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Apr 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,14 @@ device_credential = DeviceCodeCredential(

```

Create AuthorizationProvider, AuthorizationHandler and list of middleware
Create an authorization provider object and a list of scopes
```python
auth_provider = TokenCredentialAuthProvider(device_credential)
options = AuthMiddlewareOptions(['mail.send', 'user.read'])
auth_handler = AuthorizationHandler(auth_provider, auth_provider_options=options)

middleware = [
auth_handler
]
scopes = ['mail.send', 'user.read']
auth_provider = TokenCredentialAuthProvider(scopes, device_credential)
```

```python
graph_session = GraphSession(middleware=middleware)
graph_session = GraphSession(auth_provider)
result = graph_session.get('/me')
print(result.json())
```
Expand Down
4 changes: 1 addition & 3 deletions msgraphcore/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
"""msgraph-core"""

from msgraphcore.graph_session import GraphSession
from .middleware.authorization_handler import AuthorizationHandler
from .middleware.authorization_provider import AuthProviderBase, TokenCredentialAuthProvider
from .middleware.options.auth_middleware_options import AuthMiddlewareOptions
from .middleware.authorization import AuthProviderBase, TokenCredentialAuthProvider
from .constants import SDK_VERSION

__version__ = SDK_VERSION
18 changes: 9 additions & 9 deletions msgraphcore/graph_session.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
"""
Creates a session object
Graph Session
"""
from requests import Session, Request, Response

from msgraphcore.constants import BASE_URL, SDK_VERSION
from msgraphcore.middleware._middleware import MiddlewarePipeline, BaseMiddleware
from msgraphcore.middleware._base_auth import AuthProviderBase
from msgraphcore.middleware.authorization import AuthorizationHandler


class GraphSession(Session):
"""
Extends session object with graph functionality
"""
def __init__(self, **kwargs):
def __init__(self, auth_provider: AuthProviderBase, middleware: list = []):
super().__init__()
self.headers.update({'sdkVersion': 'graph-python-' + SDK_VERSION})
self._base_url = BASE_URL
middleware = kwargs.get('middleware')

auth_handler = AuthorizationHandler(auth_provider)

middleware.insert(0, auth_handler)
self._register(middleware)

def get(self, url: str, **kwargs) -> Response:
Expand Down Expand Up @@ -55,12 +60,7 @@ def _prepare_and_send_request(self, method: str = '', url: str = '', **kwargs) -
prepared_request = self.prepare_request(request)

if list_of_scopes is not None:
# prepare scopes middleware option
graph_scopes = BASE_URL + '?scopes='
for scope in list_of_scopes:
graph_scopes += scope + '%20'

# Append middleware options to the request object, will be used by MiddlewareController
prepared_request.scopes = graph_scopes
prepared_request.scopes = list_of_scopes

return self.send(prepared_request, **kwargs)
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from ._base_auth import AuthProviderBase
from ._base_auth import AuthProviderBase, TokenCredential
from ..constants import AUTH_MIDDLEWARE_OPTIONS
from ._middleware import BaseMiddleware


class AuthorizationHandler(BaseMiddleware):
def __init__(self, auth_provider: AuthProviderBase, auth_provider_options=None):
def __init__(self, auth_provider: AuthProviderBase):
super().__init__()
self.auth_provider = auth_provider
self.auth_provider_options = auth_provider_options
self.retry_count = 0

def send(self, request, **kwargs):
Expand All @@ -27,3 +26,12 @@ def send(self, request, **kwargs):

def _get_middleware_options(self, request):
return request.middleware_control.get(AUTH_MIDDLEWARE_OPTIONS)


class TokenCredentialAuthProvider(AuthProviderBase):
def __init__(self, credential: TokenCredential, scopes: [str] = ['.default']):
self.credential = credential
self.scopes = scopes

def get_access_token(self):
return self.credential.get_token(*self.scopes)[0]
10 changes: 0 additions & 10 deletions msgraphcore/middleware/authorization_provider.py

This file was deleted.

19 changes: 1 addition & 18 deletions msgraphcore/middleware/options/auth_middleware_options.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,5 @@
from msgraphcore.constants import BASE_URL


class AuthMiddlewareOptions:
def __init__(self, scopes=[]):
def __init__(self, scopes: str):
self.scopes = scopes

@property
def scopes(self):
return self._scopes

@scopes.setter
def scopes(self, list_of_scopes):
if type(list_of_scopes) == list:
graph_scopes = BASE_URL + '?scopes='

for scope in list_of_scopes:
graph_scopes += scope + '%20'

self._scopes = graph_scopes
elif type(list_of_scopes) == str:
self._scopes = list_of_scopes
20 changes: 6 additions & 14 deletions tests/integration/test_middleware_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
from unittest import TestCase

from msgraphcore.graph_session import GraphSession

from msgraphcore.middleware.authorization_provider import AuthProviderBase
from msgraphcore.middleware.authorization_handler import AuthorizationHandler
from msgraphcore.middleware.options.auth_middleware_options import AuthMiddlewareOptions
from msgraphcore.middleware.authorization import AuthProviderBase


class MiddlewarePipelineTest(TestCase):
Expand All @@ -14,22 +11,17 @@ def setUp(self):

def test_middleware_pipeline(self):
url = 'https://proxy.apisandbox.msdn.microsoft.com/svc?url=https://graph.microsoft.com/v1.0/me'

auth_provider = _CustomAuthProvider()
options = AuthMiddlewareOptions(['user.read'])
auth_handler = AuthorizationHandler(auth_provider, auth_provider_options=options)

middleware = [
auth_handler
]

graph_session = GraphSession(middleware=middleware)
scopes = ['user.read']
auth_provider = _CustomAuthProvider(scopes)
graph_session = GraphSession(auth_provider)
result = graph_session.get(url)

self.assertEqual(result.status_code, 200)


class _CustomAuthProvider(AuthProviderBase):
def __init__(self, scopes):
pass

def get_access_token(self):
return '{token:https://graph.microsoft.com/}'
Expand Down
17 changes: 11 additions & 6 deletions tests/unit/test_graph_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@

from msgraphcore.graph_session import GraphSession
from msgraphcore.constants import BASE_URL, SDK_VERSION
from msgraphcore.middleware._base_auth import AuthProviderBase


class GraphSessionTest(TestCase):
def setUp(self) -> None:
self.requests = GraphSession()
self.auth_provider = _CustomAuthProvider(['user.read'])
self.requests = GraphSession(self.auth_provider)

def tearDown(self) -> None:
self.requests = None
Expand All @@ -25,11 +27,7 @@ def test_has_sdk_version_header(self):
self.assertEqual(self.requests.headers.get('sdkVersion'), 'graph-python-'+SDK_VERSION)

def test_initialized_with_middlewares(self):
middlewares = [
HTTPAdapter() # Middlewares inherit from the HTTPAdapter class
]

graph_session = GraphSession(middlewares=middlewares)
graph_session = GraphSession(self.auth_provider)
mocked_middleware = graph_session.get_adapter('https://')

self.assertIsInstance(mocked_middleware, HTTPAdapter)
Expand All @@ -54,3 +52,10 @@ def test_does_not_build_graph_urls_for_full_urls(self):

self.assertEqual(other_url, request_url)


class _CustomAuthProvider(AuthProviderBase):
def __init__(self, scopes):
pass

def get_access_token(self):
return '{token:https://graph.microsoft.com/}'
2 changes: 1 addition & 1 deletion tests/unit/test_middleware_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
class TestMiddlewareOptions(TestCase):
def test_multiple_scopes(self):
graph_scopes = 'https://graph.microsoft.com/v1.0?scopes=mail.read%20user.read%20'
auth_options = AuthMiddlewareOptions(scopes=['mail.read', 'user.read'])
auth_options = AuthMiddlewareOptions(graph_scopes)
self.assertEqual(auth_options.scopes, graph_scopes)