Commit 8d15b8cc authored by arun.uday's avatar arun.uday

AssetManager-V1.0- To be reviewed

Added jwt token generation using bearer
parent 1a9a31b5
...@@ -7,7 +7,7 @@ SERVICE_PORT=8671 ...@@ -7,7 +7,7 @@ SERVICE_PORT=8671
PROJECT_NAME=AssetManager PROJECT_NAME=AssetManager
PROJECT_ID=1256 PROJECT_ID=1256
base_path=scripts/ BASE_PATH=scripts/
sub_path=log/ SUB_PATH=log/
ENCODING_TYPE=utf-8 ENCODING_TYPE=utf-8
\ No newline at end of file
...@@ -4,4 +4,7 @@ pydantic~=1.10.6 ...@@ -4,4 +4,7 @@ pydantic~=1.10.6
fastapi~=0.94.1 fastapi~=0.94.1
passlib~=1.7.4 passlib~=1.7.4
pymongo~=4.3.3 pymongo~=4.3.3
bcrypt~=4.0.1 bcrypt~=4.0.1
\ No newline at end of file email-validator~=1.3.1
pycryptodomex~=3.17
PyJWT~=2.6.0
\ No newline at end of file
from __future__ import annotations from __future__ import annotations
import base64 import base64
import datetime from datetime import datetime, timedelta
import jwt
from Cryptodome.Cipher import AES from Cryptodome.Cipher import AES
from passlib.context import CryptContext from passlib.context import CryptContext
...@@ -20,8 +21,8 @@ class LoginHandlers: ...@@ -20,8 +21,8 @@ class LoginHandlers:
self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
self.db_user_data = None self.db_user_data = None
self.db_user_data = None self.db_user_data = None
self.dt = datetime.datetime.now() self.dt = datetime.now()
self.time_dt = datetime.datetime.now() self.time_dt = datetime.now()
@staticmethod @staticmethod
def un_pad(s): def un_pad(s):
...@@ -115,3 +116,36 @@ class LoginHandlers: ...@@ -115,3 +116,36 @@ class LoginHandlers:
return None, {"username": login_data.username, "role": self.db_user_data["user_role"]} return None, {"username": login_data.username, "role": self.db_user_data["user_role"]}
except Exception as e: except Exception as e:
logger.exception(e) logger.exception(e)
@staticmethod
def create_access_token(data: dict, expires_delta):
try:
# creating a copy of the data
to_encode = data.copy()
# checking if the expires_delta is empty
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
# updating the data with the expiration time
to_encode.update({"expire": expire.isoformat()})
# creating the token
encoded_jwt = jwt.encode(to_encode, Services.SECRET_KEY, algorithm=Services.ALGORITHM)
return encoded_jwt
except Exception as e:
logger.exception(e)
def generate_tokens(self, login_data, data):
try:
# creating the expiration time
access_token_expires = timedelta(minutes=Services.ACCESS_TOKEN_EXPIRE_MINUTES)
# creating the access token
access_token = self.create_access_token(
data={"username": login_data.username, "role": data["role"]}, expires_delta=access_token_expires
)
if access_token:
return {"access_token": access_token, "token_type": "bearer"}
else:
return None
except Exception as e:
logger.exception(e)
...@@ -9,3 +9,4 @@ class ErrorMessages: ...@@ -9,3 +9,4 @@ class ErrorMessages:
ERROR_UNAUTHORIZED_USER_LOGIN = "Account is not available" ERROR_UNAUTHORIZED_USER_LOGIN = "Account is not available"
ERROR_USER_NOT_REGISTERED = "Account is not registered in the portal." ERROR_USER_NOT_REGISTERED = "Account is not registered in the portal."
ERROR_PASSWORD_MISMATCH = "Passwords Authentication Failed. Please enter the correct password" ERROR_PASSWORD_MISMATCH = "Passwords Authentication Failed. Please enter the correct password"
ERROR_TOKEN_GENERATION = "Unsuccessful token generation"
...@@ -25,3 +25,187 @@ TypeError: Object of type set is not JSON serializable ...@@ -25,3 +25,187 @@ TypeError: Object of type set is not JSON serializable
2023-03-20 15:09:21 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671 2023-03-20 15:09:21 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-20 15:09:36 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671 2023-03-20 15:09:36 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-20 15:10:17 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671 2023-03-20 15:10:17 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-21 10:33:43 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-21 10:33:43 - ERROR - [MainThread:<module>(): 41] - invalid syntax (jose.py, line 546)
Traceback (most recent call last):
File "E:\Git\meta-services\app.py", line 39, in <module>
uvicorn.run("main:app", host=arguments["bind"], port=int(arguments["port"]))
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\main.py", line 568, in run
server.run()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\server.py", line 59, in run
return asyncio.run(self.serve(sockets=sockets))
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\server.py", line 66, in serve
config.load()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\config.py", line 471, in load
self.loaded_app = import_from_string(self.app)
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "E:\Git\meta-services\main.py", line 17, in <module>
from scripts.services import router
File "E:\Git\meta-services\scripts\services\__init__.py", line 2, in <module>
from scripts.services import v1
File "E:\Git\meta-services\scripts\services\v1\__init__.py", line 3, in <module>
from scripts.services.v1 import iot_manager_services
File "E:\Git\meta-services\scripts\services\v1\iot_manager_services.py", line 5, in <module>
from scripts.core.handlers.login_handler import LoginHandlers
File "E:\Git\meta-services\scripts\core\handlers\login_handler.py", line 6, in <module>
from jose import jwt
File "E:\Git\meta-services\venv\lib\site-packages\jose.py", line 546
print decrypt(deserialize_compact(jwt), {'k':key},
^
SyntaxError: invalid syntax
2023-03-21 10:33:53 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-21 10:33:53 - ERROR - [MainThread:<module>(): 41] - invalid syntax (jose.py, line 546)
Traceback (most recent call last):
File "E:\Git\meta-services\app.py", line 39, in <module>
uvicorn.run("main:app", host=arguments["bind"], port=int(arguments["port"]))
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\main.py", line 568, in run
server.run()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\server.py", line 59, in run
return asyncio.run(self.serve(sockets=sockets))
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\server.py", line 66, in serve
config.load()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\config.py", line 471, in load
self.loaded_app = import_from_string(self.app)
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "E:\Git\meta-services\main.py", line 17, in <module>
from scripts.services import router
File "E:\Git\meta-services\scripts\services\__init__.py", line 2, in <module>
from scripts.services import v1
File "E:\Git\meta-services\scripts\services\v1\__init__.py", line 3, in <module>
from scripts.services.v1 import iot_manager_services
File "E:\Git\meta-services\scripts\services\v1\iot_manager_services.py", line 5, in <module>
from scripts.core.handlers.login_handler import LoginHandlers
File "E:\Git\meta-services\scripts\core\handlers\login_handler.py", line 6, in <module>
from jose import jwt
File "E:\Git\meta-services\venv\lib\site-packages\jose.py", line 546
print decrypt(deserialize_compact(jwt), {'k':key},
^
SyntaxError: invalid syntax
2023-03-21 10:35:00 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-21 10:35:01 - ERROR - [MainThread:<module>(): 41] - invalid syntax (jose.py, line 546)
Traceback (most recent call last):
File "E:\Git\meta-services\app.py", line 39, in <module>
uvicorn.run("main:app", host=arguments["bind"], port=int(arguments["port"]))
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\main.py", line 568, in run
server.run()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\server.py", line 59, in run
return asyncio.run(self.serve(sockets=sockets))
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\server.py", line 66, in serve
config.load()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\config.py", line 471, in load
self.loaded_app = import_from_string(self.app)
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "E:\Git\meta-services\main.py", line 17, in <module>
from scripts.services import router
File "E:\Git\meta-services\scripts\services\__init__.py", line 2, in <module>
from scripts.services import v1
File "E:\Git\meta-services\scripts\services\v1\__init__.py", line 3, in <module>
from scripts.services.v1 import iot_manager_services
File "E:\Git\meta-services\scripts\services\v1\iot_manager_services.py", line 5, in <module>
from scripts.core.handlers.login_handler import LoginHandlers
File "E:\Git\meta-services\scripts\core\handlers\login_handler.py", line 6, in <module>
from jose import jwt
File "E:\Git\meta-services\venv\lib\site-packages\jose.py", line 546
print decrypt(deserialize_compact(jwt), {'k':key},
^
SyntaxError: invalid syntax
2023-03-21 10:35:51 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-21 10:35:52 - ERROR - [MainThread:<module>(): 41] - type object 'datetime.datetime' has no attribute 'datetime'
Traceback (most recent call last):
File "E:\Git\meta-services\app.py", line 39, in <module>
uvicorn.run("main:app", host=arguments["bind"], port=int(arguments["port"]))
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\main.py", line 568, in run
server.run()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\server.py", line 59, in run
return asyncio.run(self.serve(sockets=sockets))
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\server.py", line 66, in serve
config.load()
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\config.py", line 471, in load
self.loaded_app = import_from_string(self.app)
File "E:\Git\meta-services\venv\lib\site-packages\uvicorn\importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "E:\Git\meta-services\main.py", line 17, in <module>
from scripts.services import router
File "E:\Git\meta-services\scripts\services\__init__.py", line 2, in <module>
from scripts.services import v1
File "E:\Git\meta-services\scripts\services\v1\__init__.py", line 3, in <module>
from scripts.services.v1 import iot_manager_services
File "E:\Git\meta-services\scripts\services\v1\iot_manager_services.py", line 14, in <module>
obj_login_handler = LoginHandlers()
File "E:\Git\meta-services\scripts\core\handlers\login_handler.py", line 24, in __init__
self.dt = datetime.datetime.now()
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
2023-03-21 10:36:26 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-21 10:37:03 - ERROR - [AnyIO worker thread:login_default(): 44] - Object of type datetime is not JSON serializable
Traceback (most recent call last):
File "E:\Git\meta-services\scripts\services\v1\iot_manager_services.py", line 37, in login_default
response = obj_login_handler.generate_tokens(login_data, data)
File "E:\Git\meta-services\scripts\core\handlers\login_handler.py", line 133, in generate_tokens
access_token = self.create_access_token(
File "E:\Git\meta-services\scripts\core\handlers\login_handler.py", line 128, in create_access_token
encoded_jwt = jwt.encode(to_encode, Services.SECRET_KEY, algorithm=Services.ALGORITHM)
File "E:\Git\meta-services\venv\lib\site-packages\jwt\api_jwt.py", line 63, in encode
json_payload = json.dumps(
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\arun.uday\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable
2023-03-21 10:40:09 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-21 10:40:46 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
2023-03-21 10:46:22 - INFO - [MainThread:<module>(): 37] - App Starting at 0.0.0.0:8671
...@@ -15,7 +15,7 @@ obj_login_handler = LoginHandlers() ...@@ -15,7 +15,7 @@ obj_login_handler = LoginHandlers()
@router.post(ApiEndPoints.asset_manager_submit) @router.post(ApiEndPoints.asset_manager_submit)
def login_default(login_data: NormalLogin): async def login_default(login_data: NormalLogin):
try: try:
# decrypting the password from the UI # decrypting the password from the UI
decrypted_password = obj_login_handler.password_decrypt(login_data.password) decrypted_password = obj_login_handler.password_decrypt(login_data.password)
...@@ -27,16 +27,25 @@ def login_default(login_data: NormalLogin): ...@@ -27,16 +27,25 @@ def login_default(login_data: NormalLogin):
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 = obj_login_handler.db_password_matching(login_data, decrypted_password) response, data = obj_login_handler.db_password_matching(login_data, decrypted_password)
# if the user is not valid
if response is not None and data["message"] == ErrorMessages.ERROR_UNAUTHORIZED_USER_LOGIN: if response is not None and data["message"] == ErrorMessages.ERROR_UNAUTHORIZED_USER_LOGIN:
return JSONResponse(content=DefaultFailureResponse(error=data).dict(), return JSONResponse(content=DefaultFailureResponse(error=data).dict(),
status_code=status.HTTP_404_NOT_FOUND) status_code=status.HTTP_404_NOT_FOUND)
# if the passwords doesn't match with the db data
if response is not None: if response is not None:
return JSONResponse(content=DefaultFailureResponse(error=data).dict(), return JSONResponse(content=DefaultFailureResponse(error=data).dict(),
status_code=status.HTTP_401_UNAUTHORIZED) status_code=status.HTTP_401_UNAUTHORIZED)
# generating the access tokens
response = obj_login_handler.generate_tokens(login_data, data)
# token generation unsuccessful
if response is None:
return JSONResponse(
content=DefaultFailureResponse(message="Access Unsuccessful",
error=ErrorMessages.ERROR_TOKEN_GENERATION).dict(),
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=data).dict(), content=DefaultResponse(message="Login Successful", payload=response).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(e)
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