Example #1
0
File: admin.py Project: ihyf/blog
async def inject_user(request: Request) -> None:
    with instant_config(bp, request=request):
        payload = bp.auth.extract_payload(request, verify=False)
        user = await jwt_call(
            bp.auth.retrieve_user, request, payload
        )
        if user:
            request.user = user
        async def decorated_function(request, *args, **kwargs):
            if initialized_on and isinstance(initialized_on, Blueprint):
                instance = initialized_on
            else:
                instance = request.app

            with instant_config(instance, request=request, **kw):
                user = await _get_user_from_request(
                    instance, request, allow_api_token, extract_user_from_jwt
                )
                return await f(request, user=user, *args, **kwargs)
async def user_from_request(request: Request) -> Optional[Dict[Text, Any]]:
    """Extract a Rasa X user from a request.

    Args:
        request: The HTTP request.

    Returns:
        The user. Might be `None` in case the endpoint does not require authentication.
    """
    with instant_config(request.app, request=request):
        return await _get_user_from_request(request.app, request)
        async def decorated_function(request, *args, **kwargs):
            user_service = UserService(request[REQUEST_DB_SESSION_KEY])

            if initialized_on and isinstance(initialized_on, Blueprint):
                instance = initialized_on
            else:
                instance = request.app

            with instant_config(instance, request=request, **kw):
                if request.method == "OPTIONS":
                    return await sanic_jwt_utils.call(f, request, *args, **kwargs)

                is_authenticated = False
                user_scopes = None
                reasons = None
                status = None

                if allow_rasa_x_token:
                    rasa_x_token = default_arg(request, "token", None)
                    if rasa_x_token == config.rasa_x_token:
                        return await await_and_return_response(args, kwargs, request)

                if allow_api_token:
                    # if decorator allows api_tokens for authentication
                    # skip the usual JWT authentication
                    api_token = default_arg(request, "api_token")
                    if api_token:
                        user = user_service.api_token_auth(api_token)
                        is_authenticated = True
                        status = 200
                        permissions = user["permissions"]
                        user_scopes = normalise_permissions(permissions)

                if not is_authenticated:
                    try:
                        (
                            is_authenticated,
                            status,
                            reasons,
                        ) = instance.auth._check_authentication(
                            request, request_args=args, request_kwargs=kwargs
                        )
                    except AttributeError:
                        raise exceptions.SanicJWTException(
                            "Authentication instance not found. Perhaps you "
                            "used @scoped without passing in a blueprint? "
                            "Try @scoped(..., initialized_on=blueprint)",
                            status_code=500,
                        )
                    except exceptions.SanicJWTException as e:
                        status = e.status_code
                        reasons = e.args[0]

                if is_authenticated:
                    is_authorized, reasons, status = await authorise_user(
                        args, kwargs, instance, reasons, request, status, user_scopes
                    )
                else:
                    is_authorized = False

                if is_authorized:
                    # the user is authorized.
                    # run the handler method and return the response
                    # NOTE: it's possible to use return await.utils(f, ...) in
                    # here, but inside the @protected decorator it wont work,
                    # so this is left as is for now
                    return await await_and_return_response(args, kwargs, request)

                else:
                    raise exceptions.Unauthorized(reasons, status_code=status)