Skip to content

Commit

Permalink
Adds cache to OIDC Authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
elitonzky committed Dec 7, 2023
1 parent 7e62979 commit 9abe387
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
24 changes: 24 additions & 0 deletions marketplace/accounts/backends.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
import json

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import get_user_model
from django_redis import get_redis_connection
from django.conf import settings

from mozilla_django_oidc.auth import OIDCAuthenticationBackend


User = get_user_model()


class WeniOIDCAuthenticationBackend(OIDCAuthenticationBackend): # pragma: no cover
cache_token = settings.OIDC_CACHE_TOKEN
cache_ttl = settings.OIDC_CACHE_TTL

def get_userinfo(self, access_token, *args):
if not self.cache_token:
return super().get_userinfo(access_token, *args)

redis_connection = get_redis_connection()
userinfo = redis_connection.get(access_token)

if userinfo is not None:
return json.loads(userinfo)

userinfo = super().get_userinfo(access_token, *args)
redis_connection.set(access_token, json.dumps(userinfo), self.cache_ttl)

return userinfo

def check_module_permission(self, claims, user) -> None:
if claims.get("can_communicate_internally", False):
content_type = ContentType.objects.get_for_model(User)
Expand Down
6 changes: 6 additions & 0 deletions marketplace/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,12 @@
)
OIDC_RP_SCOPES = env.str("OIDC_RP_SCOPES", default="openid email")

OIDC_CACHE_TOKEN = env.bool(
"OIDC_CACHE_TOKEN", default=False
) # Enable/disable user token caching (default: False).
OIDC_CACHE_TTL = env.int(
"OIDC_CACHE_TTL", default=600
) # Time-to-live for cached user tokens (default: 600 seconds).

# django-cors-headers Configurations

Expand Down

0 comments on commit 9abe387

Please sign in to comment.