Ejemplo n.º 1
0
class ClientCredentialsProvider(TokenProvider):
    client_id: str = None
    client_secret: str = None

    # TODO: Annotate the class with `@dataclass` and remove this once support
    # for Python 3.6 is dropped.
    def __init__(
        self, config: Config, client_id: str = None, client_secret: str = None
    ):
        super().__init__(config)
        self.client_id = client_id
        self.client_secret = client_secret
        self.__post_init__()

    def __post_init__(self):
        if not self.client_id:
            self.client_id = self.config.config.get("client_id")
        if not self.client_secret:
            self.client_secret = self.config.config.get("client_secret")

        if not (self.client_id and self.client_secret):
            raise TokenProviderNotInitialized

        self.client = KeycloakOpenID(
            server_url=self.config.config.get("keycloakServerUrl") + "/",
            realm_name=self.config.config.get("keycloakRealm"),
            client_id=self.client_id,
            client_secret_key=self.client_secret,
        )

    def refresh_token(self, refresh_token):
        return self.client.refresh_token(refresh_token=refresh_token)

    def new_token(self):
        return self.client.token(grant_type=["client_credentials"])
Ejemplo n.º 2
0
    def __post_init__(self):
        if not self.client_id:
            self.client_id = self.config.config.get("client_id")
        if not self.client_secret:
            self.client_secret = self.config.config.get("client_secret")

        if not (self.client_id and self.client_secret):
            raise TokenProviderNotInitialized

        self.client = KeycloakOpenID(
            server_url=self.config.config.get("keycloakServerUrl") + "/",
            realm_name=self.config.config.get("keycloakRealm"),
            client_id=self.client_id,
            client_secret_key=self.client_secret,
        )
Ejemplo n.º 3
0
    def new_openid_client(self):
        """
        :rtype: keycloak.keycloak_openid.KeycloakOpenID
        """

        return KeycloakOpenID(
            server_url='%sauth/' % self.server_url,
            realm_name=self.realm_name,
            client_id=self.client_id,
            client_secret_key=self.client_secret,
        )
Ejemplo n.º 4
0
    def __init__(self):
        self._config = getattr(settings, 'KEYCLOAK_CONFIG')

        # Read configurations
        try:
            self._server_url = self._config['KEYCLOAK_SERVER_URL']
            self._client_id = self._config['KEYCLOAK_CLIENT_ID']
            self._realm = self._config['KEYCLOAK_REALM']
        except KeyError as e:
            raise Exception("KEYCLOAK_SERVER_URL, KEYCLOAK_CLIENT_ID or KEYCLOAK_REALM not found.")

        self._client_secret_key = self._config.get('KEYCLOAK_CLIENT_SECRET_KEY', None)
        self._client_public_key = self._config.get('KEYCLOAK_CLIENT_PUBLIC_KEY', None)

        # Create Keycloak instance
        self._keycloak = KeycloakOpenID(server_url=self._server_url,
                                        client_id=self._client_id,
                                        realm_name=self._realm,
                                        client_secret_key=self._client_secret_key,
                                        verify=False)
Ejemplo n.º 5
0
 def openid_client(self):
     """
     :rtype: keycloak.keycloak_openid.KeycloakOpenID
     """
     if self._openid_client is None:
         self._openid_client = KeycloakOpenID(
             server_url='%sauth/' % self.server_url,
             realm_name=self.realm_name,
             client_id=self.client_id,
             client_secret_key=self.client_secret,
         )
     return self._openid_client
Ejemplo n.º 6
0
class KeepsAuthentication(authentication.TokenAuthentication):

    def __init__(self):
        self._config = getattr(settings, 'KEYCLOAK_CONFIG')

        # Read configurations
        try:
            self._server_url = self._config['KEYCLOAK_SERVER_URL']
            self._client_id = self._config['KEYCLOAK_CLIENT_ID']
            self._realm = self._config['KEYCLOAK_REALM']
        except KeyError as e:
            raise Exception("KEYCLOAK_SERVER_URL, KEYCLOAK_CLIENT_ID or KEYCLOAK_REALM not found.")

        self._client_secret_key = self._config.get('KEYCLOAK_CLIENT_SECRET_KEY', None)
        self._client_public_key = self._config.get('KEYCLOAK_CLIENT_PUBLIC_KEY', None)

        # Create Keycloak instance
        self._keycloak = KeycloakOpenID(server_url=self._server_url,
                                        client_id=self._client_id,
                                        realm_name=self._realm,
                                        client_secret_key=self._client_secret_key,
                                        verify=False)

    def authenticate(self, request):
        # Decode token and set request.user

        if self._skip_urls(request):
            return None, None

        user = self._get_token_info(request)
        user['client_id'] = self._get_profile(request)

        return user, None

    def _get_token_info(self, request):
        """ Decode token """

        # Options check token
        options = {"verify_signature": True, "verify_aud": False, "exp": True}

        # JWT not found
        if 'HTTP_AUTHORIZATION' not in request.META:
            raise NotAuthenticated("HTTP_AUTHORIZATION not found in the request")

        jwt = request.META.get('HTTP_AUTHORIZATION')

        try:
            token_info = self._keycloak.decode_token(jwt, key=self._client_public_key, options=options)
        except ExpiredSignatureError:
            options["verify_exp"] = False
            token_info = self._keycloak.decode_token(jwt, key=self._client_public_key, options=options)

            if "offline_access" in token_info['realm_access']['roles']:
                return token_info
            else:
                raise ExpiredSignatureError("Login expired")

        return token_info

    @staticmethod
    def _get_profile(request):
        return request.META.get('HTTP_X_CLIENT') or None

    @staticmethod
    def _skip_urls(request):
        if '/docs' in request.path or '/swagger' in request.path or '/redoc' in request.path:
            return True
        return False
Ejemplo n.º 7
0
    def __init__(self, username=None, password=None, file=None, token=None):
        """Quantum-Cirlce Annealer

        First Time using the Solver username and password are needed. Afterwards they will be
        saved in the package directory, such that the credential are not needed anymore.

        Parameters
        ----------
        username : string
            username for the developer portal
        password : string
            password for the corresponding username
        file : string, optional
            file, where to save the credentials (username and password). By default it will be saved
            in the package directory
        token : string, optional
            token, which can be obtained from the developer portal, by default None

        Raises
        ------
        ValueError
            If username and/or password is not given
        """
        FILE_NAME = 'client_secrets.json'
        
        self.response = None
        self.keycloak_openid = KeycloakOpenID(
            server_url=self.SERVER_URL,
            client_id=self.CLIENT_ID,
            realm_name=self.REALM_NAME,
        )
        # Get WellKnow
        self.config_well_know = self.keycloak_openid.well_know()
        #check file
        if file is not None:
            if Path(file).is_dir():
                file += "client_secrets.json"
            if not str(file).endswith('.json'):
                file += '.json'
        else:
            file = Path(qc_qubosolv.__file__.rsplit('/', 1)[0] + '/' + FILE_NAME)
        #check username and password
        if username is not None and password is not None:
            if Path(file).exists():
                with open(file) as config_file:
                    data = json.load(config_file)
                    data['username'] = username
                    data['password'] = password
                with open(file, 'w') as config_file:
                    json.dump(data, config_file, indent = 4)
            else:
                with open(Path(file), 'w') as config_file:
                    account = {
                        'username': username,
                        'password': password
                    }
                    json.dump(account, config_file, indent = 4)
        elif username is None and password is None:
            if not Path(file).exists():
                raise ValueError("File does not exist and username/password is not given")
            else:
                pass
        elif username is None or password is None:
            raise ValueError("Only Username or Password is given, but both are needed")
        
        # load token or username/password
        if token is not None:
            self.configuration = qc_qubosolv_api.Configuration()
            self.configuration.access_token = token
        else:
            with open(Path(file)) as config_file:
                data = json.load(config_file)
            try:
                response_token = self.keycloak_openid.token(
                    data['username'],
                    data['password']
                )
            except KeyError:
                raise ValueError(
                    "username and password is not saved, therefore token "
                    "cannot be generated or token is not given"
                )
            self.configuration = qc_qubosolv_api.Configuration()
            self.configuration.access_token = response_token["access_token"]
Ejemplo n.º 8
0
class Solver:
    """Quantum-Cirlce Annealer
    """
    SERVER_URL = "https://keycloak.quantum-circle.com/auth/"
    CLIENT_ID = "quantum-client"
    REALM_NAME = "quantum"
    
    def __init__(self, username=None, password=None, file=None, token=None):
        """Quantum-Cirlce Annealer

        First Time using the Solver username and password are needed. Afterwards they will be
        saved in the package directory, such that the credential are not needed anymore.

        Parameters
        ----------
        username : string
            username for the developer portal
        password : string
            password for the corresponding username
        file : string, optional
            file, where to save the credentials (username and password). By default it will be saved
            in the package directory
        token : string, optional
            token, which can be obtained from the developer portal, by default None

        Raises
        ------
        ValueError
            If username and/or password is not given
        """
        FILE_NAME = 'client_secrets.json'
        
        self.response = None
        self.keycloak_openid = KeycloakOpenID(
            server_url=self.SERVER_URL,
            client_id=self.CLIENT_ID,
            realm_name=self.REALM_NAME,
        )
        # Get WellKnow
        self.config_well_know = self.keycloak_openid.well_know()
        #check file
        if file is not None:
            if Path(file).is_dir():
                file += "client_secrets.json"
            if not str(file).endswith('.json'):
                file += '.json'
        else:
            file = Path(qc_qubosolv.__file__.rsplit('/', 1)[0] + '/' + FILE_NAME)
        #check username and password
        if username is not None and password is not None:
            if Path(file).exists():
                with open(file) as config_file:
                    data = json.load(config_file)
                    data['username'] = username
                    data['password'] = password
                with open(file, 'w') as config_file:
                    json.dump(data, config_file, indent = 4)
            else:
                with open(Path(file), 'w') as config_file:
                    account = {
                        'username': username,
                        'password': password
                    }
                    json.dump(account, config_file, indent = 4)
        elif username is None and password is None:
            if not Path(file).exists():
                raise ValueError("File does not exist and username/password is not given")
            else:
                pass
        elif username is None or password is None:
            raise ValueError("Only Username or Password is given, but both are needed")
        
        # load token or username/password
        if token is not None:
            self.configuration = qc_qubosolv_api.Configuration()
            self.configuration.access_token = token
        else:
            with open(Path(file)) as config_file:
                data = json.load(config_file)
            try:
                response_token = self.keycloak_openid.token(
                    data['username'],
                    data['password']
                )
            except KeyError:
                raise ValueError(
                    "username and password is not saved, therefore token "
                    "cannot be generated or token is not given"
                )
            self.configuration = qc_qubosolv_api.Configuration()
            self.configuration.access_token = response_token["access_token"]

        

    def solve(self, matrix, offset=0, temp_start=_DEFAULT_temp_start,
              temp_end=_DEFAULT_temp_end, tau=_DEFAULT_tau, beta=_DEFAULT_beta,
              maximize=_DEFAULT_maximize, algorithm=_DEFAULT_algorithm):
        """
        Solves a QUBO matrix with the Main Incubator Annealer.

        Parameters
        ----------
        matrix : list
            must be either symmetric or uppertriangular matrix
        offset : int or float
            constant or offset factor of the QUBO
        temp_start : int or float
            is the start temperature, by default 5
        temp_end : int or float
            is the end temperature by default 0.001
        tau : int or float
            is the stepwidth of decreasing temperature, where the
            temperature is changed with Temp_new = tau * Temp, by default 0.9999
        beta : int or float
            influences the acceptance probability, which is exp(-dE*beta),
            by default 0.02
        maximize : boolean
            maximize or minimize the energy function, by default False
        algorithm : str
            'bf' for bruteforce solver, 'sa' for simulated annealing or
            'sqa' for simulated quantum annealing

        Returns
        -------
        SolverResult
            an object containing the result
        """
        self.api_instance = qc_qubosolv_api.ProblemApi(
            qc_qubosolv_api.ApiClient(self.configuration)
        )
        self.body = qc_qubosolv_api.Task()

        if isinstance(matrix, np.ndarray):
            self.body.matrix = matrix.tolist()
        else:
            self.body.matrix = matrix

        self.body.parameter = qc_qubosolv_api.Parameter()
        self.body.parameter.temp_start = temp_start
        self.body.parameter.temp_end = temp_end
        self.body.parameter.tau = tau
        self.body.parameter.beta = beta
        self.body.parameter.maximize = maximize
        self.body.parameter.algorithm = algorithm
        response_json = self.api_instance.task_post(self.body)
        self.response = SolverResult(json.loads(response_json), offset)
        return self.response