Commit 176c2cc3 authored by deepdey's avatar deepdey

feat(user): add get-all and get-by-id api

parent ccb18766
from enum import Enum
ALPHANUMARIC_STRING: str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' ALPHANUMARIC_STRING: str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
ENDPOINT_TAGS: list = ['P', 'V', 'SU', 'PV', 'RA'] ENDPOINT_TAGS: list = ['P', 'V', 'SU', 'PV', 'RA']
ENDPOINT_METHODS: list = ['GET', 'POST', 'PATCH','PUT', 'DELETE'] ENDPOINT_METHODS: list = ['GET', 'POST', 'PATCH','PUT', 'DELETE']
class RoleTypeEnum(Enum):
SUPER_ADMIN = 'SUPER_ADMIN'
PROJECT_ADMIN = 'PROJECT_ADMIN'
PROJECT_STAFF = 'PROJECT_STAFF'
PROJECT_USER = 'PROJECT_USER'
\ No newline at end of file
...@@ -100,3 +100,64 @@ class GetProfile(Resource): ...@@ -100,3 +100,64 @@ class GetProfile(Resource):
except Exception as e: except Exception as e:
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
return prepare_api_response(EXCEPTION_CODE, str(e)) return prepare_api_response(EXCEPTION_CODE, str(e))
@ns.route('/get', methods=['GET'])
class GetUser(Resource):
@ns.doc(security=SECURITY)
@ns.expect(*get_user_payload())
@ns.response(*get_user_response())
@sanitized()
@fetch_user()
def get(self, user_id: int):
try:
validator = GetUserValidator()
arguments: dict = validator.load(request.args)
user_info: ORM.User | None =\
get_user_by_id_for_admin(user_id, arguments['id'])
if not user_info:
return prepare_api_response(404, 'User not found')
return prepare_api_response(
SUCCESS_CODE, GET_SUCCESS_MESSAGE, data=user_info.to_dict()
)
except ValidationError as e:
return prepare_api_response(
VALIDATION_ERROR_CODE,
VALIDATION_ERROR_MESSAGE,
error=e.normalized_messages(),
)
except Exception as e:
logger.error(traceback.format_exc())
return prepare_api_response(EXCEPTION_CODE, str(e))
@ns.route('/get-all', methods=['GET'])
class GetAllUsers(Resource):
@ns.doc(security=SECURITY)
@ns.response(*get_user_list_response())
@sanitized()
@fetch_user()
def get(self, user_id: int):
try:
users_list: List[ORM.User] = get_user_list_for_project_admin(user_id)
return prepare_api_response(
SUCCESS_CODE,
GET_ALL_SUCCESS_MESSAGE,
data=[user.to_dict(rules=('-user_roles',)) for user in users_list]
)
except Exception as e:
logger.error(traceback.format_exc())
return prepare_api_response(EXCEPTION_CODE, str(e))
# TODO: implement forget password and registration api
\ No newline at end of file
from typing import List
from app import orm as ORM from app import orm as ORM
from app.app_config.constant import RoleTypeEnum
def get_user_by_username(username: str) -> ORM.User | None: def get_user_by_username(username: str) -> ORM.User | None:
...@@ -8,5 +10,87 @@ def get_user_by_username(username: str) -> ORM.User | None: ...@@ -8,5 +10,87 @@ def get_user_by_username(username: str) -> ORM.User | None:
def get_user_by_email(email: str) -> ORM.User | None: def get_user_by_email(email: str) -> ORM.User | None:
return ORM.User.query.filter_by(email=email, is_deleted=False).first() return ORM.User.query.filter_by(email=email, is_deleted=False).first()
def get_user_by_id(id: int) -> ORM.User | None: def get_user_by_id(id: int) -> ORM.User | None:
return ORM.User.query.filter_by(id=id, is_deleted=False).first() return ORM.User.query.filter_by(id=id, is_deleted=False).first()
def get_user_by_id_for_admin(admin_id: int, user_id: int) -> ORM.User | None:
admin_user: ORM.User | None = get_user_by_id(admin_id)
if not admin_user:
raise Exception('User not found for mapped apiKey')
if all(
user_role.role.role_type.role_name != RoleTypeEnum.SUPER_ADMIN.value
for user_role in admin_user.user_roles
):
if all(
user_role.role.role_type.role_name != RoleTypeEnum.PROJECT_ADMIN.value
for user_role in admin_user.user_roles
):
raise Exception('You do not have permission to view user details')
else:
# return all user data for project admin for his specific project
subquery = (
ORM.db.session.query(ORM.Role.project_id)
.join(ORM.UserRoleMap)
.filter(ORM.UserRoleMap.user_id == admin_id)
.subquery()
)
return (
ORM.db.session.query(ORM.User)
.join(ORM.UserRoleMap)
.join(ORM.Role)
.filter(
ORM.Role.project_id == subquery,
ORM.User.id == user_id,
ORM.User.is_deleted == False,
)
.first()
)
else:
# return all user data for super admin
return ORM.User.query.filter(
ORM.User.is_deleted == False, ORM.User.id == user_id
).first()
def get_user_list_for_project_admin(admin_id: int) -> List[ORM.User]:
admin_user: ORM.User | None = get_user_by_id(admin_id)
if not admin_user:
raise Exception('User not found for mapped apiKey')
if all(
user_role.role.role_type.role_name != RoleTypeEnum.SUPER_ADMIN.value
for user_role in admin_user.user_roles
):
if all(
user_role.role.role_type.role_name != RoleTypeEnum.PROJECT_ADMIN.value
for user_role in admin_user.user_roles
):
raise Exception('You do not have permission to view user list')
else:
# return all user data for project admin for his specific project
subquery = (
ORM.db.session.query(ORM.Role.project_id)
.join(ORM.UserRoleMap)
.filter(ORM.UserRoleMap.user_id == admin_id)
.subquery()
)
return (
ORM.db.session.query(ORM.User)
.join(ORM.UserRoleMap)
.join(ORM.Role)
.filter(
ORM.Role.project_id == subquery,
ORM.User.is_deleted == False,
)
.all()
)
else:
# return all user data for super admin
return ORM.User.query.filter(ORM.User.is_deleted == False).all()
...@@ -9,3 +9,10 @@ def login_payload() -> list: ...@@ -9,3 +9,10 @@ def login_payload() -> list:
) )
return [payload] return [payload]
def get_user_payload() -> list:
parser = api.parser()
parser.add_argument('id', required=True, type=int, location='args')
return [parser]
\ No newline at end of file
...@@ -48,3 +48,11 @@ def get_user_response() -> any: ...@@ -48,3 +48,11 @@ def get_user_response() -> any:
def get_user_profile_response() -> any: def get_user_profile_response() -> any:
return get_user_response() return get_user_response()
def get_user_list_response() -> any:
return prepare_swagger_response(
code=SUCCESS_CODE,
message=GET_ALL_SUCCESS_MESSAGE,
model_name='getUserList Response',
data=fields.List(fields.Nested(USER_RESPONSE_MODEL)),
)
\ No newline at end of file
...@@ -4,3 +4,7 @@ from marshmallow import Schema, fields, validate ...@@ -4,3 +4,7 @@ from marshmallow import Schema, fields, validate
class LoginValidator(Schema): class LoginValidator(Schema):
email = fields.String(required=True) email = fields.String(required=True)
password = fields.String(required=True) password = fields.String(required=True)
class GetUserValidator(Schema):
id = fields.Integer(required=True, validate=validate.Range(min=1))
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment