implement some auth for MeshUIConsumer

This commit is contained in:
Laura Klünder 2023-11-09 17:04:55 +01:00
parent 88d6f07eaf
commit 394450f4a3
4 changed files with 30 additions and 9 deletions

View file

@ -1,8 +1,15 @@
from django.utils.functional import SimpleLazyObject, lazy
from channels.db import database_sync_to_async
from channels.middleware import BaseMiddleware as BaseChannelsMiddleware
from django.utils.functional import LazyObject, SimpleLazyObject, lazy
from c3nav.control.models import UserPermissions, UserSpaceAccess
class UserPermissionsLazyObject(LazyObject):
def _setup(self):
raise ValueError("Accessing scope user before it is ready.")
class UserPermissionsMiddleware:
"""
This middleware adds request.user_permissions to get the UserPermissions for the current request/user.
@ -32,3 +39,12 @@ class UserPermissionsMiddleware:
request.user_permissions = SimpleLazyObject(lambda: self.get_user_permissions(request))
request.user_space_accesses = lazy(self.get_user_space_accesses, dict)(request)
return self.get_response(request)
class UserPermissionsChannelMiddleware(BaseChannelsMiddleware):
async def __call__(self, scope, receive, send):
# todo: this doesn't seem to actually be lazy. and scope["user"] isn't either?
scope["user_permissions"] = UserPermissionsLazyObject()
scope["user_permissions"]._wrapped = await database_sync_to_async(UserPermissions.get_for_user)(scope["user"])
return await super().__call__(scope, receive, send)

View file

@ -1,5 +1,5 @@
from contextlib import contextmanager
from typing import Dict
from typing import Dict, Self
from django.conf import settings
from django.contrib.auth.models import User
@ -73,7 +73,7 @@ class UserPermissions(models.Model):
yield
@classmethod
def get_for_user(cls, user, force=False) -> 'UserPermissions':
def get_for_user(cls, user, force=False) -> Self:
if not user.is_authenticated:
return cls()
cache_key = cls.get_cache_key(user.pk)