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

AssetManager-V1.0- Not reveiwed

Removed project id and formatted the url request data and the collection of the request.
parent a7bc9ea3
...@@ -8,7 +8,6 @@ SERVICE_HOST=0.0.0.0 ...@@ -8,7 +8,6 @@ SERVICE_HOST=0.0.0.0
SERVICE_PORT=8671 SERVICE_PORT=8671
PROJECT_NAME=AssetManager PROJECT_NAME=AssetManager
PROJECT_ID=1256
BASE_PATH=scripts/ BASE_PATH=scripts/
SUB_PATH=log/ SUB_PATH=log/
......
...@@ -8,7 +8,6 @@ class _Services(BaseSettings): ...@@ -8,7 +8,6 @@ class _Services(BaseSettings):
HOST: str = Field(default="127.0.0.1", env="service_host") HOST: str = Field(default="127.0.0.1", env="service_host")
PORT: int = Field(default=8000, env="service_port") PORT: int = Field(default=8000, env="service_port")
PROJECT_NAME = Field(default="AssetManager", env="project_name") PROJECT_NAME = Field(default="AssetManager", env="project_name")
PROJECT_ID = Field(default="1256", env="project_id")
ENCODING_TYPE = Field(default="utf-8", env="encoding_type") ENCODING_TYPE = Field(default="utf-8", env="encoding_type")
ENABLE_CORS: bool = True ENABLE_CORS: bool = True
CORS_URLS: list[str] = ["*.ilens.io"] CORS_URLS: list[str] = ["*.ilens.io"]
......
...@@ -10,15 +10,14 @@ class LoginHandlers: ...@@ -10,15 +10,14 @@ class LoginHandlers:
self.obj_login_handler = NormalLogin() self.obj_login_handler = NormalLogin()
self.login_type = "" self.login_type = ""
def normal_login(self, login_data, request): def normal_login(self, user_data, request):
self.login_type = "normal" self.login_type = "normal"
# decrypting the password from the UI # decrypting the password from the UI
decrypted_password = self.obj_login_handler.password_decrypt(login_data.payload["password"]) decrypted_password = self.obj_login_handler.password_decrypt(user_data.password)
# validating the received inputs empty or not # validating the received inputs empty or not
response = self.obj_login_handler.user_data_validation( response = self.obj_login_handler.user_data_validation(
login_data.payload["username"], user_data.username,
login_data.project_id,
decrypted_password) decrypted_password)
# Account is not registered # Account is not registered
...@@ -26,7 +25,7 @@ class LoginHandlers: ...@@ -26,7 +25,7 @@ class LoginHandlers:
return JSONResponse(content=DefaultFailureResponse(error=response).dict(), return JSONResponse(content=DefaultFailureResponse(error=response).dict(),
status_code=status.HTTP_400_BAD_REQUEST) status_code=status.HTTP_400_BAD_REQUEST)
# checking for the account and password matching # checking for the account and password matching
response, data = self.obj_login_handler.db_password_matching(self.login_type, login_data.payload, response, data = self.obj_login_handler.db_password_matching(self.login_type, user_data,
decrypted_password) decrypted_password)
# if the passwords doesn't match with the db data # if the passwords doesn't match with the db data
if response is not None: if response is not None:
...@@ -34,7 +33,7 @@ class LoginHandlers: ...@@ -34,7 +33,7 @@ class LoginHandlers:
status_code=status.HTTP_401_UNAUTHORIZED) status_code=status.HTTP_401_UNAUTHORIZED)
# generating the access tokens # generating the access tokens
response = self.obj_login_handler.generate_cookie_tokens(login_data.payload, request) response = self.obj_login_handler.generate_cookie_tokens(user_data, request)
# token generation unsuccessful # token generation unsuccessful
if response is None: if response is None:
return JSONResponse( return JSONResponse(
...@@ -43,7 +42,7 @@ class LoginHandlers: ...@@ -43,7 +42,7 @@ class LoginHandlers:
status_code=status.HTTP_403_FORBIDDEN) status_code=status.HTTP_403_FORBIDDEN)
# sending successful response to UI # sending successful response to UI
return JSONResponse( return JSONResponse(
content=DefaultResponse(message="Login Successful", payload=response).dict(), content=DefaultResponse(message="Login Successful", data=response).dict(),
status_code=status.HTTP_200_OK) status_code=status.HTTP_200_OK)
# v1 # v1
......
...@@ -51,7 +51,7 @@ class NormalLogin: ...@@ -51,7 +51,7 @@ class NormalLogin:
logger.exception(e) logger.exception(e)
@staticmethod @staticmethod
def user_data_validation(username, project_id, password) -> dict | None: def user_data_validation(username, password) -> dict | None:
try: try:
# checking for valid username # checking for valid username
if username == "" or username == "user@example.com" or validate_email(username) is not True: if username == "" or username == "user@example.com" or validate_email(username) is not True:
...@@ -59,9 +59,6 @@ class NormalLogin: ...@@ -59,9 +59,6 @@ class NormalLogin:
# checking for valid password # checking for valid password
if password == "" or password == "string": if password == "" or password == "string":
return {"message": ErrorMessages.ERROR_INVALID_PASSWORD, "data": password} return {"message": ErrorMessages.ERROR_INVALID_PASSWORD, "data": password}
# check if the project id matches
if Services.PROJECT_ID != project_id:
return {"message": ErrorMessages.ERROR_INVALID_PROJECT_ID, "data": project_id}
return None return None
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(e)
...@@ -79,38 +76,34 @@ class NormalLogin: ...@@ -79,38 +76,34 @@ class NormalLogin:
if self.db_user_data["login_type"] != login_type: if self.db_user_data["login_type"] != login_type:
return False, {"message": ErrorMessages.ERROR_LOGIN_TYPE_INVALID, return False, {"message": ErrorMessages.ERROR_LOGIN_TYPE_INVALID,
"data": {"username": username, "Use Login": self.db_user_data["login_type"]}} "data": {"username": username, "Use Login": self.db_user_data["login_type"]}}
# Check the project id from the request body
if self.db_user_data["project_id"] != Services.PROJECT_ID:
return False, {"message": ErrorMessages.ERROR_UNAUTHORIZED_USER_LOGIN, "data": username}
# if the user exist # if the user exist
return None, {"message": True} return None, {"message": True}
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(e)
def db_password_matching(self, login_type, payload, password): def db_password_matching(self, login_type, user_data, password):
try: try:
# getting the response after checking for the user data in db # getting the response after checking for the user data in db
response, message = self.db_data_validation(login_type, payload["username"]) response, message = self.db_data_validation(login_type, user_data.username)
# if the response is false then an error message is send back # if the response is false then an error message is send back
if response is not None: if response is not None:
return response, message return response, message
# if the user exists in db then password is matched # if the user exists in db then password is matched
if not self.pwd_context.verify(password, self.db_user_data["password"]): if not self.pwd_context.verify(password, self.db_user_data["password"]):
return False, {"message": ErrorMessages.ERROR_PASSWORD_MISMATCH, return False, {"message": ErrorMessages.ERROR_PASSWORD_MISMATCH,
"data": {"username": payload["username"]}} "data": {"username": user_data.username}}
# if the password is correct # if the password is correct
return None, {"username": payload["username"], "role": self.db_user_data["user_role"]} return None, {"username": user_data.username, "role": self.db_user_data["user_role"]}
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(e)
@staticmethod @staticmethod
def generate_cookie_tokens(login_data, request): def generate_cookie_tokens(user_data, request):
try: try:
# creating the access token # creating the access token
access_token = create_token( access_token = create_token(
user_id=login_data["username"], user_id=user_data.username,
ip=request.ip_address, ip=request.ip_address
project_id=Services.PROJECT_ID,
) )
# returning the login token # returning the login token
if access_token: if access_token:
......
...@@ -6,7 +6,6 @@ class ErrorMessages: ...@@ -6,7 +6,6 @@ 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_INVALID_USERNAME = "Invalid Username" ERROR_INVALID_USERNAME = "Invalid Username"
ERROR_INVALID_PASSWORD = "Invalid Password" ERROR_INVALID_PASSWORD = "Invalid Password"
ERROR_INVALID_PROJECT_ID = "Invalid Project Id"
ERROR_UNAUTHORIZED_USER_LOGIN = "Account is not available" ERROR_UNAUTHORIZED_USER_LOGIN = "Account is not available"
ERROR_LOGIN_TYPE_INVALID = "Invalid Login Method" ERROR_LOGIN_TYPE_INVALID = "Invalid Login Method"
ERROR_USER_NOT_REGISTERED = "Account is not registered in the portal." ERROR_USER_NOT_REGISTERED = "Account is not registered in the portal."
......
...@@ -878,3 +878,17 @@ TypeError: cannot unpack non-iterable NoneType object ...@@ -878,3 +878,17 @@ TypeError: cannot unpack non-iterable NoneType object
2023-03-23 11:15:51 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671 2023-03-23 11:15:51 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:17:30 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671 2023-03-23 11:17:30 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:29:07 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671 2023-03-23 11:29:07 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:37:00 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:38:07 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:38:52 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:45:28 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:45:33 - ERROR - [MainThread:login_default(): 38] - 'LoginRequest' object is not subscriptable
Traceback (most recent call last):
File "E:\Git\meta-services\scripts\services\v1\iot_manager_services.py", line 31, in login_default
return login_mapper[login_type](user_data, request)
File "E:\Git\meta-services\scripts\core\handlers\login_handler.py", line 16, in normal_login
decrypted_password = self.obj_login_handler.password_decrypt(user_data["password"])
TypeError: 'LoginRequest' object is not subscriptable
2023-03-23 11:48:14 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:49:01 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-23 11:49:48 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
...@@ -7,7 +7,7 @@ from pydantic import BaseModel ...@@ -7,7 +7,7 @@ from pydantic import BaseModel
class DefaultResponse(BaseModel): class DefaultResponse(BaseModel):
status: bool = True status: bool = True
message: Optional[str] message: Optional[str]
payload: Optional[Any] data: Optional[Any]
# default failure responses # default failure responses
......
...@@ -5,6 +5,5 @@ from pydantic import BaseModel ...@@ -5,6 +5,5 @@ from pydantic import BaseModel
# model for login request # model for login request
class LoginRequest(BaseModel): class LoginRequest(BaseModel):
project_id: Union[str, None] = None username: Union[str, None] = None
payload: Union[dict, None] = None password: Union[str, None] = None
login_type: Union[str, None] = None
...@@ -14,7 +14,9 @@ obj_login_handler = LoginHandlers() ...@@ -14,7 +14,9 @@ obj_login_handler = LoginHandlers()
@router.post(ApiEndPoints.asset_manager_submit) @router.post(ApiEndPoints.asset_manager_submit)
async def login_default( async def login_default(
user_data: LoginRequest, request: MetaInfoSchema = Depends(auth) login_type: str,
user_data: LoginRequest,
request: MetaInfoSchema = Depends(auth)
): ):
try: try:
# mapper for login types # mapper for login types
...@@ -25,8 +27,8 @@ async def login_default( ...@@ -25,8 +27,8 @@ async def login_default(
} }
# getting the functions based on the login types # getting the functions based on the login types
if user_data.login_type in login_mapper: if login_type in login_mapper:
return login_mapper[user_data.login_type](user_data, request) return login_mapper[login_type](user_data, request)
else: else:
return HTTPException( return HTTPException(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
......
...@@ -13,15 +13,12 @@ def create_token( ...@@ -13,15 +13,12 @@ def create_token(
user_id, user_id,
ip, ip,
age=Secrets.ACCESS_TOKEN_EXPIRE_MINUTES, age=Secrets.ACCESS_TOKEN_EXPIRE_MINUTES,
project_id=None,
): ):
""" """
This method is to create a cookie This method is to create a cookie
""" """
# creating the payload # creating the payload
payload = {"ip": ip, "user_id": user_id, "token": Secrets.SECRET_KEY, "age": age} payload = {"ip": ip, "user_id": user_id, "token": Secrets.SECRET_KEY, "age": age}
if project_id:
payload["project_id"] = project_id
# getting the current time # getting the current time
current_time = datetime.now() current_time = datetime.now()
# generating the expiry time of the token # generating the expiry time of the token
......
...@@ -12,7 +12,6 @@ from scripts.utils.security.jwt_util import JWT ...@@ -12,7 +12,6 @@ from scripts.utils.security.jwt_util import JWT
class MetaInfoSchema(BaseModel): class MetaInfoSchema(BaseModel):
project_id: str = ""
user_id: str = "" user_id: str = ""
ip_address: str = "" ip_address: str = ""
login_type: str = "" login_type: str = ""
...@@ -57,7 +56,6 @@ class _CookieAuthentication(APIKeyBase): ...@@ -57,7 +56,6 @@ class _CookieAuthentication(APIKeyBase):
# if the cookie name is same as the service name # if the cookie name is same as the service name
if login_token == Services.PROJECT_NAME: if login_token == Services.PROJECT_NAME:
return MetaInfoSchema( return MetaInfoSchema(
project_id=Services.PROJECT_ID,
ip_address=request.client.host, # type: ignore ip_address=request.client.host, # type: ignore
login_token=cookies.get("login-token"), login_token=cookies.get("login-token"),
) )
...@@ -81,15 +79,13 @@ class _CookieAuthentication(APIKeyBase): ...@@ -81,15 +79,13 @@ class _CookieAuthentication(APIKeyBase):
# checking if the token has necessary fields # checking if the token has necessary fields
user_id = decoded_token.get("user_id") user_id = decoded_token.get("user_id")
project_id = decoded_token.get("project_id") if not user_id:
if not user_id or not project_id:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token doesn't have required fields", detail="Token doesn't have required fields",
) )
return MetaInfoSchema( return MetaInfoSchema(
project_id=project_id,
user_id=user_id, user_id=user_id,
ip_address=request.client.host, # type: ignore ip_address=request.client.host, # type: ignore
login_token=cookies.get("login-token"), login_token=cookies.get("login-token"),
......
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