Generate the before_request function to be added to the app.

        Currently this function is static, however it is very likely we will
        need to programmatically generate this function in the future.

def _make_before_request(self):
        """
        Generate the before_request function to be added to the app.

        Currently this function is static, however it is very likely we will
        need to programmatically generate this function in the future.
        """
        def before_request():
            """
            Process invalid identity statuses and attach user to request.

            :raises: :exception:`exceptions.FlaskKeystoneUnauthorized`

            This function guarantees that a bad token will return a 401
            when :mod:`keystonemiddleware` is configured to
            defer_auth_decision. Once this is done, it instantiates a user
            from the generated User model and attaches it to the request
            context for later access.
            """
            identity_status = request.headers.get(
                "X-Identity-Status", "Invalid"
            )
            if identity_status != "Confirmed":
                msg = ("Couldn't authenticate user '%s' with "
                       "X-Identity-Status '%s'")
                self.logger.info(msg % (
                    request.headers.get("X-User-Id", "None"),
                    request.headers.get("X-Identity-Status", "None")
                ))
                if not self.config.allow_anonymous_access:
                    msg = "Anonymous Access disabled, rejecting %s"
                    self.logger.debug(
                        msg % request.headers.get("X-User-Id", "None")
                    )
                    raise FlaskKeystoneUnauthorized()
                else:
                    self.logger.debug("Setting Anonymous user.")
                    self._set_anonymous_user()
                    return

            self._set_user(request)

        return before_request