Exemple #1
0
    def get_or_post(uri,
                    method,
                    req,
                    content_type=DEFAULT_POST_CONTENT_TYPE,
                    accept=None,
                    **kwargs):
        if method == "GET":
            _qp = req.to_urlencoded()
            if _qp:
                path = uri + '?' + _qp
            else:
                path = uri
            body = None
        elif method == "POST":
            path = uri
            if content_type == URL_ENCODED:
                body = req.to_urlencoded()
            elif content_type == JSON_ENCODED:
                body = req.to_json()
            else:
                raise UnSupported("Unsupported content type: '%s'" %
                                  content_type)

            header_ext = {"Content-type": content_type}
            if accept:
                header_ext = {"Accept": accept}

            if "headers" in kwargs.keys():
                kwargs["headers"].update(header_ext)
            else:
                kwargs["headers"] = header_ext
        else:
            raise UnSupported("Unsupported HTTP method: '%s'" % method)

        return path, body, kwargs
Exemple #2
0
def get_or_post(uri,
                method,
                req,
                content_type=DEFAULT_POST_CONTENT_TYPE,
                accept=None,
                **kwargs):
    """
    Construct HTTP request.

    :param uri:
    :param method:
    :param req:
    :param content_type:
    :param accept:
    :param kwargs:
    :return:
    """
    if method in ["GET", "DELETE"]:
        if req.keys():
            _req = req.copy()
            comp = urlsplit(str(uri))
            if comp.query:
                _req.update(parse_qs(comp.query))

            _query = str(_req.to_urlencoded())
            path = urlunsplit(
                (comp.scheme, comp.netloc, comp.path, _query, comp.fragment))
        else:
            path = uri
        body = None
    elif method in ["POST", "PUT"]:
        path = uri
        if content_type == URL_ENCODED:
            body = req.to_urlencoded()
        elif content_type == JSON_ENCODED:
            body = req.to_json()
        else:
            raise UnSupported("Unsupported content type: '%s'" % content_type)

        header_ext = {"Content-Type": content_type}
        if accept:
            header_ext = {"Accept": accept}

        if "headers" in kwargs.keys():
            kwargs["headers"].update(header_ext)
        else:
            kwargs["headers"] = header_ext
    else:
        raise UnSupported("Unsupported HTTP method: '%s'" % method)

    return path, body, kwargs
Exemple #3
0
    def token_endpoint(self, authn="", **kwargs):
        """
        This is where clients come to get their access tokens
        """

        logger.debug("- token -")
        body = kwargs["request"]
        logger.debug("body: %s" % body)

        areq = AccessTokenRequest().deserialize(body, "urlencoded")

        try:
            self.client_authn(self, areq, authn)
        except FailedAuthentication as err:
            logger.error(err)
            err = TokenErrorResponse(error="unauthorized_client",
                                     error_description="%s" % err)
            return Response(err.to_json(),
                            content="application/json",
                            status_code=401)

        logger.debug("AccessTokenRequest: %s" % areq)

        _grant_type = areq["grant_type"]
        if _grant_type == "authorization_code":
            return self.code_grant_type(areq)
        elif _grant_type == 'client_credentials':
            return self.client_credentials_grant_type(areq)
        elif _grant_type == 'password':
            return self.password_grant_type(areq)
        elif _grant_type == 'refresh_token':
            return self.refresh_token_grant_type(areq)
        else:
            raise UnSupported('grant_type: {}'.format(_grant_type))
Exemple #4
0
    def verify_client(self, environ, areq, authn_method, client_id=""):
        """
        Verify the client based on credentials.

        :param environ: WSGI environ
        :param areq: The request
        :param authn_method: client authentication method
        :return:
        """
        if not client_id:
            client_id = get_client_id(self.cdb, areq, environ["HTTP_AUTHORIZATION"])

        try:
            method = self.client_authn_methods[authn_method]
        except KeyError:
            raise UnSupported()
        return method(self).verify(environ, client_id=client_id)
Exemple #5
0
    def token_endpoint(self,
                       request="",
                       authn="",
                       dtype="urlencoded",
                       **kwargs):
        """
        Provide clients with access tokens.

        :param authn: Auhentication info, comes from HTTP header.
        :param request: The request.
        :param dtype: deserialization method for the request.
        """
        logger.debug("- token -")
        logger.debug("token_request: %s" % sanitize(request))

        areq = self.server.message_factory.get_request_type(
            "token_endpoint")().deserialize(request, dtype)

        # Verify client authentication
        try:
            client_id = self.client_authn(self, areq, authn)
        except (FailedAuthentication, AuthnFailure) as err:
            logger.error(err)
            error = TokenErrorResponse(error="unauthorized_client",
                                       error_description="%s" % err)
            return Unauthorized(error.to_json(), content="application/json")

        logger.debug("AccessTokenRequest: %s" % sanitize(areq))

        # `code` is not mandatory for all requests
        if "code" in areq:
            try:
                _info = self.sdb[areq["code"]]
            except KeyError:
                logger.error("Code not present in SessionDB")
                error = TokenErrorResponse(error="unauthorized_client",
                                           error_description="Invalid code.")
                return Unauthorized(error.to_json(),
                                    content="application/json")

            resp = self.token_scope_check(areq, _info)
            if resp:
                return resp
            # If redirect_uri was in the initial authorization request verify that they match
            if ("redirect_uri" in _info
                    and areq["redirect_uri"] != _info["redirect_uri"]):
                logger.error("Redirect_uri mismatch")
                error = TokenErrorResponse(
                    error="unauthorized_client",
                    error_description="Redirect_uris do not match.",
                )
                return Unauthorized(error.to_json(),
                                    content="application/json")
            if "state" in areq:
                if _info["state"] != areq["state"]:
                    logger.error("State value mismatch")
                    error = TokenErrorResponse(
                        error="unauthorized_client",
                        error_description="State values do not match.",
                    )
                    return Unauthorized(error.to_json(),
                                        content="application/json")

        # Propagate the client_id further
        areq.setdefault("client_id", client_id)
        grant_type = areq["grant_type"]
        if grant_type == "authorization_code":
            return self.code_grant_type(areq)
        elif grant_type == "refresh_token":
            return self.refresh_token_grant_type(areq)
        elif grant_type == "client_credentials":
            return self.client_credentials_grant_type(areq)
        elif grant_type == "password":
            return self.password_grant_type(areq)
        else:
            raise UnSupported("grant_type: {}".format(grant_type))