Add declarative JSON requests.
This commit is contained in:
parent
14cc8ec7c4
commit
65b0a25429
29
pos/rest.py
29
pos/rest.py
|
@ -3,6 +3,24 @@ from aiohttp.web import json_response
|
|||
from pos.database import User, ProductCategory, AccessToken
|
||||
|
||||
|
||||
def needs(*needed):
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
async def wrapper(request):
|
||||
request_json = await request.json()
|
||||
if not all(k in request_json.keys() for k in needed) or
|
||||
return json_response({
|
||||
'err': 'malformed_request',
|
||||
'msg': 'Missing one or more keys: {}.'.format(
|
||||
", ".join(needed))
|
||||
}, status=400)
|
||||
else:
|
||||
return func(request)
|
||||
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
def auth_required(func):
|
||||
@wraps(func)
|
||||
async def wrapper(request):
|
||||
|
@ -35,21 +53,20 @@ def auth_required(func):
|
|||
return wrapper
|
||||
|
||||
|
||||
@needs('username', 'password')
|
||||
async def token_create(request):
|
||||
db = request.app['db']
|
||||
request_json = await request.json()
|
||||
|
||||
if not all(k in request_json.keys() for k in ['username', 'password']):
|
||||
return json_response({'err': 'malformed_request',
|
||||
'msg': 'Missing username and/or password keys.'},
|
||||
status=400)
|
||||
username = request_json['username']
|
||||
password = request_json['password']
|
||||
|
||||
with db.get_session() as session:
|
||||
user = session.query(User) \
|
||||
.filter_by(username=request_json['username']) \
|
||||
.filter_by(username=username) \
|
||||
.one_or_none()
|
||||
|
||||
if not user or user.password != request_json['password']:
|
||||
if not user or user.password != password:
|
||||
return json_response({'err': 'invalid_credentials'},
|
||||
status=400)
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user