Commit f471b1ae authored by arun.uday's avatar arun.uday

Merge branch '1-arun-uday-asset-manager-v1-0' into 'master'

1 arun uday asset manager v1 0

See merge request !5
parents 24d0cc0c 94e90fa8
...@@ -19,10 +19,11 @@ EMAIL_PORT=465 ...@@ -19,10 +19,11 @@ EMAIL_PORT=465
EMAIL_PASSWORD=gpphuiweedqukchf EMAIL_PASSWORD=gpphuiweedqukchf
HTML_LINK=scripts/utils/link_email.html HTML_LINK=scripts/utils/link_email.html
RESET_ENDPOINT=http://localhost:8671/asset_manager_api/v1/login/reset?token RESET_ENDPOINT=http://localhost:8671/asset_manager_api/v1/login/reset?token
REDIRECT_URL_RESET=http://192.168.2.102/iLens_UI/#/l/login
CLIENT_ID=1060631831358-a21djaa3hm165a8976fnmo1lerujs5p6.apps.googleusercontent.com CLIENT_ID=1060631831358-a21djaa3hm165a8976fnmo1lerujs5p6.apps.googleusercontent.com
LOG_PATH=log LOG_PATH=log
LOG_LEVEL=INFO LOG_LEVEL=INFO
BACKUP_COUNT=100 BACKUP_COUNT=5
MAX_BYTES=5 MAX_BYTES=10000000
...@@ -38,5 +38,5 @@ if __name__ == "__main__": ...@@ -38,5 +38,5 @@ if __name__ == "__main__":
# starting the app # starting the app
uvicorn.run("main:app", host=arguments["bind"], port=int(arguments["port"])) uvicorn.run("main:app", host=arguments["bind"], port=int(arguments["port"]))
except Exception as e: except Exception as e:
logger.exception(f'Services Failed with error {e}') logger.exception(f'Services Failed with error from app {e}')
2023-04-04 20:12:33 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671 2023-04-05 19:15:09 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-05 19:15:29 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 10:07:03 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 11:15:22 - ERROR - [MainThread:db_password_matching(): 76] - Services Failed with error from process login db password matching hash could not be identified
2023-04-06 11:16:06 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 11:16:09 - ERROR - [MainThread:db_password_matching(): 76] - Services Failed with error from process login db password matching hash could not be identified
2023-04-06 11:16:56 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 11:17:02 - ERROR - [MainThread:db_password_matching(): 77] - Services Failed with error from process login db password matching hash could not be identified
2023-04-06 11:17:37 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 11:17:39 - ERROR - [MainThread:db_password_matching(): 77] - Services Failed with error from process login db password matching hash could not be identified
2023-04-06 11:18:13 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 11:18:16 - ERROR - [MainThread:db_password_matching(): 77] - Services Failed with error from process login db password matching hash could not be identified
2023-04-06 11:18:39 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 11:18:47 - ERROR - [MainThread:db_password_matching(): 77] - Services Failed with error from process login db password matching hash could not be identified
2023-04-06 12:15:33 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 14:43:59 - ERROR - [MainThread:reset_password(): 318] - Services Failed with error from reset user password 'password'
Traceback (most recent call last):
File "E:\Git\meta-services\scripts\core\handlers\user_management_handler.py", line 278, in reset_password
db_user_data["password"]):
KeyError: 'password'
2023-04-06 14:58:17 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 15:23:00 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 15:23:06 - ERROR - [MainThread:fetch_user_details(): 257] - Services Failed with error from fetch user details unhashable type: 'dict'
Traceback (most recent call last):
File "E:\Git\meta-services\scripts\core\handlers\user_management_handler.py", line 237, in fetch_user_details
cursor_data = obj_mongo_user.fetch_all_user_details({"user_id": {obj_stage.not_equal(request.user_id)}},
TypeError: unhashable type: 'dict'
2023-04-06 15:23:41 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-06 15:53:28 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-04 20:08:30 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-04 20:07:39 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-04 20:06:55 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-04 20:06:23 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-04-04 20:06:10 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
...@@ -37,4 +37,4 @@ if __name__ == "__main__": ...@@ -37,4 +37,4 @@ if __name__ == "__main__":
allow_headers=ServiceConf.CORS_ALLOW_HEADERS, allow_headers=ServiceConf.CORS_ALLOW_HEADERS,
) )
except Exception as e: except Exception as e:
logger.error(e) logger.error(f'Services Failed with error from main {e}')
import pathlib
from typing import Literal
from pydantic import BaseSettings, Field from pydantic import BaseSettings, Field
...@@ -24,6 +21,7 @@ class _Services(BaseSettings): ...@@ -24,6 +21,7 @@ class _Services(BaseSettings):
EMAIL_PASSWORD: str EMAIL_PASSWORD: str
HTML_LINK: str HTML_LINK: str
RESET_ENDPOINT: str RESET_ENDPOINT: str
REDIRECT_URL_RESET: str
DATE_TIME = '%Y-%m-%d %H:%M:%S' DATE_TIME = '%Y-%m-%d %H:%M:%S'
......
...@@ -42,4 +42,5 @@ class DashboardManagement: ...@@ -42,4 +42,5 @@ class DashboardManagement:
data=data).dict(), data=data).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from download header {e}')
return None
...@@ -33,6 +33,7 @@ class LoginHandlers: ...@@ -33,6 +33,7 @@ class LoginHandlers:
self.login_type = "" self.login_type = ""
def general_login(self, user_data, request): def general_login(self, user_data, request):
try:
self.login_type = "general_login" self.login_type = "general_login"
# decrypting the password from the UI # decrypting the password from the UI
decrypted_password = self.pass_decrypt.password_decrypt(user_data.password) decrypted_password = self.pass_decrypt.password_decrypt(user_data.password)
...@@ -74,9 +75,17 @@ class LoginHandlers: ...@@ -74,9 +75,17 @@ class LoginHandlers:
status_code=status.HTTP_200_OK, headers={"Content-Type": "application/json"}) status_code=status.HTTP_200_OK, headers={"Content-Type": "application/json"})
response.set_cookie(key="login-token", value=responses, expires=exp) response.set_cookie(key="login-token", value=responses, expires=exp)
return response return response
except Exception as e:
logger.error(f'Services Failed with error from general_login {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_LOGIN).dict(),
status_code=status.HTTP_200_OK)
def google_login(self, user_data, request): def google_login(self, user_data, request):
user_data_remove_none = {key: value for key, value in user_data if key != 'login_type' and value is not None} try:
user_data_remove_none = {key: value for key, value in user_data if
key != 'login_type' and value is not None}
req = requests.Request() req = requests.Request()
try: try:
id_info = id_token.verify_oauth2_token( id_info = id_token.verify_oauth2_token(
...@@ -115,6 +124,12 @@ class LoginHandlers: ...@@ -115,6 +124,12 @@ class LoginHandlers:
status_code=status.HTTP_200_OK, headers={"Content-Type": "application/json"}) status_code=status.HTTP_200_OK, headers={"Content-Type": "application/json"})
response.set_cookie(key="login-token", value=responses, expires=exp) response.set_cookie(key="login-token", value=responses, expires=exp)
return response return response
except Exception as e:
logger.error(f'Services Failed with error from google login {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_LOGIN).dict(),
status_code=status.HTTP_200_OK)
# v2 # v2
def microsoft_login(self, request): def microsoft_login(self, request):
...@@ -143,7 +158,6 @@ class LoginHandlers: ...@@ -143,7 +158,6 @@ class LoginHandlers:
expire = datetime.utcnow() + timedelta(minutes=Secrets.TOKEN_EXPIRE_TIME) expire = datetime.utcnow() + timedelta(minutes=Secrets.TOKEN_EXPIRE_TIME)
to_encode.update({"exp": expire}) to_encode.update({"exp": expire})
jwt_token = jwt.encode(to_encode) jwt_token = jwt.encode(to_encode)
html = ''
# Load the HTML file # Load the HTML file
try: try:
with open(Services.HTML_LINK, "r") as f: with open(Services.HTML_LINK, "r") as f:
...@@ -151,7 +165,9 @@ class LoginHandlers: ...@@ -151,7 +165,9 @@ class LoginHandlers:
html = html.replace("{{ message }}", "Please click the link to reset your password:").replace( html = html.replace("{{ message }}", "Please click the link to reset your password:").replace(
"{{ link }}", Services.RESET_ENDPOINT + "=" + str(jwt_token)) "{{ link }}", Services.RESET_ENDPOINT + "=" + str(jwt_token))
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(logger.error(f'Services Failed sending email {e}'))
return
html_body = MIMEText(html, "html") html_body = MIMEText(html, "html")
mail.attach(html_body) mail.attach(html_body)
context = ssl.create_default_context() context = ssl.create_default_context()
...@@ -164,7 +180,11 @@ class LoginHandlers: ...@@ -164,7 +180,11 @@ class LoginHandlers:
content=DefaultSuccessResponse(status="success", message="Email Send Successfully").dict(), content=DefaultSuccessResponse(status="success", message="Email Send Successfully").dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from forgot password handler {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_SENDING_MAIL).dict(),
status_code=status.HTTP_200_OK)
@staticmethod @staticmethod
def validate_jwt(request): def validate_jwt(request):
...@@ -182,12 +202,16 @@ class LoginHandlers: ...@@ -182,12 +202,16 @@ class LoginHandlers:
message=ErrorMessages.ERROR_USER_ID_DOESNT_EXIST).dict(), message=ErrorMessages.ERROR_USER_ID_DOESNT_EXIST).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
jwt_token_new = jwt.encode({"email": decoded_token['email']}) jwt_token_new = jwt.encode({"email": decoded_token['email']})
return RedirectResponse('http://192.168.2.102/iLens_UI/#/l/login?user_id=' + jwt_token_new) return RedirectResponse(Services.REDIRECT_URL_RESET + '?user_id=' + jwt_token_new)
except ExpiredSignatureError: except ExpiredSignatureError:
return RedirectResponse( return RedirectResponse(
'http://192.168.2.102/iLens_UI/#/l/login?error=' + "true") Services.REDIRECT_URL_RESET + '?error=' + "true")
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from validate jwt {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_RESETTING_PASSWORD).dict(),
status_code=status.HTTP_200_OK)
@staticmethod @staticmethod
def reset_user_password(reset_data): def reset_user_password(reset_data):
...@@ -210,13 +234,19 @@ class LoginHandlers: ...@@ -210,13 +234,19 @@ class LoginHandlers:
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_USER_ID_DOESNT_EXIST).dict(), message=ErrorMessages.ERROR_USER_ID_DOESNT_EXIST).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
response = EncryptDecryptPassword().password_encrypt(reset_data.password) response, password_encrypted = EncryptDecryptPassword().check_password_mismatch(
reset_data.new_password, reset_data.confirm_password)
if not response: if not response:
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=password_encrypted).dict(),
status_code=status.HTTP_200_OK)
if not password_encrypted:
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_AUTH_FAILED).dict(), message=ErrorMessages.ERROR_AUTH_FAILED).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
response = obj_mongo_user.update_user({"email": decoded_token['email']}, {"password": response}) response = obj_mongo_user.update_user({"email": decoded_token['email']}, {"password": password_encrypted})
if not response: if not response:
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
...@@ -226,6 +256,13 @@ class LoginHandlers: ...@@ -226,6 +256,13 @@ class LoginHandlers:
content=DefaultSuccessResponse(status="success", message="Reset Successful").dict(), content=DefaultSuccessResponse(status="success", message="Reset Successful").dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
except ExpiredSignatureError: except ExpiredSignatureError:
return "Password Reset Token Expired" return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_INVALID_TOKEN).dict(),
status_code=status.HTTP_200_OK)
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from reset user password {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_RESETTING_PASSWORD).dict(),
status_code=status.HTTP_200_OK)
...@@ -31,7 +31,8 @@ class NormalLogin: ...@@ -31,7 +31,8 @@ class NormalLogin:
return ErrorMessages.ERROR_INVALID_PASSWORD return ErrorMessages.ERROR_INVALID_PASSWORD
return None return None
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from process login user data validation {e}')
return None
# db validation # db validation
def db_data_validation(self, login_type, email): def db_data_validation(self, login_type, email):
...@@ -47,7 +48,7 @@ class NormalLogin: ...@@ -47,7 +48,7 @@ class NormalLogin:
try: try:
response = {"user_id": self.db_user_data["user_id"], "name": self.db_user_data["name"], response = {"user_id": self.db_user_data["user_id"], "name": self.db_user_data["name"],
"email": email, "email": email,
"user_role": self.db_user_data["user_role"]} "user_role": self.db_user_data["user_role"], "login_type": self.db_user_data["login_type"]}
except KeyError: except KeyError:
response = {"user_id": self.db_user_data["user_id"], response = {"user_id": self.db_user_data["user_id"],
"email": email, "email": email,
...@@ -55,7 +56,8 @@ class NormalLogin: ...@@ -55,7 +56,8 @@ class NormalLogin:
# if the user exist # if the user exist
return None, response return None, response
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from process login db data validation {e}')
return True, "Exception"
# matching the password # matching the password
def db_password_matching(self, login_type, user_data, password): def db_password_matching(self, login_type, user_data, password):
...@@ -71,14 +73,19 @@ class NormalLogin: ...@@ -71,14 +73,19 @@ class NormalLogin:
# if the password is correct # if the password is correct
return None, message return None, message
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from process login db password matching {e}')
return True, "Exception"
@staticmethod @staticmethod
def update_pic(obj_mongo_user, info_data): def update_pic(obj_mongo_user, info_data):
try:
if not obj_mongo_user.update_user({"email": info_data["email"]}, if not obj_mongo_user.update_user({"email": info_data["email"]},
{"name": info_data["name"], "pic_url": info_data["picture"]}): {"name": info_data["name"], "pic_url": info_data["picture"]}):
return None return None
return True return True
except Exception as e:
logger.error(f'Services Failed with error from process login update pic {e}')
return None
# cookie and token creation # cookie and token creation
@staticmethod @staticmethod
...@@ -95,4 +102,5 @@ class NormalLogin: ...@@ -95,4 +102,5 @@ class NormalLogin:
else: else:
return None return None
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from process login cookie tokens {e}')
return None
import datetime import datetime
import uuid import uuid
from fastapi import status
from fastapi.responses import JSONResponse
from passlib.context import CryptContext from passlib.context import CryptContext
from scripts.database.mongo.mongo_db import MongoUser from scripts.database.mongo.mongo_db import MongoUser
from scripts.database.redis.redis_conn import login_db from scripts.database.redis.redis_conn import login_db
from scripts.errors import ErrorMessages from scripts.errors import ErrorMessages
from scripts.logging.logger import logger from scripts.logging.logger import logger
from fastapi.responses import JSONResponse
from fastapi import status
from scripts.schemas.default_responses import DefaultResponse, DefaultFailureResponse, DefaultSuccessResponse from scripts.schemas.default_responses import DefaultResponse, DefaultFailureResponse, DefaultSuccessResponse
from scripts.utils.mongo_utils import MongoStageCreator from scripts.utils.mongo_utils import MongoStageCreator
from scripts.utils.response_utils import ResponseData from scripts.utils.response_utils import ResponseData
from scripts.utils.security.authorize_access import AuthorizeAccess
from scripts.utils.security.password_util import EncryptDecryptPassword from scripts.utils.security.password_util import EncryptDecryptPassword
from scripts.utils.validations_util import UserDataValidations from scripts.utils.validations_util import UserDataValidations
obj_mongo_user = MongoUser() obj_mongo_user = MongoUser()
obj_response_data = ResponseData() obj_response_data = ResponseData()
obj_stage = MongoStageCreator() obj_stage = MongoStageCreator()
obj_authorize = AuthorizeAccess()
# user management # user management
...@@ -34,7 +36,7 @@ class UserManagement: ...@@ -34,7 +36,7 @@ class UserManagement:
if not response: if not response:
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=message["message"]).dict(), message=message).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
# fetching the data based on the username # fetching the data based on the username
db_user_data = obj_mongo_user.fetch_one_user_details({"email": user_data.email}) db_user_data = obj_mongo_user.fetch_one_user_details({"email": user_data.email})
...@@ -71,7 +73,11 @@ class UserManagement: ...@@ -71,7 +73,11 @@ class UserManagement:
content=DefaultSuccessResponse(status="success", message="User Registration Successful").dict(), content=DefaultSuccessResponse(status="success", message="User Registration Successful").dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from general register {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_REGISTERING).dict(),
status_code=status.HTTP_200_OK)
@staticmethod @staticmethod
# for Google registration using gmail # for Google registration using gmail
...@@ -104,7 +110,11 @@ class UserManagement: ...@@ -104,7 +110,11 @@ class UserManagement:
content=DefaultSuccessResponse(status="success", message="User Registration Successful").dict(), content=DefaultSuccessResponse(status="success", message="User Registration Successful").dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from google register {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_REGISTERING).dict(),
status_code=status.HTTP_200_OK)
@staticmethod @staticmethod
# for microsoft registration using microsoft account # for microsoft registration using microsoft account
...@@ -112,7 +122,11 @@ class UserManagement: ...@@ -112,7 +122,11 @@ class UserManagement:
try: try:
return {"message": "Not available"} return {"message": "Not available"}
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from microsoft register {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_REGISTERING).dict(),
status_code=status.HTTP_200_OK)
# update user details # update user details
def update_user_details(self, update_data): def update_user_details(self, update_data):
...@@ -137,15 +151,8 @@ class UserManagement: ...@@ -137,15 +151,8 @@ class UserManagement:
status_code=status.HTTP_404_NOT_FOUND) status_code=status.HTTP_404_NOT_FOUND)
# creating the filter data # creating the filter data
filter_data_updated = {"user_id": update_data.user_id} filter_data_updated = {"user_id": update_data.user_id}
encrypted = EncryptDecryptPassword().password_encrypt(update_data.password)
if encrypted is None:
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_INVALID_PASSWORD).dict(),
status_code=status.HTTP_200_OK)
# encrypting the password # encrypting the password
update_data_removed = {key: (encrypted update_data_removed = {key: value for key, value in update_data if
if key == "password" else value) for key, value in update_data if
key != 'action' and value is not None} key != 'action' and value is not None}
# validating the data # validating the data
response, message = UserDataValidations.update_data_validation(update_data) response, message = UserDataValidations.update_data_validation(update_data)
...@@ -162,11 +169,16 @@ class UserManagement: ...@@ -162,11 +169,16 @@ class UserManagement:
content=DefaultSuccessResponse(status="success", message="Updated Successfully").dict(), content=DefaultSuccessResponse(status="success", message="Updated Successfully").dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from update user {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_UPDATING).dict(),
status_code=status.HTTP_200_OK)
# delete user # delete user
@staticmethod @staticmethod
def delete_user_details(user_id): def delete_user_details(user_id):
try:
# fetching and validating the user id # fetching and validating the user id
db_user_data = obj_mongo_user.fetch_one_user_details({"user_id": user_id}) db_user_data = obj_mongo_user.fetch_one_user_details({"user_id": user_id})
# if the user is not available # if the user is not available
...@@ -187,6 +199,8 @@ class UserManagement: ...@@ -187,6 +199,8 @@ class UserManagement:
return JSONResponse( return JSONResponse(
content=DefaultSuccessResponse(status="success", message="Deleted Successfully").dict(), content=DefaultSuccessResponse(status="success", message="Deleted Successfully").dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
except Exception as e:
logger.exception(f'Services Failed with error from delete user {e}')
@staticmethod @staticmethod
def fetch_view_header(): def fetch_view_header():
...@@ -203,20 +217,24 @@ class UserManagement: ...@@ -203,20 +217,24 @@ class UserManagement:
message=ErrorMessages.ERROR_IN_FETCHING).dict(), message=ErrorMessages.ERROR_IN_FETCHING).dict(),
status_code=status.HTTP_404_NOT_FOUND) status_code=status.HTTP_404_NOT_FOUND)
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from fetch user header {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_FETCHING_HEADER).dict(),
status_code=status.HTTP_200_OK)
@staticmethod @staticmethod
def fetch_user_details(): def fetch_user_details():
try: try:
# defining the filter values # defining the filter values
filter_data = {'_id': 0, filter_data = {'_id': 0,
"login_type": 0,
"is_alive": 0, "is_alive": 0,
"password": 0, "password": 0,
"created_at": 0, "created_at": 0,
"updated_at": 0} "updated_at": 0}
# filtering the users and getting all the details # filtering the users and getting all the details
cursor_data = obj_mongo_user.fetch_all_user_details({}, filter_data) cursor_data = obj_mongo_user.fetch_all_user_details({},
filter_data)
cursor_data_count = cursor_data.explain() cursor_data_count = cursor_data.explain()
# counting the total records in the query # counting the total records in the query
if cursor_data_count["executionStats"]["nReturned"] <= 0: if cursor_data_count["executionStats"]["nReturned"] <= 0:
...@@ -235,10 +253,21 @@ class UserManagement: ...@@ -235,10 +253,21 @@ class UserManagement:
message=ErrorMessages.ERROR_IN_FETCHING).dict(), message=ErrorMessages.ERROR_IN_FETCHING).dict(),
status_code=status.HTTP_404_NOT_FOUND) status_code=status.HTTP_404_NOT_FOUND)
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from fetch user details {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_FETCHING).dict(),
status_code=status.HTTP_200_OK)
# user change password # user change password
def reset_password(self, reset_data): def reset_password(self, request, reset_data):
try:
response = obj_authorize.login_authorize(request, reset_data)
if not response:
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_UNAUTHORIZED_ACCESS).dict(),
status_code=status.HTTP_200_OK)
db_user_data = obj_mongo_user.fetch_one_user_details({"user_id": reset_data.user_id}) db_user_data = obj_mongo_user.fetch_one_user_details({"user_id": reset_data.user_id})
# if the user is not available # if the user is not available
if db_user_data is None: if db_user_data is None:
...@@ -246,17 +275,30 @@ class UserManagement: ...@@ -246,17 +275,30 @@ class UserManagement:
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_USER_ID_DOESNT_EXIST).dict(), message=ErrorMessages.ERROR_USER_ID_DOESNT_EXIST).dict(),
status_code=status.HTTP_404_NOT_FOUND) status_code=status.HTTP_404_NOT_FOUND)
if not self.pwd_context.verify(self.pass_decrypt.password_decrypt(reset_data.old_password).split("\"")[1],
db_user_data["password"]):
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_PASSWORD_MISMATCH).dict(),
status_code=status.HTTP_200_OK)
try: try:
decrypted_password = self.pass_decrypt.password_decrypt(reset_data.new_password) response, password_encrypted = self.pass_decrypt.check_password_mismatch(reset_data.new_password,
except TypeError: reset_data.confirm_password,
reset_data.old_password)
if not response:
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_INVALID_PASSWORD).dict(), message=password_encrypted).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
if not self.pwd_context.verify(decrypted_password.split("\"")[1], db_user_data["password"]): if not password_encrypted:
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_PASSWORD_MISMATCH).dict(), message=ErrorMessages.ERROR_AUTH_FAILED).dict(),
status_code=status.HTTP_200_OK)
except TypeError:
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_INVALID_PASSWORD).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
response = EncryptDecryptPassword().password_encrypt(reset_data.new_password) response = EncryptDecryptPassword().password_encrypt(reset_data.new_password)
if not response: if not response:
...@@ -273,6 +315,12 @@ class UserManagement: ...@@ -273,6 +315,12 @@ class UserManagement:
return JSONResponse( return JSONResponse(
content=DefaultSuccessResponse(status="success", message="Password Changed Successfully").dict(), content=DefaultSuccessResponse(status="success", message="Password Changed Successfully").dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
except Exception as e:
logger.exception(f'Services Failed with error from reset user password {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_RESETTING_PASSWORD).dict(),
status_code=status.HTTP_200_OK)
# user logout # user logout
@staticmethod @staticmethod
...@@ -295,4 +343,8 @@ class UserManagement: ...@@ -295,4 +343,8 @@ class UserManagement:
response.delete_cookie("login-token") response.delete_cookie("login-token")
return response return response
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from user logout {e}')
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_LOGOUT).dict(),
status_code=status.HTTP_200_OK)
...@@ -58,9 +58,3 @@ class MongoUser(CollectionBaseClass): ...@@ -58,9 +58,3 @@ class MongoUser(CollectionBaseClass):
if user := self.delete_one(query=query): if user := self.delete_one(query=query):
return user return user
return None return None
# for filtering
def filter_data_aggregate(self, pipeline):
if user := self.aggregate(pipelines=pipeline):
return user
return None
...@@ -6,6 +6,7 @@ class ErrorMessages: ...@@ -6,6 +6,7 @@ class ErrorMessages:
ERROR_INVALID_LOGIN = "Your are not authorized to view this website." ERROR_INVALID_LOGIN = "Your are not authorized to view this website."
ERROR_ACCOUNT_DOESNT_EXIST = "Account Does Not Exist" ERROR_ACCOUNT_DOESNT_EXIST = "Account Does Not Exist"
ERROR_UNAUTHORIZED_USER_LOGIN = "Account is not available" ERROR_UNAUTHORIZED_USER_LOGIN = "Account is not available"
ERROR_IN_LOGIN = "Login Error"
ERROR_UNAUTHORIZED_ACCESS = "Your are not authorized to view this page" ERROR_UNAUTHORIZED_ACCESS = "Your are not authorized to view this page"
ERROR_ACCESS_DENIED = "Access Denied!" ERROR_ACCESS_DENIED = "Access Denied!"
ERROR_USER_NOT_REGISTERED = "Account is not registered in the portal." ERROR_USER_NOT_REGISTERED = "Account is not registered in the portal."
...@@ -18,6 +19,13 @@ class ErrorMessages: ...@@ -18,6 +19,13 @@ class ErrorMessages:
ERROR_INVALID_REQUEST = "Invalid Request" ERROR_INVALID_REQUEST = "Invalid Request"
ERROR_USER_SESSION = "Not The Users Session" ERROR_USER_SESSION = "Not The Users Session"
ERROR_TOKEN_EXPIRED = "Google Token Expired" ERROR_TOKEN_EXPIRED = "Google Token Expired"
ERROR_IN_SENDING_MAIL = "Error In Sending Mail"
ERROR_IN_RESETTING_PASSWORD = "Password Reset Failed"
ERROR_IN_REGISTERING = "User Cannot Be Added"
ERROR_IN_DELETING = "User Deletion Error"
ERROR_IN_FETCHING_HEADER = "Header Fetch Failed"
ERROR_IN_LOGOUT = "Logout Failed"
ERROR_PASSWORD_FAILED = "Password Validation Failed"
# Data Validation # Data Validation
ERROR_INVALID_PASSWORD = "Invalid Password" ERROR_INVALID_PASSWORD = "Invalid Password"
...@@ -28,3 +36,6 @@ class ErrorMessages: ...@@ -28,3 +36,6 @@ class ErrorMessages:
ERROR_USER_ID_DOESNT_EXIST = "User Id doesn't exist" ERROR_USER_ID_DOESNT_EXIST = "User Id doesn't exist"
ERROR_USER_ID = "User Id Not Required" ERROR_USER_ID = "User Id Not Required"
ERROR_INVALID_TOKEN = "Invalid Token" ERROR_INVALID_TOKEN = "Invalid Token"
ERROR_IN_VALIDATION = "Validation Failed"
ERROR_MISMATCH_CONFIRM = "New Password and Confirm Password Must Be Same"
ERROR_PASSWORD_EMPTY = "Password Cannot be Empty"
...@@ -25,7 +25,7 @@ class UserActions(BaseModel): ...@@ -25,7 +25,7 @@ class UserActions(BaseModel):
user_id: Optional[str] = None user_id: Optional[str] = None
name: Optional[str] = None name: Optional[str] = None
email: Optional[str] = None email: Optional[str] = None
password: Optional[str] password: Optional[str] = None
phone_number: Optional[str] = None phone_number: Optional[str] = None
login_type: Optional[str] = None login_type: Optional[str] = None
user_role: Optional[str] = None user_role: Optional[str] = None
...@@ -41,6 +41,7 @@ class ResetPassword(BaseModel): ...@@ -41,6 +41,7 @@ class ResetPassword(BaseModel):
user_id: str user_id: str
old_password: Optional[str] = None old_password: Optional[str] = None
new_password: str new_password: str
confirm_password: str
class UserIDValidation(BaseModel): class UserIDValidation(BaseModel):
......
...@@ -43,7 +43,7 @@ async def login_default_api( ...@@ -43,7 +43,7 @@ async def login_default_api(
detail=ErrorMessages.ERROR_INVALID_REQUEST) detail=ErrorMessages.ERROR_INVALID_REQUEST)
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from login_default_api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -58,9 +58,14 @@ async def forgot_password( ...@@ -58,9 +58,14 @@ async def forgot_password(
try: try:
# forgot password # forgot password
response = obj_login_handler.forgot_password_handler(validation_data.email) response = obj_login_handler.forgot_password_handler(validation_data.email)
if not response:
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_SENDING_MAIL).dict(),
status_code=status.HTTP_200_OK)
return response return response
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from forgot password api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -75,9 +80,14 @@ async def reset_password( ...@@ -75,9 +80,14 @@ async def reset_password(
try: try:
# Get the JWT token from the query parameters # Get the JWT token from the query parameters
response = obj_login_handler.validate_jwt(request) response = obj_login_handler.validate_jwt(request)
if not response:
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_RESETTING_PASSWORD).dict(),
status_code=status.HTTP_200_OK)
return response return response
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from get reset password api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -92,9 +102,14 @@ async def reset_password( ...@@ -92,9 +102,14 @@ async def reset_password(
try: try:
# Get the JWT token from the query parameters # Get the JWT token from the query parameters
response = obj_login_handler.reset_user_password(reset_data) response = obj_login_handler.reset_user_password(reset_data)
if not response:
return JSONResponse(
content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_IN_RESETTING_PASSWORD).dict(),
status_code=status.HTTP_200_OK)
return response return response
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from post reset password api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -135,7 +150,7 @@ async def user_management( ...@@ -135,7 +150,7 @@ async def user_management(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
detail=ErrorMessages.ERROR_INVALID_REQUEST) detail=ErrorMessages.ERROR_INVALID_REQUEST)
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from user management api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -163,7 +178,7 @@ async def user_view_header( ...@@ -163,7 +178,7 @@ async def user_view_header(
detail=ErrorMessages.ERROR_IN_FETCHING) detail=ErrorMessages.ERROR_IN_FETCHING)
return response return response
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from view users header api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -190,7 +205,7 @@ async def user_view_data( ...@@ -190,7 +205,7 @@ async def user_view_data(
detail=ErrorMessages.ERROR_IN_FETCHING) detail=ErrorMessages.ERROR_IN_FETCHING)
return response return response
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from view users data api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -211,14 +226,14 @@ async def user_change_password( ...@@ -211,14 +226,14 @@ async def user_change_password(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.ERROR_UNAUTHORIZED_ACCESS).dict(), message=ErrorMessages.ERROR_UNAUTHORIZED_ACCESS).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
response = obj_user_handler.reset_password(reset_data) response = obj_user_handler.reset_password(request, reset_data)
if not response: if not response:
return HTTPException( return HTTPException(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
detail=ErrorMessages.ERROR_IN_FETCHING) detail=ErrorMessages.ERROR_IN_FETCHING)
return response return response
except Exception as e: except Exception as e:
logger.exception(f"From user change password - {e}") logger.exception(f'Services Failed with error from change password api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -245,7 +260,7 @@ async def dashboard_download_files( ...@@ -245,7 +260,7 @@ async def dashboard_download_files(
detail=ErrorMessages.ERROR_IN_FETCHING) detail=ErrorMessages.ERROR_IN_FETCHING)
return response return response
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from download button api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
...@@ -268,7 +283,7 @@ async def user_logout( ...@@ -268,7 +283,7 @@ async def user_logout(
detail=ErrorMessages.ERROR_IN_FETCHING) detail=ErrorMessages.ERROR_IN_FETCHING)
return response return response
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(f'Services Failed with error from logout api {e}')
return JSONResponse( return JSONResponse(
content=DefaultFailureResponse(status="failed", content=DefaultFailureResponse(status="failed",
message=ErrorMessages.OP_FAILED).dict(), message=ErrorMessages.OP_FAILED).dict(),
......
...@@ -60,3 +60,6 @@ class MongoStageCreator: ...@@ -60,3 +60,6 @@ class MongoStageCreator:
def regex_stage(self, stage: dict) -> dict: def regex_stage(self, stage: dict) -> dict:
return self.add_stage("$regex", stage) return self.add_stage("$regex", stage)
def not_equal(self, stage: dict) -> dict:
return self.add_stage("$ne", stage)
...@@ -11,7 +11,8 @@ class RegexValidation: ...@@ -11,7 +11,8 @@ class RegexValidation:
regex = re.fullmatch(r'^([A-Za-z]+)*$', str(name)) regex = re.fullmatch(r'^([A-Za-z]+)*$', str(name))
return regex return regex
except Exception as e: except Exception as e:
logger.error(f'An Error While listing the home plans {str(e)}') logger.error(f'Error in name regex {str(e)}')
return None
@staticmethod @staticmethod
def phone_number_validation(phone_number): def phone_number_validation(phone_number):
...@@ -19,7 +20,8 @@ class RegexValidation: ...@@ -19,7 +20,8 @@ class RegexValidation:
regex = re.fullmatch('([0-9]{1,20})', str(phone_number)) regex = re.fullmatch('([0-9]{1,20})', str(phone_number))
return regex return regex
except Exception as e: except Exception as e:
logger.error(f'An Error While listing the home plans {str(e)}') logger.error(f'An Error in phone number regex {str(e)}')
return None
@staticmethod @staticmethod
def password_validation(password): def password_validation(password):
...@@ -29,4 +31,5 @@ class RegexValidation: ...@@ -29,4 +31,5 @@ class RegexValidation:
return False return False
except Exception as e: except Exception as e:
logger.error(f'An Error While listing the home plans {str(e)}') logger.error(f'Error in password regex {str(e)}')
return None
from typing import Optional from typing import Optional
from scripts.database.mongo.mongo_db import MongoUser from scripts.database.mongo.mongo_db import MongoUser
from scripts.logging.logger import logger
from scripts.schemas.project_schema import ResetPassword from scripts.schemas.project_schema import ResetPassword
obj_mongo_user = MongoUser() obj_mongo_user = MongoUser()
...@@ -18,9 +19,13 @@ class AuthorizeAccess: ...@@ -18,9 +19,13 @@ class AuthorizeAccess:
return True return True
except TypeError: except TypeError:
return False return False
except Exception as e:
logger.error(f'Services Failed with error from authorize access {e}')
return False
@staticmethod @staticmethod
def login_authorize(request, reset_data: Optional[ResetPassword] = None): def login_authorize(request, reset_data: Optional[ResetPassword] = None):
try:
if reset_data is not None: if reset_data is not None:
if reset_data.user_id != request.user_id: if reset_data.user_id != request.user_id:
return False return False
...@@ -28,3 +33,6 @@ class AuthorizeAccess: ...@@ -28,3 +33,6 @@ class AuthorizeAccess:
if request.user_id: if request.user_id:
return True return True
return False return False
except Exception as e:
logger.error(f'Services Failed with error from login authorize {e}')
return False
...@@ -20,11 +20,7 @@ class JWT: ...@@ -20,11 +20,7 @@ class JWT:
# decoding the payload # decoding the payload
def decode(self, token): def decode(self, token):
try:
return jwt.decode(token, self.key, algorithms=self.alg) return jwt.decode(token, self.key, algorithms=self.alg)
except Exception as e:
logging.exception(f"Exception while encoding JWT: {str(e)}")
raise
# validate the payload # validate the payload
def validate(self, token): def validate(self, token):
...@@ -39,3 +35,4 @@ class JWT: ...@@ -39,3 +35,4 @@ class JWT:
except Exception as e: except Exception as e:
logging.exception(f"Exception while validating JWT: {str(e)}") logging.exception(f"Exception while validating JWT: {str(e)}")
raise
import base64 import base64
from typing import Optional
from Cryptodome.Cipher import AES from Cryptodome.Cipher import AES
from passlib.context import CryptContext from passlib.context import CryptContext
from scripts.config import Secrets, Services from scripts.config import Secrets, Services
from scripts.errors import ErrorMessages
from scripts.logging.logger import logger from scripts.logging.logger import logger
...@@ -36,10 +39,12 @@ class EncryptDecryptPassword: ...@@ -36,10 +39,12 @@ class EncryptDecryptPassword:
data = self.un_pad(data) data = self.un_pad(data)
return data.decode(Services.ENCODING_TYPE) return data.decode(Services.ENCODING_TYPE)
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Services Failed with error from password util password decrypt {e}')
return None
# encrypting the password # encrypting the password
def password_encrypt(self, password): def password_encrypt(self, password):
try:
# decrypting the UI password # decrypting the UI password
decrypted_password = self.password_decrypt(password) decrypted_password = self.password_decrypt(password)
# hashing the decrypted password # hashing the decrypted password
...@@ -47,3 +52,24 @@ class EncryptDecryptPassword: ...@@ -47,3 +52,24 @@ class EncryptDecryptPassword:
return None return None
hashed_password = self.pwd_context.hash(decrypted_password.split("\"")[1]) hashed_password = self.pwd_context.hash(decrypted_password.split("\"")[1])
return hashed_password return hashed_password
except Exception as e:
logger.error(f'Services Failed with error from password util password encrypt {e}')
return None
def check_password_mismatch(self, new_password, confirm_password, old_password: Optional[str] = None):
try:
# decrypting the UI password
password_decrypted = self.password_decrypt(new_password)
confirm_decrypted = self.password_decrypt(confirm_password)
if password_decrypted != confirm_decrypted:
return None, ErrorMessages.ERROR_MISMATCH_CONFIRM
# hashing the decrypted password
if confirm_decrypted is None:
return None, ErrorMessages.ERROR_PASSWORD_EMPTY
if old_password is not None:
return True, confirm_decrypted
hashed_password = self.pwd_context.hash(confirm_decrypted.split("\"")[1])
return True, hashed_password
except Exception as e:
logger.error(f'Services Failed with error from password util check password mismatch {e}')
return None, ErrorMessages.ERROR_PASSWORD_FAILED
...@@ -12,36 +12,33 @@ class UserDataValidations: ...@@ -12,36 +12,33 @@ class UserDataValidations:
def register_data_validation(user_data, method, feature): def register_data_validation(user_data, method, feature):
try: try:
if user_data.name == "": if user_data.name == "":
return False, {"message": ErrorMessages.ERROR_INVALID_NAME, return False, ErrorMessages.ERROR_INVALID_NAME
"data": user_data.phone_number}
# checking for valid username # checking for valid username
if user_data.email == "" or validate_email( if user_data.email == "" or validate_email(
user_data.email) is not True: user_data.email) is not True:
return False, {"message": ErrorMessages.ERROR_INVALID_EMAIL, "data": user_data.email} return False, ErrorMessages.ERROR_INVALID_EMAIL
# checking for valid password # checking for valid password
if method == 'general': if method == 'general':
if user_data.password == "" or user_data.password == "string": if user_data.password == "" or user_data.password == "string":
return False, {"message": ErrorMessages.ERROR_INVALID_PASSWORD, "data": user_data.password} return False, ErrorMessages.ERROR_INVALID_PASSWORD
# Validate phone number # Validate phone number
if user_data.phone_number == "": if user_data.phone_number == "":
return False, {"message": ErrorMessages.ERROR_INVALID_PHONE_NUMBER, return False, ErrorMessages.ERROR_INVALID_PHONE_NUMBER
"data": user_data.phone_number}
if user_data.user_role == "" and method == 'general' and feature == 'register': if user_data.user_role == "" and method == 'general' and feature == 'register':
return False, {"message": ErrorMessages.ERROR_INVALID_USER_ROLE, return False, ErrorMessages.ERROR_INVALID_USER_ROLE
"data": user_data.phone_number}
return True, None return True, None
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Register data validation error {e}')
return False, ErrorMessages.ERROR_IN_VALIDATION
@staticmethod @staticmethod
def update_data_validation(user_data): def update_data_validation(user_data):
try: try:
if user_data.name == "": if user_data.name == "":
return False, {"message": ErrorMessages.ERROR_INVALID_NAME, return False, ErrorMessages.ERROR_INVALID_NAME
"data": user_data.phone_number}
if user_data.user_role == "": if user_data.user_role == "":
return False, {"message": ErrorMessages.ERROR_INVALID_USER_ROLE, return False, ErrorMessages.ERROR_INVALID_USER_ROLE
"data": user_data.phone_number}
return True, None return True, None
except Exception as e: except Exception as e:
logger.exception(e) logger.error(f'Update data validation error {e}')
return False, ErrorMessages.ERROR_IN_VALIDATION
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