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
|
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):
|
def auth_required(func):
|
||||||
@wraps(func)
|
@wraps(func)
|
||||||
async def wrapper(request):
|
async def wrapper(request):
|
||||||
|
@ -35,21 +53,20 @@ def auth_required(func):
|
||||||
return wrapper
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
@needs('username', 'password')
|
||||||
async def token_create(request):
|
async def token_create(request):
|
||||||
db = request.app['db']
|
db = request.app['db']
|
||||||
request_json = await request.json()
|
request_json = await request.json()
|
||||||
|
|
||||||
if not all(k in request_json.keys() for k in ['username', 'password']):
|
username = request_json['username']
|
||||||
return json_response({'err': 'malformed_request',
|
password = request_json['password']
|
||||||
'msg': 'Missing username and/or password keys.'},
|
|
||||||
status=400)
|
|
||||||
|
|
||||||
with db.get_session() as session:
|
with db.get_session() as session:
|
||||||
user = session.query(User) \
|
user = session.query(User) \
|
||||||
.filter_by(username=request_json['username']) \
|
.filter_by(username=username) \
|
||||||
.one_or_none()
|
.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'},
|
return json_response({'err': 'invalid_credentials'},
|
||||||
status=400)
|
status=400)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user