Beispiel #1
0
    def validate_authorization_request(self):
        """Validate authorization request

        :return: None
        """
        # Validate client for this request
        client_id = self.request.client_id
        self.server.log.debug("Validate authorization request of", client_id)
        if client_id is None:
            raise InvalidClientError(state=self.request.state)
        client = self.server.query_client(client_id)
        if not client:
            raise InvalidClientError(state=self.request.state)
        response_type = self.request.response_type
        if not client.check_response_type(response_type):
            raise UnauthorizedClientError(
                'The client is not authorized to use "response_type={}"'.
                format(response_type))
        self.request.client = client
        self.validate_requested_scope()

        # Check user_code, when user go to authorization endpoint
        userCode = self.request.args.get("user_code")
        if not userCode:
            raise OAuth2Error("user_code is absent.")

        # Get session from cookie
        if not self.server.db.getSessionByUserCode(userCode):
            raise OAuth2Error("Session with %s user code is expired." %
                              userCode)
        return None
Beispiel #2
0
    def save_device_credential(self, client_id, scope, data):
        """Save device credentials

        :param str client_id: client id
        :param str scope: request scopes
        :param dict data: device credentials
        """
        data.update(
            dict(
                uri=
                "{api}?{query}&response_type=device&client_id={client_id}&scope={scope}"
                .format(
                    api=data["verification_uri"],
                    query=self.req.query,
                    client_id=client_id,
                    scope=scope,
                ),
                id=data["device_code"],
                client_id=client_id,
                scope=scope,
            ))
        result = self.server.db.addSession(data)
        if not result["OK"]:
            raise OAuth2Error("Cannot save device credentials",
                              result["Message"])
Beispiel #3
0
    async def _refresh_token(self, data):
        resp = await self.request('POST',
                                  self.token_endpoint,
                                  data=data,
                                  withhold_token=True)

        token = resp.json()
        if 'error' in token:
            raise OAuth2Error(error=token['error'],
                              description=token.get('error_description'))
        self.token = token
        return self.token
Beispiel #4
0
    def _refresh_token(self, data):
        resp = self.request("POST",
                            self.token_endpoint,
                            data=data,
                            withhold_token=True)

        token = resp.json()
        if "error" in token:
            raise OAuth2Error(error=token["error"],
                              description=token.get("error_description"))
        self.token = token
        return self.token
Beispiel #5
0
    def query_user_grant(self, user_code):
        """Check if user alredy authed and return it to token generator

        :param str user_code: user code

        :return: (str, bool) or None -- user dict and user auth status
        """
        result = self.server.db.getSessionByUserCode(user_code)
        if not result["OK"]:
            raise OAuth2Error("Cannot found authorization session",
                              result["Message"])
        return (result["Value"]["user_id"], True) if result["Value"].get(
            "username", "None") != "None" else None
Beispiel #6
0
    def query_device_credential(self, device_code):
        """Get device credential from previously savings via ``DeviceAuthorizationEndpoint``.

        :param str device_code: device code

        :return: dict
        """
        result = self.server.db.getSession(device_code)
        if not result["OK"]:
            raise OAuth2Error(result["Message"])
        data = result["Value"]
        if not data:
            return None
        data["verification_uri"] = self.server.metadata[
            "device_authorization_endpoint"]
        data["expires_at"] = int(data["expires_in"]) + int(time.time())
        data["interval"] = DeviceAuthorizationEndpoint.INTERVAL
        return DeviceCredentialDict(data)
Beispiel #7
0
 def get_auth_token(self):
     """Fetch Access Token either using redirection grant flow or using auth_client"""
     if self.auth_client is not None and self.auth_registrar is not None:
         try:
             if "authorization_code" in self.auth_registrar.client_metadata.get(
                     "grant_types", {}):
                 self.logger.writeInfo(
                     "Endpoint '/oauth' on Node API will provide redirect to authorization endpoint on Auth Server."
                 )
                 return
             elif "client_credentials" in self.auth_registrar.client_metadata.get(
                     "grant_types", {}):
                 # Fetch Token
                 token = self.auth_client.fetch_access_token()
                 # Store token in member variable to be extracted using `fetch_local_token` function
                 self.auth_registry.bearer_token = token
             else:
                 raise OAuth2Error(
                     "Client not registered with supported Grant Type")
         except OAuth2Error as e:
             self.logger.writeError(
                 "Failure fetching access token. {}".format(e))
Beispiel #8
0
 def raise_error_response(self, error: OAuth2Error) -> typing.NoReturn:
     status_code = error.status_code
     data = dict(error.get_body())
     headers = error.get_headers()
     raise JSONException(status_code, data, headers)