Skip to content

Commit

Permalink
100% code coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
pylover committed Jan 19, 2020
1 parent 1c364fa commit a914ae7
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
24 changes: 23 additions & 1 deletion tests/test_extension.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest
from bddrest import status, response, given
from yhttp import text
from yhttp import text, json

from yhttp.extensions.auth import install, JWT

Expand All @@ -25,6 +25,12 @@ def get(req):

return req.identity.name

@app.route('/admin')
@auth(roles='admin, god')
@json
def get(req):
return req.identity.roles

with story(app, headers={'Authorization': token.dump(dict(name='foo'))}):
assert status == 200
assert response.text == 'foo'
Expand All @@ -35,6 +41,22 @@ def get(req):
when(headers={'Authorization': 'mAlfoRMeD'})
assert status == 401

with story(app, '/admin', headers={
'Authorization': token.dump(dict(name='foo', roles=['admin']))
}):
assert status == 200
assert response.json == ['admin']

when(headers={
'Authorization': token.dump(dict(name='foo', roles=['editor']))
})
assert status == 403

when(headers={
'Authorization': token.dump()
})
assert status == 403


def test_exceptions(app):
db = install(app)
Expand Down
7 changes: 6 additions & 1 deletion yhttp/extensions/auth/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@


def authenticate(app, roles=None):
if isinstance(roles, str):
roles = [i.strip() for i in roles.split(',')]

def decorator(handler):
@functools.wraps(handler)
def wrapper(req, *args, **kw):
req.identity = app.jwt.verifyrequest(req)
if roles is not None:
req.identity.authorize(roles)

return handler(req, *args, **kw)

return wrapper
return decorator

Expand Down
10 changes: 10 additions & 0 deletions yhttp/extensions/auth/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ def __getattr__(self, attr):
except KeyError:
raise AttributeError()

def authorize(self, roles):
if 'roles' not in self.payload:
raise statuses.forbidden()

for r in roles:
if r in self.roles:
return r

raise statuses.forbidden()


class JWT:
def __init__(self, secret, algorithm='HS256'):
Expand Down

0 comments on commit a914ae7

Please sign in to comment.