api_v1.4/hub_api/user.py

77 lines
3.1 KiB
Python

"""
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, request
from flask_restful import Resource
from imports.user_factory import UserFactory
from exports.user_factory import UserFactory as ExUserFactory
import os
from hub_logger import logger
from hub_api.helpers.auth import generate_auth_token, role_required
from persistence.models import UserRoles
class User(Resource):
def __init__(self):
self.user_factory = UserFactory(db_name='hub_prod', app_env='PROD',
dotenv_path="{}/.env".format(os.path.expanduser('~')))
@role_required([UserRoles.Admin.value])
def post(self):
try:
payload = request.get_json()
user = self.user_factory.create_user(name=payload["name"], email=payload["email"], password=payload["password"],
role=payload["role"])
if type(user) is dict:
return Response(response=json.dumps(user), status=400)
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)
@role_required([UserRoles.Admin.value])
def put(self):
try:
payload = request.get_json()
res = self.user_factory.update_user(user_id=payload['id'], name=payload['name'], password=payload['password'],
role=payload['role'], email=payload['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)
class UserLogin(Resource):
def __init__(self):
self.user_factory = ExUserFactory(db_name='hub_prod', app_env='PROD',
dotenv_path="{}/.env".format(os.path.expanduser('~')))
def post(self):
try:
payload = request.get_json()
user = self.user_factory.login_user(email=payload["email"], password=payload["password"])
if type(user) is dict:
return Response(response=json.dumps(user), status=400)
user = user[0]
user_dict = {
'user': {
'id': user.id,
'name': user.name,
'email': user.email,
'password': user.password,
'role': user.role.value,
}
}
user_dict['token'] = generate_auth_token(user_dict)
return Response(response=json.dumps(user_dict), status=200)
except Exception as err:
logger.error(err)
return Response(response=json.dumps({'err_msg': 'An error occurred while authenticating user'}), status=400)