def TokenAuthMiddlewareStack(inner):
    return CookieMiddleware(SessionMiddleware(TokenAuthMiddleware(inner)))
Beispiel #2
0
                try:
                    tenant = domain.tenant
                    schema_name = tenant.schema_name
                except domain_model.DoesNotExist:
                    raise Http404('No tenant for hostname "%s"' % hostname)
                break
        else:
            raise ValueError(
                "The headers key in the scope is invalid. " +
                "(make sure it is passed valid HTTP or WebSocket connections)")
        return self.inner(
            dict(scope, schema_name=schema_name, multitenant=True))


# MiddlewareStack to give access to user object in a multitenant environment
ChatterMTMiddlewareStack = lambda inner: CookieMiddleware(
    SessionMiddleware(MTSchemaMiddleware(MTAuthMiddleware(inner))))


# Takes in a list of User objects and returns the UUID of the room created.
def create_room(user_list):
    for user in user_list:
        if type(user) != get_user_model():
            raise TypeError(
                "Parameters passed to create_room doesn't "
                "match your project's user model. Please make sure the list "
                "you passed contains valid User objects as defined in your "
                "settings.AUTH_USER_MODEL parameter.")
    rooms_with_member_count = Room.objects.annotate(
        num_members=Count('members'))
    rooms = rooms_with_member_count.filter(num_members=len(user_list))
Beispiel #3
0
class UserLazyObject(LazyObject):
    """
    Throw a more useful error message when scope['user'] is accessed before it's resolved
    """
    def _setup(self):
        raise ValueError("Accessing scope user before it is ready.")


class AuthMiddleware(BaseMiddleware):
    """
    Middleware which populates scope["user"] from a Django session.
    Requires SessionMiddleware to function.
    """
    def populate_scope(self, scope: Scope) -> None:
        # Make sure we have a session
        if "session" not in scope:
            raise ValueError(
                "AuthMiddleware cannot find session in scope. SessionMiddleware must be above it."
            )
        # Add it to the scope if it's not there already
        if "user" not in scope:
            scope["user"] = UserLazyObject()

    async def resolve_scope(self, scope: Scope) -> None:
        scope["user"]._wrapped = await get_user(scope)


# Handy shortcut for applying all three layers at once
AuthMiddlewareStack = lambda inner: CookieMiddleware(
    SessionMiddleware(AuthMiddleware(inner)))
Beispiel #4
0
from rest_framework.exceptions import AuthenticationFailed
import logging
logger = logging.getLogger(__name__)


class TokenAuthMiddleware:
    """
    Token authorization middleware for Django Channels 2
    """
    def __init__(self, inner):
        self.inner = inner

    def __call__(self, scope):
        cookies = dict(scope['cookies'])
        if 'token' in cookies:
            try:
                tokenString = cookies['token']
                knoxAuth = TokenAuthentication()
                user, auth_token = knoxAuth.authenticate_credentials(
                    tokenString.encode("utf-8"))
                scope['user'] = user
            except AuthenticationFailed:
                logger.error("authentication failed!")
                scope['user'] = AnonymousUser()
        else:
            scope['user'] = AnonymousUser()
        return self.inner(scope)


TokenAuthMiddlewareStack = lambda inner: CookieMiddleware(
    TokenAuthMiddleware(AuthMiddlewareStack(inner)))
def AuthorizationProcessorBasedMiddlewareStack(inner):
    """ Handy shortcut for applying all three layers at once """
    from channels.sessions import CookieMiddleware, SessionMiddleware

    return CookieMiddleware(
        SessionMiddleware(AuthorizationProcessorBasedMiddleware(inner)))
Beispiel #6
0
def JWTAuthMiddlewareStack(inner):
    return CookieMiddleware(JWTAuthMiddleware(inner))