auth service up running
This commit is contained in:
@@ -8,4 +8,4 @@ from .templates.password_templates import (
|
||||
change_your_password_template,
|
||||
)
|
||||
|
||||
update_selected_to_redis = RedisActions.set_json
|
||||
update_selected_to_redis = RedisActions.set_json
|
||||
|
||||
@@ -70,7 +70,9 @@ class RedisActions:
|
||||
already_tokens = redis_cli.scan_iter(match=str(value_regex))
|
||||
already_tokens_list = {}
|
||||
for already_token in already_tokens:
|
||||
already_tokens_list[already_token.decode()] = json.loads(redis_cli.get(already_token))
|
||||
already_tokens_list[already_token.decode()] = json.loads(
|
||||
redis_cli.get(already_token)
|
||||
)
|
||||
return RedisResponse(
|
||||
status=True,
|
||||
message="Values are listed successfully.",
|
||||
@@ -187,21 +189,22 @@ class RedisActions:
|
||||
try:
|
||||
search_name = str(name) if isinstance(name, str) else name.decode()
|
||||
expiry_time = system_arrow.get_expiry_time(**expiry_kwargs)
|
||||
seconds_until_expiry = int(expiry_time.timestamp() - system_arrow.now().timestamp())
|
||||
|
||||
seconds_until_expiry = int(
|
||||
expiry_time.timestamp() - system_arrow.now().timestamp()
|
||||
)
|
||||
|
||||
redis_cli.setex(
|
||||
name=search_name,
|
||||
time=seconds_until_expiry,
|
||||
value=json.dumps({
|
||||
'value': value,
|
||||
'expires_at': expiry_time.timestamp()
|
||||
})
|
||||
value=json.dumps(
|
||||
{"value": value, "expires_at": expiry_time.timestamp()}
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
return RedisResponse(
|
||||
status=True,
|
||||
message="Value is set successfully with expiry.",
|
||||
data={'value': value, 'expires_at': expiry_time.timestamp()},
|
||||
data={"value": value, "expires_at": expiry_time.timestamp()},
|
||||
)
|
||||
except Exception as e:
|
||||
return RedisResponse(
|
||||
@@ -216,25 +219,25 @@ class RedisActions:
|
||||
try:
|
||||
search_name = str(name) if isinstance(name, str) else name.decode()
|
||||
result = redis_cli.get(name=search_name)
|
||||
|
||||
|
||||
if not result:
|
||||
return RedisResponse(
|
||||
status=False,
|
||||
message="Key not found.",
|
||||
)
|
||||
|
||||
|
||||
data = json.loads(result)
|
||||
if system_arrow.is_expired(data.get('expires_at')):
|
||||
if system_arrow.is_expired(data.get("expires_at")):
|
||||
redis_cli.delete(search_name)
|
||||
return RedisResponse(
|
||||
status=False,
|
||||
message="Cache expired.",
|
||||
)
|
||||
|
||||
|
||||
return RedisResponse(
|
||||
status=True,
|
||||
message="Value retrieved successfully.",
|
||||
data=data['value'],
|
||||
data=data["value"],
|
||||
)
|
||||
except Exception as e:
|
||||
return RedisResponse(
|
||||
@@ -272,24 +275,22 @@ class RedisActions:
|
||||
try:
|
||||
key = f"{access_token}:{model_object.user_uu_id}"
|
||||
expiry_time = system_arrow.get_expiry_time(minutes=expiry_minutes)
|
||||
seconds_until_expiry = max(1, int(expiry_time.timestamp() - system_arrow.now().timestamp()))
|
||||
|
||||
seconds_until_expiry = max(
|
||||
1, int(expiry_time.timestamp() - system_arrow.now().timestamp())
|
||||
)
|
||||
|
||||
# Add expiry time to the model data
|
||||
model_data = json.loads(model_object.model_dump_json())
|
||||
model_data['expires_at'] = expiry_time.timestamp()
|
||||
|
||||
model_data["expires_at"] = expiry_time.timestamp()
|
||||
|
||||
if redis_cli.setex(
|
||||
name=key,
|
||||
time=seconds_until_expiry,
|
||||
value=json.dumps(model_data)
|
||||
name=key, time=seconds_until_expiry, value=json.dumps(model_data)
|
||||
):
|
||||
return access_token
|
||||
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(
|
||||
f"Failed to save object to Redis. Error: {str(e)}"
|
||||
)
|
||||
|
||||
raise Exception(f"Failed to save object to Redis. Error: {str(e)}")
|
||||
|
||||
raise Exception("Failed to save token to Redis")
|
||||
|
||||
@classmethod
|
||||
@@ -304,21 +305,21 @@ class RedisActions:
|
||||
"""
|
||||
from api_configs.configs import Auth
|
||||
from api_library.date_time_actions.date_functions import system_arrow
|
||||
|
||||
|
||||
if not hasattr(request, "headers"):
|
||||
raise Exception("Headers not found in request")
|
||||
|
||||
|
||||
access_token = request.headers.get(Auth.ACCESS_TOKEN_TAG)
|
||||
if not access_token:
|
||||
raise Exception("Unauthorized user, please login")
|
||||
|
||||
|
||||
# Scan for matching tokens
|
||||
token_pattern = f"{access_token}:*"
|
||||
matching_tokens = list(redis_cli.scan_iter(match=token_pattern))
|
||||
|
||||
|
||||
if not matching_tokens:
|
||||
raise Exception("Invalid credentials. Please login again")
|
||||
|
||||
|
||||
try:
|
||||
# Check if token has expired in Redis
|
||||
token_key = matching_tokens[0]
|
||||
@@ -326,23 +327,23 @@ class RedisActions:
|
||||
if ttl <= 0:
|
||||
redis_cli.delete(token_key)
|
||||
raise Exception("Token expired. Please login again")
|
||||
|
||||
|
||||
# Get the token data
|
||||
token_data = json.loads(redis_cli.get(token_key) or '{}')
|
||||
|
||||
token_data = json.loads(redis_cli.get(token_key) or "{}")
|
||||
|
||||
# Return appropriate token object based on user type
|
||||
if token_data.get("user_type") == 1: # Employee
|
||||
if not token_data.get("selected_company"):
|
||||
token_data["selected_company"] = None
|
||||
return EmployeeTokenObject(**token_data)
|
||||
|
||||
|
||||
elif token_data.get("user_type") == 2: # Occupant
|
||||
if not token_data.get("selected_occupant"):
|
||||
token_data["selected_occupant"] = None
|
||||
return OccupantTokenObject(**token_data)
|
||||
|
||||
|
||||
raise Exception("Invalid user type in token")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"Failed to retrieve token: {str(e)}")
|
||||
|
||||
@@ -356,24 +357,28 @@ class RedisActions:
|
||||
"""
|
||||
token_pattern = f"*:{str(user_id)}"
|
||||
matching_tokens = redis_cli.scan_iter(match=token_pattern)
|
||||
|
||||
|
||||
tokens_dict = {}
|
||||
for token_key in matching_tokens:
|
||||
token_data = json.loads(redis_cli.get(token_key) or '{}')
|
||||
|
||||
token_data = json.loads(redis_cli.get(token_key) or "{}")
|
||||
|
||||
# Skip expired tokens and clean them up
|
||||
if system_arrow.is_expired(token_data.get('expires_at')):
|
||||
if system_arrow.is_expired(token_data.get("expires_at")):
|
||||
redis_cli.delete(token_key)
|
||||
continue
|
||||
|
||||
|
||||
tokens_dict[token_key.decode()] = token_data
|
||||
|
||||
|
||||
return tokens_dict
|
||||
|
||||
|
||||
class RedisResponse:
|
||||
def __init__(
|
||||
self, status: bool, message: str, data: typing.Union[dict | list] = None, error: str = None
|
||||
self,
|
||||
status: bool,
|
||||
message: str,
|
||||
data: typing.Union[dict | list] = None,
|
||||
error: str = None,
|
||||
):
|
||||
self.status = status
|
||||
self.message = message
|
||||
|
||||
@@ -8,16 +8,18 @@ from api_configs import Auth
|
||||
from databases import Users, UsersTokens
|
||||
from api_library.date_time_actions.date_functions import system_arrow
|
||||
|
||||
|
||||
class TokenService:
|
||||
@staticmethod
|
||||
def validate_token(request: Request) -> Union[OccupantTokenObject, EmployeeTokenObject]:
|
||||
def validate_token(
|
||||
request: Request,
|
||||
) -> Union[OccupantTokenObject, EmployeeTokenObject]:
|
||||
"""Validate and return token object from request"""
|
||||
try:
|
||||
return RedisActions.get_object_via_access_key(request)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail={"message": str(e)}
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail={"message": str(e)}
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -26,12 +28,12 @@ class TokenService:
|
||||
return RedisActions.get_object_via_user_uu_id(user_id)
|
||||
|
||||
@staticmethod
|
||||
def validate_refresh_token(domain: str, refresh_token: str) -> Optional[UsersTokens]:
|
||||
def validate_refresh_token(
|
||||
domain: str, refresh_token: str
|
||||
) -> Optional[UsersTokens]:
|
||||
"""Validate refresh token and return token object"""
|
||||
return UsersTokens.filter_by_one(
|
||||
token=refresh_token,
|
||||
domain=domain,
|
||||
**UsersTokens.valid_record_dict
|
||||
token=refresh_token, domain=domain, **UsersTokens.valid_record_dict
|
||||
).data
|
||||
|
||||
@staticmethod
|
||||
@@ -39,10 +41,9 @@ class TokenService:
|
||||
"""Update user metadata from request"""
|
||||
user.last_agent = request.headers.get("User-Agent")
|
||||
user.last_platform = request.headers.get("Origin")
|
||||
user.last_remote_addr = (
|
||||
getattr(request, "remote_addr", None) or
|
||||
request.headers.get("X-Forwarded-For")
|
||||
)
|
||||
user.last_remote_addr = getattr(
|
||||
request, "remote_addr", None
|
||||
) or request.headers.get("X-Forwarded-For")
|
||||
user.last_seen = str(system_arrow.now())
|
||||
user.save()
|
||||
|
||||
@@ -64,12 +65,12 @@ class TokenService:
|
||||
user = Users.filter_one(Users.password_token == token).data
|
||||
if not user:
|
||||
return None
|
||||
|
||||
|
||||
# Check if token is expired
|
||||
token_valid_until = system_arrow.get(str(user.password_token_is_valid))
|
||||
if system_arrow.now() > token_valid_until:
|
||||
user.password_token = ""
|
||||
user.save()
|
||||
return None
|
||||
|
||||
|
||||
return user
|
||||
|
||||
Reference in New Issue
Block a user