university-final-iot-backend/app/api/resources/account.py

42 lines
1.3 KiB
Python
Raw Normal View History

from flask_restful import Resource, abort
2018-05-08 08:52:36 +00:00
from flask import g
2018-05-08 14:45:09 +00:00
from marshmallow import Schema, fields
from webargs.flaskparser import use_args
2018-05-07 14:13:07 +00:00
from flasgger import swag_from
2018-05-06 19:42:21 +00:00
import app.accounts as accounts
2018-05-08 14:45:09 +00:00
from app.api import ProtectedResource
2018-05-06 19:42:21 +00:00
2018-05-08 14:45:09 +00:00
class UserSchema(Schema):
username = fields.Str(required=True)
email = fields.Email(required=True)
password = fields.Str(required=True, load_only=True)
class UserWrapperSchema(Schema):
user = fields.Nested(UserSchema, required=True, location='json')
2018-05-06 19:42:21 +00:00
2018-05-08 08:52:36 +00:00
2018-05-08 14:45:09 +00:00
class AccountResource(ProtectedResource):
2018-05-08 08:52:36 +00:00
@swag_from('swagger/get_account_spec.yaml')
def get(self, account_id):
if g.current_account.id == account_id:
2018-05-08 14:45:09 +00:00
return UserWrapperSchema().dump({'user': g.current_account}), 200
2018-05-08 08:52:36 +00:00
abort(403, message='You can only get your own account', status='error')
class AccountListResource(Resource):
2018-05-08 14:45:09 +00:00
@use_args(UserWrapperSchema())
2018-05-07 14:13:07 +00:00
@swag_from('swagger/create_account_spec.yaml')
def post(self, args):
2018-05-06 19:42:21 +00:00
try:
args = args['user']
2018-05-06 19:42:21 +00:00
success = accounts.create_account(
args['username'],
args['email'],
args['password'])
if success:
return '', 201
except ValueError:
abort(422, message='Account already exists', status='error')