Changeset View
Changeset View
Standalone View
Standalone View
swh/deposit/auth.py
Show First 20 Lines • Show All 116 Lines • ▼ Show 20 Lines | class KeycloakBasicAuthentication(BasicAuthentication): | ||||
@property | @property | ||||
def client(self): | def client(self): | ||||
if self._client is None: | if self._client is None: | ||||
self._client = KeycloakOpenIDConnect.from_configfile( | self._client = KeycloakOpenIDConnect.from_configfile( | ||||
client_id=OIDC_DEPOSIT_CLIENT_ID | client_id=OIDC_DEPOSIT_CLIENT_ID | ||||
) | ) | ||||
return self._client | return self._client | ||||
def _cache_key(self, user_id: str) -> str: | |||||
"""Internal key to use to store user id token. | |||||
""" | |||||
return f"oidc_user_{self.client.realm_name}_{self.client.client_id}_{user_id}" | |||||
def get_user(self, user_id: str) -> Optional[OIDCUser]: | def get_user(self, user_id: str) -> Optional[OIDCUser]: | ||||
"""Retrieve user from cache if any. | """Retrieve user from cache if any. | ||||
""" | """ | ||||
oidc_profile = cache.get(f"oidc_user_{user_id}") | oidc_profile = cache.get(self._cache_key(user_id)) | ||||
if oidc_profile: | if oidc_profile: | ||||
try: | try: | ||||
return oidc_user_from_profile(self.client, oidc_profile) | return oidc_user_from_profile(self.client, oidc_profile) | ||||
except Exception as e: | except Exception as e: | ||||
logger.warning("Error during cache token retrieval: %s", e) | logger.warning("Error during cache token retrieval: %s", e) | ||||
capture_exception(e) | capture_exception(e) | ||||
return None | return None | ||||
Show All 31 Lines | def authenticate_credentials(self, user_id, password, request): | ||||
if not deposit_client.is_active: | if not deposit_client.is_active: | ||||
raise AuthenticationFailed(f"Deactivated user {user_id}") | raise AuthenticationFailed(f"Deactivated user {user_id}") | ||||
deposit_client.oidc_user = oidc_user | deposit_client.oidc_user = oidc_user | ||||
if ttl: | if ttl: | ||||
# cache the oidc_profile user while it's valid | # cache the oidc_profile user while it's valid | ||||
cache.set( | cache.set( | ||||
f"oidc_user_{user_id}", oidc_profile, timeout=max(0, ttl), | self._cache_key(user_id), oidc_profile, timeout=max(0, ttl), | ||||
) | ) | ||||
return (deposit_client, None) | return (deposit_client, None) |