auth service up running
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user