api_v1.4/hub_api/user.py

76 lines
2.8 KiB
Python
Raw Normal View History

"""
HeatPump Service
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2022 Project Author Peter Yefi peteryefi@gmail.com
"""
import json
from flask import Response
from flask_apispec import use_kwargs, doc
from flask_apispec.views import MethodResource
from flask_restful import Resource
from marshmallow import Schema, fields
from imports.user_factory import UserFactory
import os
from hub_logger import logger
class UserPostData(Schema):
"""
Defines post data for users
"""
name = fields.String(required=True, description='Name of user')
email = fields.String(required=True, description='Email of user')
password = fields.String(required=True, description='Password of user')
role = fields.String(required=True, description='Allowed user roles', enum=['Admin', 'Hub_Reader'])
class UserPutData(UserPostData):
"""
Defines put data for users
"""
id = fields.Int(required=True, description='The Id of the user to be Updated')
class UserLoginData(Schema):
"""
Defines post data for users
"""
email = fields.String(required=True, description='Email of user')
password = fields.String(required=True, description='Password of user')
class User(MethodResource, Resource):
def __init__(self):
self.user_factory = UserFactory(db_name='hub_prod', app_env='PROD',
dotenv_path="{}/.env".format(os.path.expanduser('~')))
@doc(description='Create users', tags=['CreateUser'])
@use_kwargs(UserPostData)
def post(self, **kwargs):
try:
user = self.user_factory.create_user(name=kwargs["name"], email=kwargs["email"], password=kwargs["password"],
role=kwargs["role"])
if type(user) is dict:
return Response(response=json.dumps(user), status=200)
return Response(response=json.dumps({'user': {'id': user.id, 'name': user.name, 'email': user.email,
'password': user.password, 'role': user.role.value}}), status=201)
except Exception as err:
logger.error(err)
return Response(response=json.dumps({'err_msg': 'Sorry an error occurred while creating user'}), status=400)
@doc(description='Get all users', tags=['UpdateUsers'])
@use_kwargs(UserPutData)
def put(self, **kwargs):
try:
res = self.user_factory.update_user(user_id=kwargs['id'], name=kwargs['name'], password=kwargs['password'],
role=kwargs['role'], email=kwargs['email'])
if res:
return Response(response=json.dumps(res), status=400)
return Response(response=json.dumps({'success': 'user updated successfully'}), status=200)
except Exception as err:
logger.error(err)
return Response(response=json.dumps({'err_msg': 'Sorry, an error occurred while updating user'}),
status=400)