id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,500
kragniz/python-etcd3
etcd3/events.py
new_event
def new_event(event): """ Wrap a raw gRPC event in a friendlier containing class. This picks the appropriate class from one of PutEvent or DeleteEvent and returns a new instance. """ op_name = event.EventType.DESCRIPTOR.values_by_number[event.type].name if op_name == 'PUT': cls = PutEvent elif op_name == 'DELETE': cls = DeleteEvent else: raise Exception('Invalid op_name') return cls(event)
python
def new_event(event): op_name = event.EventType.DESCRIPTOR.values_by_number[event.type].name if op_name == 'PUT': cls = PutEvent elif op_name == 'DELETE': cls = DeleteEvent else: raise Exception('Invalid op_name') return cls(event)
[ "def", "new_event", "(", "event", ")", ":", "op_name", "=", "event", ".", "EventType", ".", "DESCRIPTOR", ".", "values_by_number", "[", "event", ".", "type", "]", ".", "name", "if", "op_name", "==", "'PUT'", ":", "cls", "=", "PutEvent", "elif", "op_name"...
Wrap a raw gRPC event in a friendlier containing class. This picks the appropriate class from one of PutEvent or DeleteEvent and returns a new instance.
[ "Wrap", "a", "raw", "gRPC", "event", "in", "a", "friendlier", "containing", "class", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/events.py#L26-L41
232,501
kragniz/python-etcd3
etcd3/locks.py
Lock.is_acquired
def is_acquired(self): """Check if this lock is currently acquired.""" uuid, _ = self.etcd_client.get(self.key) if uuid is None: return False return uuid == self.uuid
python
def is_acquired(self): uuid, _ = self.etcd_client.get(self.key) if uuid is None: return False return uuid == self.uuid
[ "def", "is_acquired", "(", "self", ")", ":", "uuid", ",", "_", "=", "self", ".", "etcd_client", ".", "get", "(", "self", ".", "key", ")", "if", "uuid", "is", "None", ":", "return", "False", "return", "uuid", "==", "self", ".", "uuid" ]
Check if this lock is currently acquired.
[ "Check", "if", "this", "lock", "is", "currently", "acquired", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/locks.py#L126-L133
232,502
kragniz/python-etcd3
etcd3/utils.py
lease_to_id
def lease_to_id(lease): """Figure out if the argument is a Lease object, or the lease ID.""" lease_id = 0 if hasattr(lease, 'id'): lease_id = lease.id else: try: lease_id = int(lease) except TypeError: pass return lease_id
python
def lease_to_id(lease): lease_id = 0 if hasattr(lease, 'id'): lease_id = lease.id else: try: lease_id = int(lease) except TypeError: pass return lease_id
[ "def", "lease_to_id", "(", "lease", ")", ":", "lease_id", "=", "0", "if", "hasattr", "(", "lease", ",", "'id'", ")", ":", "lease_id", "=", "lease", ".", "id", "else", ":", "try", ":", "lease_id", "=", "int", "(", "lease", ")", "except", "TypeError", ...
Figure out if the argument is a Lease object, or the lease ID.
[ "Figure", "out", "if", "the", "argument", "is", "a", "Lease", "object", "or", "the", "lease", "ID", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/utils.py#L20-L30
232,503
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.put
def put(self, key, value, lease=None, prev_kv=False): """ Save a value to etcd. Example usage: .. code-block:: python >>> import etcd3 >>> etcd = etcd3.client() >>> etcd.put('/thing/key', 'hello world') :param key: key in etcd to set :param value: value to set key to :type value: bytes :param lease: Lease to associate with this key. :type lease: either :class:`.Lease`, or int (ID of lease) :param prev_kv: return the previous key-value pair :type prev_kv: bool :returns: a response containing a header and the prev_kv :rtype: :class:`.rpc_pb2.PutResponse` """ put_request = self._build_put_request(key, value, lease=lease, prev_kv=prev_kv) return self.kvstub.Put( put_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
python
def put(self, key, value, lease=None, prev_kv=False): put_request = self._build_put_request(key, value, lease=lease, prev_kv=prev_kv) return self.kvstub.Put( put_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
[ "def", "put", "(", "self", ",", "key", ",", "value", ",", "lease", "=", "None", ",", "prev_kv", "=", "False", ")", ":", "put_request", "=", "self", ".", "_build_put_request", "(", "key", ",", "value", ",", "lease", "=", "lease", ",", "prev_kv", "=", ...
Save a value to etcd. Example usage: .. code-block:: python >>> import etcd3 >>> etcd = etcd3.client() >>> etcd.put('/thing/key', 'hello world') :param key: key in etcd to set :param value: value to set key to :type value: bytes :param lease: Lease to associate with this key. :type lease: either :class:`.Lease`, or int (ID of lease) :param prev_kv: return the previous key-value pair :type prev_kv: bool :returns: a response containing a header and the prev_kv :rtype: :class:`.rpc_pb2.PutResponse`
[ "Save", "a", "value", "to", "etcd", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L396-L425
232,504
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.put_if_not_exists
def put_if_not_exists(self, key, value, lease=None): """ Atomically puts a value only if the key previously had no value. This is the etcdv3 equivalent to setting a key with the etcdv2 parameter prevExist=false. :param key: key in etcd to put :param value: value to be written to key :type value: bytes :param lease: Lease to associate with this key. :type lease: either :class:`.Lease`, or int (ID of lease) :returns: state of transaction, ``True`` if the put was successful, ``False`` otherwise :rtype: bool """ status, _ = self.transaction( compare=[self.transactions.create(key) == '0'], success=[self.transactions.put(key, value, lease=lease)], failure=[], ) return status
python
def put_if_not_exists(self, key, value, lease=None): status, _ = self.transaction( compare=[self.transactions.create(key) == '0'], success=[self.transactions.put(key, value, lease=lease)], failure=[], ) return status
[ "def", "put_if_not_exists", "(", "self", ",", "key", ",", "value", ",", "lease", "=", "None", ")", ":", "status", ",", "_", "=", "self", ".", "transaction", "(", "compare", "=", "[", "self", ".", "transactions", ".", "create", "(", "key", ")", "==", ...
Atomically puts a value only if the key previously had no value. This is the etcdv3 equivalent to setting a key with the etcdv2 parameter prevExist=false. :param key: key in etcd to put :param value: value to be written to key :type value: bytes :param lease: Lease to associate with this key. :type lease: either :class:`.Lease`, or int (ID of lease) :returns: state of transaction, ``True`` if the put was successful, ``False`` otherwise :rtype: bool
[ "Atomically", "puts", "a", "value", "only", "if", "the", "key", "previously", "had", "no", "value", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L428-L450
232,505
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.delete
def delete(self, key, prev_kv=False, return_response=False): """ Delete a single key in etcd. :param key: key in etcd to delete :param prev_kv: return the deleted key-value pair :type prev_kv: bool :param return_response: return the full response :type return_response: bool :returns: True if the key has been deleted when ``return_response`` is False and a response containing a header, the number of deleted keys and prev_kvs when ``return_response`` is True """ delete_request = self._build_delete_request(key, prev_kv=prev_kv) delete_response = self.kvstub.DeleteRange( delete_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) if return_response: return delete_response return delete_response.deleted >= 1
python
def delete(self, key, prev_kv=False, return_response=False): delete_request = self._build_delete_request(key, prev_kv=prev_kv) delete_response = self.kvstub.DeleteRange( delete_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) if return_response: return delete_response return delete_response.deleted >= 1
[ "def", "delete", "(", "self", ",", "key", ",", "prev_kv", "=", "False", ",", "return_response", "=", "False", ")", ":", "delete_request", "=", "self", ".", "_build_delete_request", "(", "key", ",", "prev_kv", "=", "prev_kv", ")", "delete_response", "=", "s...
Delete a single key in etcd. :param key: key in etcd to delete :param prev_kv: return the deleted key-value pair :type prev_kv: bool :param return_response: return the full response :type return_response: bool :returns: True if the key has been deleted when ``return_response`` is False and a response containing a header, the number of deleted keys and prev_kvs when ``return_response`` is True
[ "Delete", "a", "single", "key", "in", "etcd", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L491-L514
232,506
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.status
def status(self): """Get the status of the responding member.""" status_request = etcdrpc.StatusRequest() status_response = self.maintenancestub.Status( status_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) for m in self.members: if m.id == status_response.leader: leader = m break else: # raise exception? leader = None return Status(status_response.version, status_response.dbSize, leader, status_response.raftIndex, status_response.raftTerm)
python
def status(self): status_request = etcdrpc.StatusRequest() status_response = self.maintenancestub.Status( status_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) for m in self.members: if m.id == status_response.leader: leader = m break else: # raise exception? leader = None return Status(status_response.version, status_response.dbSize, leader, status_response.raftIndex, status_response.raftTerm)
[ "def", "status", "(", "self", ")", ":", "status_request", "=", "etcdrpc", ".", "StatusRequest", "(", ")", "status_response", "=", "self", ".", "maintenancestub", ".", "Status", "(", "status_request", ",", "self", ".", "timeout", ",", "credentials", "=", "sel...
Get the status of the responding member.
[ "Get", "the", "status", "of", "the", "responding", "member", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L531-L553
232,507
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.add_watch_callback
def add_watch_callback(self, *args, **kwargs): """ Watch a key or range of keys and call a callback on every event. If timeout was declared during the client initialization and the watch cannot be created during that time the method raises a ``WatchTimedOut`` exception. :param key: key to watch :param callback: callback function :returns: watch_id. Later it could be used for cancelling watch. """ try: return self.watcher.add_callback(*args, **kwargs) except queue.Empty: raise exceptions.WatchTimedOut()
python
def add_watch_callback(self, *args, **kwargs): try: return self.watcher.add_callback(*args, **kwargs) except queue.Empty: raise exceptions.WatchTimedOut()
[ "def", "add_watch_callback", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "watcher", ".", "add_callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "queue", ".", "Empty", ":", ...
Watch a key or range of keys and call a callback on every event. If timeout was declared during the client initialization and the watch cannot be created during that time the method raises a ``WatchTimedOut`` exception. :param key: key to watch :param callback: callback function :returns: watch_id. Later it could be used for cancelling watch.
[ "Watch", "a", "key", "or", "range", "of", "keys", "and", "call", "a", "callback", "on", "every", "event", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L556-L572
232,508
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.watch_prefix
def watch_prefix(self, key_prefix, **kwargs): """Watches a range of keys with a prefix.""" kwargs['range_end'] = \ utils.increment_last_byte(utils.to_bytes(key_prefix)) return self.watch(key_prefix, **kwargs)
python
def watch_prefix(self, key_prefix, **kwargs): kwargs['range_end'] = \ utils.increment_last_byte(utils.to_bytes(key_prefix)) return self.watch(key_prefix, **kwargs)
[ "def", "watch_prefix", "(", "self", ",", "key_prefix", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'range_end'", "]", "=", "utils", ".", "increment_last_byte", "(", "utils", ".", "to_bytes", "(", "key_prefix", ")", ")", "return", "self", ".", "wat...
Watches a range of keys with a prefix.
[ "Watches", "a", "range", "of", "keys", "with", "a", "prefix", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L620-L624
232,509
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.watch_prefix_once
def watch_prefix_once(self, key_prefix, timeout=None, **kwargs): """ Watches a range of keys with a prefix and stops after the first event. If the timeout was specified and event didn't arrived method will raise ``WatchTimedOut`` exception. """ kwargs['range_end'] = \ utils.increment_last_byte(utils.to_bytes(key_prefix)) return self.watch_once(key_prefix, timeout=timeout, **kwargs)
python
def watch_prefix_once(self, key_prefix, timeout=None, **kwargs): kwargs['range_end'] = \ utils.increment_last_byte(utils.to_bytes(key_prefix)) return self.watch_once(key_prefix, timeout=timeout, **kwargs)
[ "def", "watch_prefix_once", "(", "self", ",", "key_prefix", ",", "timeout", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'range_end'", "]", "=", "utils", ".", "increment_last_byte", "(", "utils", ".", "to_bytes", "(", "key_prefix", ")", ...
Watches a range of keys with a prefix and stops after the first event. If the timeout was specified and event didn't arrived method will raise ``WatchTimedOut`` exception.
[ "Watches", "a", "range", "of", "keys", "with", "a", "prefix", "and", "stops", "after", "the", "first", "event", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L653-L662
232,510
kragniz/python-etcd3
etcd3/client.py
Etcd3Client._ops_to_requests
def _ops_to_requests(self, ops): """ Return a list of grpc requests. Returns list from an input list of etcd3.transactions.{Put, Get, Delete, Txn} objects. """ request_ops = [] for op in ops: if isinstance(op, transactions.Put): request = self._build_put_request(op.key, op.value, op.lease, op.prev_kv) request_op = etcdrpc.RequestOp(request_put=request) request_ops.append(request_op) elif isinstance(op, transactions.Get): request = self._build_get_range_request(op.key, op.range_end) request_op = etcdrpc.RequestOp(request_range=request) request_ops.append(request_op) elif isinstance(op, transactions.Delete): request = self._build_delete_request(op.key, op.range_end, op.prev_kv) request_op = etcdrpc.RequestOp(request_delete_range=request) request_ops.append(request_op) elif isinstance(op, transactions.Txn): compare = [c.build_message() for c in op.compare] success_ops = self._ops_to_requests(op.success) failure_ops = self._ops_to_requests(op.failure) request = etcdrpc.TxnRequest(compare=compare, success=success_ops, failure=failure_ops) request_op = etcdrpc.RequestOp(request_txn=request) request_ops.append(request_op) else: raise Exception( 'Unknown request class {}'.format(op.__class__)) return request_ops
python
def _ops_to_requests(self, ops): request_ops = [] for op in ops: if isinstance(op, transactions.Put): request = self._build_put_request(op.key, op.value, op.lease, op.prev_kv) request_op = etcdrpc.RequestOp(request_put=request) request_ops.append(request_op) elif isinstance(op, transactions.Get): request = self._build_get_range_request(op.key, op.range_end) request_op = etcdrpc.RequestOp(request_range=request) request_ops.append(request_op) elif isinstance(op, transactions.Delete): request = self._build_delete_request(op.key, op.range_end, op.prev_kv) request_op = etcdrpc.RequestOp(request_delete_range=request) request_ops.append(request_op) elif isinstance(op, transactions.Txn): compare = [c.build_message() for c in op.compare] success_ops = self._ops_to_requests(op.success) failure_ops = self._ops_to_requests(op.failure) request = etcdrpc.TxnRequest(compare=compare, success=success_ops, failure=failure_ops) request_op = etcdrpc.RequestOp(request_txn=request) request_ops.append(request_op) else: raise Exception( 'Unknown request class {}'.format(op.__class__)) return request_ops
[ "def", "_ops_to_requests", "(", "self", ",", "ops", ")", ":", "request_ops", "=", "[", "]", "for", "op", "in", "ops", ":", "if", "isinstance", "(", "op", ",", "transactions", ".", "Put", ")", ":", "request", "=", "self", ".", "_build_put_request", "(",...
Return a list of grpc requests. Returns list from an input list of etcd3.transactions.{Put, Get, Delete, Txn} objects.
[ "Return", "a", "list", "of", "grpc", "requests", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L673-L712
232,511
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.transaction
def transaction(self, compare, success=None, failure=None): """ Perform a transaction. Example usage: .. code-block:: python etcd.transaction( compare=[ etcd.transactions.value('/doot/testing') == 'doot', etcd.transactions.version('/doot/testing') > 0, ], success=[ etcd.transactions.put('/doot/testing', 'success'), ], failure=[ etcd.transactions.put('/doot/testing', 'failure'), ] ) :param compare: A list of comparisons to make :param success: A list of operations to perform if all the comparisons are true :param failure: A list of operations to perform if any of the comparisons are false :return: A tuple of (operation status, responses) """ compare = [c.build_message() for c in compare] success_ops = self._ops_to_requests(success) failure_ops = self._ops_to_requests(failure) transaction_request = etcdrpc.TxnRequest(compare=compare, success=success_ops, failure=failure_ops) txn_response = self.kvstub.Txn( transaction_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) responses = [] for response in txn_response.responses: response_type = response.WhichOneof('response') if response_type in ['response_put', 'response_delete_range', 'response_txn']: responses.append(response) elif response_type == 'response_range': range_kvs = [] for kv in response.response_range.kvs: range_kvs.append((kv.value, KVMetadata(kv, txn_response.header))) responses.append(range_kvs) return txn_response.succeeded, responses
python
def transaction(self, compare, success=None, failure=None): compare = [c.build_message() for c in compare] success_ops = self._ops_to_requests(success) failure_ops = self._ops_to_requests(failure) transaction_request = etcdrpc.TxnRequest(compare=compare, success=success_ops, failure=failure_ops) txn_response = self.kvstub.Txn( transaction_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) responses = [] for response in txn_response.responses: response_type = response.WhichOneof('response') if response_type in ['response_put', 'response_delete_range', 'response_txn']: responses.append(response) elif response_type == 'response_range': range_kvs = [] for kv in response.response_range.kvs: range_kvs.append((kv.value, KVMetadata(kv, txn_response.header))) responses.append(range_kvs) return txn_response.succeeded, responses
[ "def", "transaction", "(", "self", ",", "compare", ",", "success", "=", "None", ",", "failure", "=", "None", ")", ":", "compare", "=", "[", "c", ".", "build_message", "(", ")", "for", "c", "in", "compare", "]", "success_ops", "=", "self", ".", "_ops_...
Perform a transaction. Example usage: .. code-block:: python etcd.transaction( compare=[ etcd.transactions.value('/doot/testing') == 'doot', etcd.transactions.version('/doot/testing') > 0, ], success=[ etcd.transactions.put('/doot/testing', 'success'), ], failure=[ etcd.transactions.put('/doot/testing', 'failure'), ] ) :param compare: A list of comparisons to make :param success: A list of operations to perform if all the comparisons are true :param failure: A list of operations to perform if any of the comparisons are false :return: A tuple of (operation status, responses)
[ "Perform", "a", "transaction", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L715-L773
232,512
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.lease
def lease(self, ttl, lease_id=None): """ Create a new lease. All keys attached to this lease will be expired and deleted if the lease expires. A lease can be sent keep alive messages to refresh the ttl. :param ttl: Requested time to live :param lease_id: Requested ID for the lease :returns: new lease :rtype: :class:`.Lease` """ lease_grant_request = etcdrpc.LeaseGrantRequest(TTL=ttl, ID=lease_id) lease_grant_response = self.leasestub.LeaseGrant( lease_grant_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) return leases.Lease(lease_id=lease_grant_response.ID, ttl=lease_grant_response.TTL, etcd_client=self)
python
def lease(self, ttl, lease_id=None): lease_grant_request = etcdrpc.LeaseGrantRequest(TTL=ttl, ID=lease_id) lease_grant_response = self.leasestub.LeaseGrant( lease_grant_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) return leases.Lease(lease_id=lease_grant_response.ID, ttl=lease_grant_response.TTL, etcd_client=self)
[ "def", "lease", "(", "self", ",", "ttl", ",", "lease_id", "=", "None", ")", ":", "lease_grant_request", "=", "etcdrpc", ".", "LeaseGrantRequest", "(", "TTL", "=", "ttl", ",", "ID", "=", "lease_id", ")", "lease_grant_response", "=", "self", ".", "leasestub"...
Create a new lease. All keys attached to this lease will be expired and deleted if the lease expires. A lease can be sent keep alive messages to refresh the ttl. :param ttl: Requested time to live :param lease_id: Requested ID for the lease :returns: new lease :rtype: :class:`.Lease`
[ "Create", "a", "new", "lease", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L776-L799
232,513
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.revoke_lease
def revoke_lease(self, lease_id): """ Revoke a lease. :param lease_id: ID of the lease to revoke. """ lease_revoke_request = etcdrpc.LeaseRevokeRequest(ID=lease_id) self.leasestub.LeaseRevoke( lease_revoke_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
python
def revoke_lease(self, lease_id): lease_revoke_request = etcdrpc.LeaseRevokeRequest(ID=lease_id) self.leasestub.LeaseRevoke( lease_revoke_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
[ "def", "revoke_lease", "(", "self", ",", "lease_id", ")", ":", "lease_revoke_request", "=", "etcdrpc", ".", "LeaseRevokeRequest", "(", "ID", "=", "lease_id", ")", "self", ".", "leasestub", ".", "LeaseRevoke", "(", "lease_revoke_request", ",", "self", ".", "tim...
Revoke a lease. :param lease_id: ID of the lease to revoke.
[ "Revoke", "a", "lease", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L802-L814
232,514
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.lock
def lock(self, name, ttl=60): """ Create a new lock. :param name: name of the lock :type name: string or bytes :param ttl: length of time for the lock to live for in seconds. The lock will be released after this time elapses, unless refreshed :type ttl: int :returns: new lock :rtype: :class:`.Lock` """ return locks.Lock(name, ttl=ttl, etcd_client=self)
python
def lock(self, name, ttl=60): return locks.Lock(name, ttl=ttl, etcd_client=self)
[ "def", "lock", "(", "self", ",", "name", ",", "ttl", "=", "60", ")", ":", "return", "locks", ".", "Lock", "(", "name", ",", "ttl", "=", "ttl", ",", "etcd_client", "=", "self", ")" ]
Create a new lock. :param name: name of the lock :type name: string or bytes :param ttl: length of time for the lock to live for in seconds. The lock will be released after this time elapses, unless refreshed :type ttl: int :returns: new lock :rtype: :class:`.Lock`
[ "Create", "a", "new", "lock", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L840-L853
232,515
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.add_member
def add_member(self, urls): """ Add a member into the cluster. :returns: new member :rtype: :class:`.Member` """ member_add_request = etcdrpc.MemberAddRequest(peerURLs=urls) member_add_response = self.clusterstub.MemberAdd( member_add_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) member = member_add_response.member return etcd3.members.Member(member.ID, member.name, member.peerURLs, member.clientURLs, etcd_client=self)
python
def add_member(self, urls): member_add_request = etcdrpc.MemberAddRequest(peerURLs=urls) member_add_response = self.clusterstub.MemberAdd( member_add_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) member = member_add_response.member return etcd3.members.Member(member.ID, member.name, member.peerURLs, member.clientURLs, etcd_client=self)
[ "def", "add_member", "(", "self", ",", "urls", ")", ":", "member_add_request", "=", "etcdrpc", ".", "MemberAddRequest", "(", "peerURLs", "=", "urls", ")", "member_add_response", "=", "self", ".", "clusterstub", ".", "MemberAdd", "(", "member_add_request", ",", ...
Add a member into the cluster. :returns: new member :rtype: :class:`.Member`
[ "Add", "a", "member", "into", "the", "cluster", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L856-L877
232,516
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.remove_member
def remove_member(self, member_id): """ Remove an existing member from the cluster. :param member_id: ID of the member to remove """ member_rm_request = etcdrpc.MemberRemoveRequest(ID=member_id) self.clusterstub.MemberRemove( member_rm_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
python
def remove_member(self, member_id): member_rm_request = etcdrpc.MemberRemoveRequest(ID=member_id) self.clusterstub.MemberRemove( member_rm_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
[ "def", "remove_member", "(", "self", ",", "member_id", ")", ":", "member_rm_request", "=", "etcdrpc", ".", "MemberRemoveRequest", "(", "ID", "=", "member_id", ")", "self", ".", "clusterstub", ".", "MemberRemove", "(", "member_rm_request", ",", "self", ".", "ti...
Remove an existing member from the cluster. :param member_id: ID of the member to remove
[ "Remove", "an", "existing", "member", "from", "the", "cluster", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L880-L892
232,517
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.update_member
def update_member(self, member_id, peer_urls): """ Update the configuration of an existing member in the cluster. :param member_id: ID of the member to update :param peer_urls: new list of peer urls the member will use to communicate with the cluster """ member_update_request = etcdrpc.MemberUpdateRequest(ID=member_id, peerURLs=peer_urls) self.clusterstub.MemberUpdate( member_update_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
python
def update_member(self, member_id, peer_urls): member_update_request = etcdrpc.MemberUpdateRequest(ID=member_id, peerURLs=peer_urls) self.clusterstub.MemberUpdate( member_update_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
[ "def", "update_member", "(", "self", ",", "member_id", ",", "peer_urls", ")", ":", "member_update_request", "=", "etcdrpc", ".", "MemberUpdateRequest", "(", "ID", "=", "member_id", ",", "peerURLs", "=", "peer_urls", ")", "self", ".", "clusterstub", ".", "Membe...
Update the configuration of an existing member in the cluster. :param member_id: ID of the member to update :param peer_urls: new list of peer urls the member will use to communicate with the cluster
[ "Update", "the", "configuration", "of", "an", "existing", "member", "in", "the", "cluster", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L895-L910
232,518
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.members
def members(self): """ List of all members associated with the cluster. :type: sequence of :class:`.Member` """ member_list_request = etcdrpc.MemberListRequest() member_list_response = self.clusterstub.MemberList( member_list_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) for member in member_list_response.members: yield etcd3.members.Member(member.ID, member.name, member.peerURLs, member.clientURLs, etcd_client=self)
python
def members(self): member_list_request = etcdrpc.MemberListRequest() member_list_response = self.clusterstub.MemberList( member_list_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) for member in member_list_response.members: yield etcd3.members.Member(member.ID, member.name, member.peerURLs, member.clientURLs, etcd_client=self)
[ "def", "members", "(", "self", ")", ":", "member_list_request", "=", "etcdrpc", ".", "MemberListRequest", "(", ")", "member_list_response", "=", "self", ".", "clusterstub", ".", "MemberList", "(", "member_list_request", ",", "self", ".", "timeout", ",", "credent...
List of all members associated with the cluster. :type: sequence of :class:`.Member`
[ "List", "of", "all", "members", "associated", "with", "the", "cluster", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L913-L933
232,519
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.compact
def compact(self, revision, physical=False): """ Compact the event history in etcd up to a given revision. All superseded keys with a revision less than the compaction revision will be removed. :param revision: revision for the compaction operation :param physical: if set to True, the request will wait until the compaction is physically applied to the local database such that compacted entries are totally removed from the backend database """ compact_request = etcdrpc.CompactionRequest(revision=revision, physical=physical) self.kvstub.Compact( compact_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
python
def compact(self, revision, physical=False): compact_request = etcdrpc.CompactionRequest(revision=revision, physical=physical) self.kvstub.Compact( compact_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
[ "def", "compact", "(", "self", ",", "revision", ",", "physical", "=", "False", ")", ":", "compact_request", "=", "etcdrpc", ".", "CompactionRequest", "(", "revision", "=", "revision", ",", "physical", "=", "physical", ")", "self", ".", "kvstub", ".", "Comp...
Compact the event history in etcd up to a given revision. All superseded keys with a revision less than the compaction revision will be removed. :param revision: revision for the compaction operation :param physical: if set to True, the request will wait until the compaction is physically applied to the local database such that compacted entries are totally removed from the backend database
[ "Compact", "the", "event", "history", "in", "etcd", "up", "to", "a", "given", "revision", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L936-L956
232,520
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.defragment
def defragment(self): """Defragment a member's backend database to recover storage space.""" defrag_request = etcdrpc.DefragmentRequest() self.maintenancestub.Defragment( defrag_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
python
def defragment(self): defrag_request = etcdrpc.DefragmentRequest() self.maintenancestub.Defragment( defrag_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata )
[ "def", "defragment", "(", "self", ")", ":", "defrag_request", "=", "etcdrpc", ".", "DefragmentRequest", "(", ")", "self", ".", "maintenancestub", ".", "Defragment", "(", "defrag_request", ",", "self", ".", "timeout", ",", "credentials", "=", "self", ".", "ca...
Defragment a member's backend database to recover storage space.
[ "Defragment", "a", "member", "s", "backend", "database", "to", "recover", "storage", "space", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L959-L967
232,521
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.hash
def hash(self): """ Return the hash of the local KV state. :returns: kv state hash :rtype: int """ hash_request = etcdrpc.HashRequest() return self.maintenancestub.Hash(hash_request).hash
python
def hash(self): hash_request = etcdrpc.HashRequest() return self.maintenancestub.Hash(hash_request).hash
[ "def", "hash", "(", "self", ")", ":", "hash_request", "=", "etcdrpc", ".", "HashRequest", "(", ")", "return", "self", ".", "maintenancestub", ".", "Hash", "(", "hash_request", ")", ".", "hash" ]
Return the hash of the local KV state. :returns: kv state hash :rtype: int
[ "Return", "the", "hash", "of", "the", "local", "KV", "state", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L970-L978
232,522
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.create_alarm
def create_alarm(self, member_id=0): """Create an alarm. If no member id is given, the alarm is activated for all the members of the cluster. Only the `no space` alarm can be raised. :param member_id: The cluster member id to create an alarm to. If 0, the alarm is created for all the members of the cluster. :returns: list of :class:`.Alarm` """ alarm_request = self._build_alarm_request('activate', member_id, 'no space') alarm_response = self.maintenancestub.Alarm( alarm_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) return [Alarm(alarm.alarm, alarm.memberID) for alarm in alarm_response.alarms]
python
def create_alarm(self, member_id=0): alarm_request = self._build_alarm_request('activate', member_id, 'no space') alarm_response = self.maintenancestub.Alarm( alarm_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) return [Alarm(alarm.alarm, alarm.memberID) for alarm in alarm_response.alarms]
[ "def", "create_alarm", "(", "self", ",", "member_id", "=", "0", ")", ":", "alarm_request", "=", "self", ".", "_build_alarm_request", "(", "'activate'", ",", "member_id", ",", "'no space'", ")", "alarm_response", "=", "self", ".", "maintenancestub", ".", "Alarm...
Create an alarm. If no member id is given, the alarm is activated for all the members of the cluster. Only the `no space` alarm can be raised. :param member_id: The cluster member id to create an alarm to. If 0, the alarm is created for all the members of the cluster. :returns: list of :class:`.Alarm`
[ "Create", "an", "alarm", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L1004-L1026
232,523
kragniz/python-etcd3
etcd3/client.py
Etcd3Client.snapshot
def snapshot(self, file_obj): """Take a snapshot of the database. :param file_obj: A file-like object to write the database contents in. """ snapshot_request = etcdrpc.SnapshotRequest() snapshot_response = self.maintenancestub.Snapshot( snapshot_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) for response in snapshot_response: file_obj.write(response.blob)
python
def snapshot(self, file_obj): snapshot_request = etcdrpc.SnapshotRequest() snapshot_response = self.maintenancestub.Snapshot( snapshot_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ) for response in snapshot_response: file_obj.write(response.blob)
[ "def", "snapshot", "(", "self", ",", "file_obj", ")", ":", "snapshot_request", "=", "etcdrpc", ".", "SnapshotRequest", "(", ")", "snapshot_response", "=", "self", ".", "maintenancestub", ".", "Snapshot", "(", "snapshot_request", ",", "self", ".", "timeout", ",...
Take a snapshot of the database. :param file_obj: A file-like object to write the database contents in.
[ "Take", "a", "snapshot", "of", "the", "database", "." ]
0adb14840d4a6011a2023a13f07e247e4c336a80
https://github.com/kragniz/python-etcd3/blob/0adb14840d4a6011a2023a13f07e247e4c336a80/etcd3/client.py#L1074-L1088
232,524
sentinel-hub/sentinel2-cloud-detector
s2cloudless/PixelClassifier.py
PixelClassifier.extract_pixels
def extract_pixels(X): """ Extract pixels from array X :param X: Array of images to be classified. :type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands] :return: Reshaped 2D array :rtype: numpy array, [n_samples*n_pixels_y*n_pixels_x,n_bands] :raises: ValueError is input array has wrong dimensions """ if len(X.shape) != 4: raise ValueError('Array of input images has to be a 4-dimensional array of shape' '[n_images, n_pixels_y, n_pixels_x, n_bands]') new_shape = (X.shape[0] * X.shape[1] * X.shape[2], X.shape[3],) pixels = X.reshape(new_shape) return pixels
python
def extract_pixels(X): if len(X.shape) != 4: raise ValueError('Array of input images has to be a 4-dimensional array of shape' '[n_images, n_pixels_y, n_pixels_x, n_bands]') new_shape = (X.shape[0] * X.shape[1] * X.shape[2], X.shape[3],) pixels = X.reshape(new_shape) return pixels
[ "def", "extract_pixels", "(", "X", ")", ":", "if", "len", "(", "X", ".", "shape", ")", "!=", "4", ":", "raise", "ValueError", "(", "'Array of input images has to be a 4-dimensional array of shape'", "'[n_images, n_pixels_y, n_pixels_x, n_bands]'", ")", "new_shape", "=",...
Extract pixels from array X :param X: Array of images to be classified. :type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands] :return: Reshaped 2D array :rtype: numpy array, [n_samples*n_pixels_y*n_pixels_x,n_bands] :raises: ValueError is input array has wrong dimensions
[ "Extract", "pixels", "from", "array", "X" ]
7130a4a6af90a92f28592d11da692bbb0dc1dc01
https://github.com/sentinel-hub/sentinel2-cloud-detector/blob/7130a4a6af90a92f28592d11da692bbb0dc1dc01/s2cloudless/PixelClassifier.py#L47-L62
232,525
sentinel-hub/sentinel2-cloud-detector
s2cloudless/PixelClassifier.py
PixelClassifier.image_predict
def image_predict(self, X): """ Predicts class label for the entire image. :param X: Array of images to be classified. :type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands] :return: raster classification map :rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x] """ pixels = self.extract_pixels(X) predictions = self.classifier.predict(pixels) return predictions.reshape(X.shape[0], X.shape[1], X.shape[2])
python
def image_predict(self, X): pixels = self.extract_pixels(X) predictions = self.classifier.predict(pixels) return predictions.reshape(X.shape[0], X.shape[1], X.shape[2])
[ "def", "image_predict", "(", "self", ",", "X", ")", ":", "pixels", "=", "self", ".", "extract_pixels", "(", "X", ")", "predictions", "=", "self", ".", "classifier", ".", "predict", "(", "pixels", ")", "return", "predictions", ".", "reshape", "(", "X", ...
Predicts class label for the entire image. :param X: Array of images to be classified. :type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands] :return: raster classification map :rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x]
[ "Predicts", "class", "label", "for", "the", "entire", "image", "." ]
7130a4a6af90a92f28592d11da692bbb0dc1dc01
https://github.com/sentinel-hub/sentinel2-cloud-detector/blob/7130a4a6af90a92f28592d11da692bbb0dc1dc01/s2cloudless/PixelClassifier.py#L64-L79
232,526
sentinel-hub/sentinel2-cloud-detector
s2cloudless/PixelClassifier.py
PixelClassifier.image_predict_proba
def image_predict_proba(self, X): """ Predicts class probabilities for the entire image. :param X: Array of images to be classified. :type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands] :return: classification probability map :rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x] """ pixels = self.extract_pixels(X) probabilities = self.classifier.predict_proba(pixels) return probabilities.reshape(X.shape[0], X.shape[1], X.shape[2], probabilities.shape[1])
python
def image_predict_proba(self, X): pixels = self.extract_pixels(X) probabilities = self.classifier.predict_proba(pixels) return probabilities.reshape(X.shape[0], X.shape[1], X.shape[2], probabilities.shape[1])
[ "def", "image_predict_proba", "(", "self", ",", "X", ")", ":", "pixels", "=", "self", ".", "extract_pixels", "(", "X", ")", "probabilities", "=", "self", ".", "classifier", ".", "predict_proba", "(", "pixels", ")", "return", "probabilities", ".", "reshape", ...
Predicts class probabilities for the entire image. :param X: Array of images to be classified. :type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands] :return: classification probability map :rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x]
[ "Predicts", "class", "probabilities", "for", "the", "entire", "image", "." ]
7130a4a6af90a92f28592d11da692bbb0dc1dc01
https://github.com/sentinel-hub/sentinel2-cloud-detector/blob/7130a4a6af90a92f28592d11da692bbb0dc1dc01/s2cloudless/PixelClassifier.py#L81-L96
232,527
sentinel-hub/sentinel2-cloud-detector
s2cloudless/S2PixelCloudDetector.py
CloudMaskRequest._prepare_ogc_request_params
def _prepare_ogc_request_params(self): """ Method makes sure that correct parameters will be used for download of S-2 bands. """ self.ogc_request.image_format = MimeType.TIFF_d32f if self.ogc_request.custom_url_params is None: self.ogc_request.custom_url_params = {} self.ogc_request.custom_url_params.update({ CustomUrlParam.SHOWLOGO: False, CustomUrlParam.TRANSPARENT: True, CustomUrlParam.EVALSCRIPT: S2_BANDS_EVALSCRIPT if self.all_bands else MODEL_EVALSCRIPT, CustomUrlParam.ATMFILTER: 'NONE' }) self.ogc_request.create_request(reset_wfs_iterator=False)
python
def _prepare_ogc_request_params(self): self.ogc_request.image_format = MimeType.TIFF_d32f if self.ogc_request.custom_url_params is None: self.ogc_request.custom_url_params = {} self.ogc_request.custom_url_params.update({ CustomUrlParam.SHOWLOGO: False, CustomUrlParam.TRANSPARENT: True, CustomUrlParam.EVALSCRIPT: S2_BANDS_EVALSCRIPT if self.all_bands else MODEL_EVALSCRIPT, CustomUrlParam.ATMFILTER: 'NONE' }) self.ogc_request.create_request(reset_wfs_iterator=False)
[ "def", "_prepare_ogc_request_params", "(", "self", ")", ":", "self", ".", "ogc_request", ".", "image_format", "=", "MimeType", ".", "TIFF_d32f", "if", "self", ".", "ogc_request", ".", "custom_url_params", "is", "None", ":", "self", ".", "ogc_request", ".", "cu...
Method makes sure that correct parameters will be used for download of S-2 bands.
[ "Method", "makes", "sure", "that", "correct", "parameters", "will", "be", "used", "for", "download", "of", "S", "-", "2", "bands", "." ]
7130a4a6af90a92f28592d11da692bbb0dc1dc01
https://github.com/sentinel-hub/sentinel2-cloud-detector/blob/7130a4a6af90a92f28592d11da692bbb0dc1dc01/s2cloudless/S2PixelCloudDetector.py#L197-L209
232,528
sentinel-hub/sentinel2-cloud-detector
s2cloudless/S2PixelCloudDetector.py
CloudMaskRequest._set_band_and_valid_mask
def _set_band_and_valid_mask(self): """ Downloads band data and valid mask. Sets parameters self.bands, self.valid_data """ data = np.asarray(self.ogc_request.get_data()) self.bands = data[..., :-1] self.valid_data = (data[..., -1] == 1.0).astype(np.bool)
python
def _set_band_and_valid_mask(self): data = np.asarray(self.ogc_request.get_data()) self.bands = data[..., :-1] self.valid_data = (data[..., -1] == 1.0).astype(np.bool)
[ "def", "_set_band_and_valid_mask", "(", "self", ")", ":", "data", "=", "np", ".", "asarray", "(", "self", ".", "ogc_request", ".", "get_data", "(", ")", ")", "self", ".", "bands", "=", "data", "[", "...", ",", ":", "-", "1", "]", "self", ".", "vali...
Downloads band data and valid mask. Sets parameters self.bands, self.valid_data
[ "Downloads", "band", "data", "and", "valid", "mask", ".", "Sets", "parameters", "self", ".", "bands", "self", ".", "valid_data" ]
7130a4a6af90a92f28592d11da692bbb0dc1dc01
https://github.com/sentinel-hub/sentinel2-cloud-detector/blob/7130a4a6af90a92f28592d11da692bbb0dc1dc01/s2cloudless/S2PixelCloudDetector.py#L249-L254
232,529
sentinel-hub/sentinel2-cloud-detector
s2cloudless/S2PixelCloudDetector.py
CloudMaskRequest.get_probability_masks
def get_probability_masks(self, non_valid_value=0): """ Get probability maps of areas for each available date. The pixels without valid data are assigned non_valid_value. :param non_valid_value: Value to be assigned to non valid data pixels :type non_valid_value: float :return: Probability map of shape `(times, height, width)` and `dtype=numpy.float64` :rtype: numpy.ndarray """ if self.probability_masks is None: self.get_data() self.probability_masks = self.cloud_detector.get_cloud_probability_maps(self.bands) self.probability_masks[~self.valid_data] = non_valid_value return self.probability_masks
python
def get_probability_masks(self, non_valid_value=0): if self.probability_masks is None: self.get_data() self.probability_masks = self.cloud_detector.get_cloud_probability_maps(self.bands) self.probability_masks[~self.valid_data] = non_valid_value return self.probability_masks
[ "def", "get_probability_masks", "(", "self", ",", "non_valid_value", "=", "0", ")", ":", "if", "self", ".", "probability_masks", "is", "None", ":", "self", ".", "get_data", "(", ")", "self", ".", "probability_masks", "=", "self", ".", "cloud_detector", ".", ...
Get probability maps of areas for each available date. The pixels without valid data are assigned non_valid_value. :param non_valid_value: Value to be assigned to non valid data pixels :type non_valid_value: float :return: Probability map of shape `(times, height, width)` and `dtype=numpy.float64` :rtype: numpy.ndarray
[ "Get", "probability", "maps", "of", "areas", "for", "each", "available", "date", ".", "The", "pixels", "without", "valid", "data", "are", "assigned", "non_valid_value", "." ]
7130a4a6af90a92f28592d11da692bbb0dc1dc01
https://github.com/sentinel-hub/sentinel2-cloud-detector/blob/7130a4a6af90a92f28592d11da692bbb0dc1dc01/s2cloudless/S2PixelCloudDetector.py#L256-L271
232,530
sentinel-hub/sentinel2-cloud-detector
s2cloudless/S2PixelCloudDetector.py
CloudMaskRequest.get_cloud_masks
def get_cloud_masks(self, threshold=None, non_valid_value=False): """ The binary cloud mask is computed on the fly. Be cautious. The pixels without valid data are assigned non_valid_value. :param threshold: A float from [0,1] specifying threshold :type threshold: float :param non_valid_value: Value which will be assigned to pixels without valid data :type non_valid_value: int in range `[-254, 255]` :return: Binary cloud masks of shape `(times, height, width)` and `dtype=numpy.int8` :rtype: numpy.ndarray """ self.get_probability_masks() cloud_masks = self.cloud_detector.get_mask_from_prob(self.probability_masks, threshold) cloud_masks[~self.valid_data] = non_valid_value return cloud_masks
python
def get_cloud_masks(self, threshold=None, non_valid_value=False): self.get_probability_masks() cloud_masks = self.cloud_detector.get_mask_from_prob(self.probability_masks, threshold) cloud_masks[~self.valid_data] = non_valid_value return cloud_masks
[ "def", "get_cloud_masks", "(", "self", ",", "threshold", "=", "None", ",", "non_valid_value", "=", "False", ")", ":", "self", ".", "get_probability_masks", "(", ")", "cloud_masks", "=", "self", ".", "cloud_detector", ".", "get_mask_from_prob", "(", "self", "."...
The binary cloud mask is computed on the fly. Be cautious. The pixels without valid data are assigned non_valid_value. :param threshold: A float from [0,1] specifying threshold :type threshold: float :param non_valid_value: Value which will be assigned to pixels without valid data :type non_valid_value: int in range `[-254, 255]` :return: Binary cloud masks of shape `(times, height, width)` and `dtype=numpy.int8` :rtype: numpy.ndarray
[ "The", "binary", "cloud", "mask", "is", "computed", "on", "the", "fly", ".", "Be", "cautious", ".", "The", "pixels", "without", "valid", "data", "are", "assigned", "non_valid_value", "." ]
7130a4a6af90a92f28592d11da692bbb0dc1dc01
https://github.com/sentinel-hub/sentinel2-cloud-detector/blob/7130a4a6af90a92f28592d11da692bbb0dc1dc01/s2cloudless/S2PixelCloudDetector.py#L273-L289
232,531
IdentityPython/pysaml2
src/saml2/client_base.py
Base.add_vo_information_about_user
def add_vo_information_about_user(self, name_id): """ Add information to the knowledge I have about the user. This is for Virtual organizations. :param name_id: The subject identifier :return: A possibly extended knowledge. """ ava = {} try: (ava, _) = self.users.get_identity(name_id) except KeyError: pass # is this a Virtual Organization situation if self.vorg: if self.vorg.do_aggregation(name_id): # Get the extended identity ava = self.users.get_identity(name_id)[0] return ava
python
def add_vo_information_about_user(self, name_id): ava = {} try: (ava, _) = self.users.get_identity(name_id) except KeyError: pass # is this a Virtual Organization situation if self.vorg: if self.vorg.do_aggregation(name_id): # Get the extended identity ava = self.users.get_identity(name_id)[0] return ava
[ "def", "add_vo_information_about_user", "(", "self", ",", "name_id", ")", ":", "ava", "=", "{", "}", "try", ":", "(", "ava", ",", "_", ")", "=", "self", ".", "users", ".", "get_identity", "(", "name_id", ")", "except", "KeyError", ":", "pass", "# is th...
Add information to the knowledge I have about the user. This is for Virtual organizations. :param name_id: The subject identifier :return: A possibly extended knowledge.
[ "Add", "information", "to", "the", "knowledge", "I", "have", "about", "the", "user", ".", "This", "is", "for", "Virtual", "organizations", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client_base.py#L197-L216
232,532
IdentityPython/pysaml2
src/saml2/client_base.py
Base.create_attribute_query
def create_attribute_query(self, destination, name_id=None, attribute=None, message_id=0, consent=None, extensions=None, sign=False, sign_prepare=False, sign_alg=None, digest_alg=None, **kwargs): """ Constructs an AttributeQuery :param destination: To whom the query should be sent :param name_id: The identifier of the subject :param attribute: A dictionary of attributes and values that is asked for. The key are one of 4 variants: 3-tuple of name_format,name and friendly_name, 2-tuple of name_format and name, 1-tuple with name or just the name as a string. :param sp_name_qualifier: The unique identifier of the service provider or affiliation of providers for whom the identifier was generated. :param name_qualifier: The unique identifier of the identity provider that generated the identifier. :param format: The format of the name ID :param message_id: The identifier of the session :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the query should be signed or not. :param sign_prepare: Whether the Signature element should be added. :return: Tuple of request ID and an AttributeQuery instance """ if name_id is None: if "subject_id" in kwargs: name_id = saml.NameID(text=kwargs["subject_id"]) for key in ["sp_name_qualifier", "name_qualifier", "format"]: try: setattr(name_id, key, kwargs[key]) except KeyError: pass else: raise AttributeError("Missing required parameter") elif isinstance(name_id, six.string_types): name_id = saml.NameID(text=name_id) for key in ["sp_name_qualifier", "name_qualifier", "format"]: try: setattr(name_id, key, kwargs[key]) except KeyError: pass subject = saml.Subject(name_id=name_id) if attribute: attribute = do_attributes(attribute) try: nsprefix = kwargs["nsprefix"] except KeyError: nsprefix = None return self._message(AttributeQuery, destination, message_id, consent, extensions, sign, sign_prepare, subject=subject, attribute=attribute, nsprefix=nsprefix, sign_alg=sign_alg, digest_alg=digest_alg)
python
def create_attribute_query(self, destination, name_id=None, attribute=None, message_id=0, consent=None, extensions=None, sign=False, sign_prepare=False, sign_alg=None, digest_alg=None, **kwargs): if name_id is None: if "subject_id" in kwargs: name_id = saml.NameID(text=kwargs["subject_id"]) for key in ["sp_name_qualifier", "name_qualifier", "format"]: try: setattr(name_id, key, kwargs[key]) except KeyError: pass else: raise AttributeError("Missing required parameter") elif isinstance(name_id, six.string_types): name_id = saml.NameID(text=name_id) for key in ["sp_name_qualifier", "name_qualifier", "format"]: try: setattr(name_id, key, kwargs[key]) except KeyError: pass subject = saml.Subject(name_id=name_id) if attribute: attribute = do_attributes(attribute) try: nsprefix = kwargs["nsprefix"] except KeyError: nsprefix = None return self._message(AttributeQuery, destination, message_id, consent, extensions, sign, sign_prepare, subject=subject, attribute=attribute, nsprefix=nsprefix, sign_alg=sign_alg, digest_alg=digest_alg)
[ "def", "create_attribute_query", "(", "self", ",", "destination", ",", "name_id", "=", "None", ",", "attribute", "=", "None", ",", "message_id", "=", "0", ",", "consent", "=", "None", ",", "extensions", "=", "None", ",", "sign", "=", "False", ",", "sign_...
Constructs an AttributeQuery :param destination: To whom the query should be sent :param name_id: The identifier of the subject :param attribute: A dictionary of attributes and values that is asked for. The key are one of 4 variants: 3-tuple of name_format,name and friendly_name, 2-tuple of name_format and name, 1-tuple with name or just the name as a string. :param sp_name_qualifier: The unique identifier of the service provider or affiliation of providers for whom the identifier was generated. :param name_qualifier: The unique identifier of the identity provider that generated the identifier. :param format: The format of the name ID :param message_id: The identifier of the session :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the query should be signed or not. :param sign_prepare: Whether the Signature element should be added. :return: Tuple of request ID and an AttributeQuery instance
[ "Constructs", "an", "AttributeQuery" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client_base.py#L470-L531
232,533
IdentityPython/pysaml2
src/saml2/client_base.py
Base.create_authz_decision_query
def create_authz_decision_query(self, destination, action, evidence=None, resource=None, subject=None, message_id=0, consent=None, extensions=None, sign=None, sign_alg=None, digest_alg=None, **kwargs): """ Creates an authz decision query. :param destination: The IdP endpoint :param action: The action you want to perform (has to be at least one) :param evidence: Why you should be able to perform the action :param resource: The resource you want to perform the action on :param subject: Who wants to do the thing :param message_id: Message identifier :param consent: If the principal gave her consent to this request :param extensions: Possible request extensions :param sign: Whether the request should be signed or not. :return: AuthzDecisionQuery instance """ return self._message(AuthzDecisionQuery, destination, message_id, consent, extensions, sign, action=action, evidence=evidence, resource=resource, subject=subject, sign_alg=sign_alg, digest_alg=digest_alg, **kwargs)
python
def create_authz_decision_query(self, destination, action, evidence=None, resource=None, subject=None, message_id=0, consent=None, extensions=None, sign=None, sign_alg=None, digest_alg=None, **kwargs): return self._message(AuthzDecisionQuery, destination, message_id, consent, extensions, sign, action=action, evidence=evidence, resource=resource, subject=subject, sign_alg=sign_alg, digest_alg=digest_alg, **kwargs)
[ "def", "create_authz_decision_query", "(", "self", ",", "destination", ",", "action", ",", "evidence", "=", "None", ",", "resource", "=", "None", ",", "subject", "=", "None", ",", "message_id", "=", "0", ",", "consent", "=", "None", ",", "extensions", "=",...
Creates an authz decision query. :param destination: The IdP endpoint :param action: The action you want to perform (has to be at least one) :param evidence: Why you should be able to perform the action :param resource: The resource you want to perform the action on :param subject: Who wants to do the thing :param message_id: Message identifier :param consent: If the principal gave her consent to this request :param extensions: Possible request extensions :param sign: Whether the request should be signed or not. :return: AuthzDecisionQuery instance
[ "Creates", "an", "authz", "decision", "query", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client_base.py#L536-L558
232,534
IdentityPython/pysaml2
src/saml2/client_base.py
Base.create_authz_decision_query_using_assertion
def create_authz_decision_query_using_assertion(self, destination, assertion, action=None, resource=None, subject=None, message_id=0, consent=None, extensions=None, sign=False, nsprefix=None): """ Makes an authz decision query based on a previously received Assertion. :param destination: The IdP endpoint to send the request to :param assertion: An Assertion instance :param action: The action you want to perform (has to be at least one) :param resource: The resource you want to perform the action on :param subject: Who wants to do the thing :param message_id: Message identifier :param consent: If the principal gave her consent to this request :param extensions: Possible request extensions :param sign: Whether the request should be signed or not. :return: AuthzDecisionQuery instance """ if action: if isinstance(action, six.string_types): _action = [saml.Action(text=action)] else: _action = [saml.Action(text=a) for a in action] else: _action = None return self.create_authz_decision_query( destination, _action, saml.Evidence(assertion=assertion), resource, subject, message_id=message_id, consent=consent, extensions=extensions, sign=sign, nsprefix=nsprefix)
python
def create_authz_decision_query_using_assertion(self, destination, assertion, action=None, resource=None, subject=None, message_id=0, consent=None, extensions=None, sign=False, nsprefix=None): if action: if isinstance(action, six.string_types): _action = [saml.Action(text=action)] else: _action = [saml.Action(text=a) for a in action] else: _action = None return self.create_authz_decision_query( destination, _action, saml.Evidence(assertion=assertion), resource, subject, message_id=message_id, consent=consent, extensions=extensions, sign=sign, nsprefix=nsprefix)
[ "def", "create_authz_decision_query_using_assertion", "(", "self", ",", "destination", ",", "assertion", ",", "action", "=", "None", ",", "resource", "=", "None", ",", "subject", "=", "None", ",", "message_id", "=", "0", ",", "consent", "=", "None", ",", "ex...
Makes an authz decision query based on a previously received Assertion. :param destination: The IdP endpoint to send the request to :param assertion: An Assertion instance :param action: The action you want to perform (has to be at least one) :param resource: The resource you want to perform the action on :param subject: Who wants to do the thing :param message_id: Message identifier :param consent: If the principal gave her consent to this request :param extensions: Possible request extensions :param sign: Whether the request should be signed or not. :return: AuthzDecisionQuery instance
[ "Makes", "an", "authz", "decision", "query", "based", "on", "a", "previously", "received", "Assertion", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client_base.py#L560-L593
232,535
IdentityPython/pysaml2
src/saml2/client_base.py
Base.parse_authn_request_response
def parse_authn_request_response(self, xmlstr, binding, outstanding=None, outstanding_certs=None, conv_info=None): """ Deal with an AuthnResponse :param xmlstr: The reply as a xml string :param binding: Which binding that was used for the transport :param outstanding: A dictionary with session IDs as keys and the original web request from the user before redirection as values. :param outstanding_certs: :param conv_info: Information about the conversation. :return: An response.AuthnResponse or None """ if not getattr(self.config, 'entityid', None): raise SAMLError("Missing entity_id specification") if not xmlstr: return None kwargs = { "outstanding_queries": outstanding, "outstanding_certs": outstanding_certs, "allow_unsolicited": self.allow_unsolicited, "want_assertions_signed": self.want_assertions_signed, "want_assertions_or_response_signed": self.want_assertions_or_response_signed, "want_response_signed": self.want_response_signed, "return_addrs": self.service_urls(binding=binding), "entity_id": self.config.entityid, "attribute_converters": self.config.attribute_converters, "allow_unknown_attributes": self.config.allow_unknown_attributes, 'conv_info': conv_info } try: resp = self._parse_response(xmlstr, AuthnResponse, "assertion_consumer_service", binding, **kwargs) except StatusError as err: logger.error("SAML status error: %s", err) raise except UnravelError: return None except Exception as err: logger.error("XML parse error: %s", err) raise if not isinstance(resp, AuthnResponse): logger.error("Response type not supported: %s", saml2.class_name(resp)) return None if (resp.assertion and len(resp.response.encrypted_assertion) == 0 and resp.assertion.subject.name_id): self.users.add_information_about_person(resp.session_info()) logger.info("--- ADDED person info ----") return resp
python
def parse_authn_request_response(self, xmlstr, binding, outstanding=None, outstanding_certs=None, conv_info=None): if not getattr(self.config, 'entityid', None): raise SAMLError("Missing entity_id specification") if not xmlstr: return None kwargs = { "outstanding_queries": outstanding, "outstanding_certs": outstanding_certs, "allow_unsolicited": self.allow_unsolicited, "want_assertions_signed": self.want_assertions_signed, "want_assertions_or_response_signed": self.want_assertions_or_response_signed, "want_response_signed": self.want_response_signed, "return_addrs": self.service_urls(binding=binding), "entity_id": self.config.entityid, "attribute_converters": self.config.attribute_converters, "allow_unknown_attributes": self.config.allow_unknown_attributes, 'conv_info': conv_info } try: resp = self._parse_response(xmlstr, AuthnResponse, "assertion_consumer_service", binding, **kwargs) except StatusError as err: logger.error("SAML status error: %s", err) raise except UnravelError: return None except Exception as err: logger.error("XML parse error: %s", err) raise if not isinstance(resp, AuthnResponse): logger.error("Response type not supported: %s", saml2.class_name(resp)) return None if (resp.assertion and len(resp.response.encrypted_assertion) == 0 and resp.assertion.subject.name_id): self.users.add_information_about_person(resp.session_info()) logger.info("--- ADDED person info ----") return resp
[ "def", "parse_authn_request_response", "(", "self", ",", "xmlstr", ",", "binding", ",", "outstanding", "=", "None", ",", "outstanding_certs", "=", "None", ",", "conv_info", "=", "None", ")", ":", "if", "not", "getattr", "(", "self", ".", "config", ",", "'e...
Deal with an AuthnResponse :param xmlstr: The reply as a xml string :param binding: Which binding that was used for the transport :param outstanding: A dictionary with session IDs as keys and the original web request from the user before redirection as values. :param outstanding_certs: :param conv_info: Information about the conversation. :return: An response.AuthnResponse or None
[ "Deal", "with", "an", "AuthnResponse" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client_base.py#L675-L733
232,536
IdentityPython/pysaml2
src/saml2/client_base.py
Base.create_discovery_service_request
def create_discovery_service_request(url, entity_id, **kwargs): """ Created the HTTP redirect URL needed to send the user to the discovery service. :param url: The URL of the discovery service :param entity_id: The unique identifier of the service provider :param return: The discovery service MUST redirect the user agent to this location in response to this request :param policy: A parameter name used to indicate the desired behavior controlling the processing of the discovery service :param returnIDParam: A parameter name used to return the unique identifier of the selected identity provider to the original requester. :param isPassive: A boolean value True/False that controls whether the discovery service is allowed to visibly interact with the user agent. :return: A URL """ args = {"entityID": entity_id} for key in ["policy", "returnIDParam"]: try: args[key] = kwargs[key] except KeyError: pass try: args["return"] = kwargs["return_url"] except KeyError: try: args["return"] = kwargs["return"] except KeyError: pass if "isPassive" in kwargs: if kwargs["isPassive"]: args["isPassive"] = "true" else: args["isPassive"] = "false" params = urlencode(args) return "%s?%s" % (url, params)
python
def create_discovery_service_request(url, entity_id, **kwargs): args = {"entityID": entity_id} for key in ["policy", "returnIDParam"]: try: args[key] = kwargs[key] except KeyError: pass try: args["return"] = kwargs["return_url"] except KeyError: try: args["return"] = kwargs["return"] except KeyError: pass if "isPassive" in kwargs: if kwargs["isPassive"]: args["isPassive"] = "true" else: args["isPassive"] = "false" params = urlencode(args) return "%s?%s" % (url, params)
[ "def", "create_discovery_service_request", "(", "url", ",", "entity_id", ",", "*", "*", "kwargs", ")", ":", "args", "=", "{", "\"entityID\"", ":", "entity_id", "}", "for", "key", "in", "[", "\"policy\"", ",", "\"returnIDParam\"", "]", ":", "try", ":", "arg...
Created the HTTP redirect URL needed to send the user to the discovery service. :param url: The URL of the discovery service :param entity_id: The unique identifier of the service provider :param return: The discovery service MUST redirect the user agent to this location in response to this request :param policy: A parameter name used to indicate the desired behavior controlling the processing of the discovery service :param returnIDParam: A parameter name used to return the unique identifier of the selected identity provider to the original requester. :param isPassive: A boolean value True/False that controls whether the discovery service is allowed to visibly interact with the user agent. :return: A URL
[ "Created", "the", "HTTP", "redirect", "URL", "needed", "to", "send", "the", "user", "to", "the", "discovery", "service", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client_base.py#L892-L934
232,537
IdentityPython/pysaml2
src/saml2/client_base.py
Base.parse_discovery_service_response
def parse_discovery_service_response(url="", query="", returnIDParam="entityID"): """ Deal with the response url from a Discovery Service :param url: the url the user was redirected back to or :param query: just the query part of the URL. :param returnIDParam: This is where the identifier of the IdP is place if it was specified in the query. Default is 'entityID' :return: The IdP identifier or "" if none was given """ if url: part = urlparse(url) qsd = parse_qs(part[4]) elif query: qsd = parse_qs(query) else: qsd = {} try: return qsd[returnIDParam][0] except KeyError: return ""
python
def parse_discovery_service_response(url="", query="", returnIDParam="entityID"): if url: part = urlparse(url) qsd = parse_qs(part[4]) elif query: qsd = parse_qs(query) else: qsd = {} try: return qsd[returnIDParam][0] except KeyError: return ""
[ "def", "parse_discovery_service_response", "(", "url", "=", "\"\"", ",", "query", "=", "\"\"", ",", "returnIDParam", "=", "\"entityID\"", ")", ":", "if", "url", ":", "part", "=", "urlparse", "(", "url", ")", "qsd", "=", "parse_qs", "(", "part", "[", "4",...
Deal with the response url from a Discovery Service :param url: the url the user was redirected back to or :param query: just the query part of the URL. :param returnIDParam: This is where the identifier of the IdP is place if it was specified in the query. Default is 'entityID' :return: The IdP identifier or "" if none was given
[ "Deal", "with", "the", "response", "url", "from", "a", "Discovery", "Service" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client_base.py#L937-L960
232,538
IdentityPython/pysaml2
src/saml2/assertion.py
filter_on_demands
def filter_on_demands(ava, required=None, optional=None): """ Never return more than is needed. Filters out everything the server is prepared to return but the receiver doesn't ask for :param ava: Attribute value assertion as a dictionary :param required: Required attributes :param optional: Optional attributes :return: The possibly reduced assertion """ # Is all what's required there: if required is None: required = {} lava = dict([(k.lower(), k) for k in ava.keys()]) for attr, vals in required.items(): attr = attr.lower() if attr in lava: if vals: for val in vals: if val not in ava[lava[attr]]: raise MissingValue( "Required attribute value missing: %s,%s" % (attr, val)) else: raise MissingValue("Required attribute missing: %s" % (attr,)) if optional is None: optional = {} oka = [k.lower() for k in required.keys()] oka.extend([k.lower() for k in optional.keys()]) # OK, so I can imaging releasing values that are not absolutely necessary # but not attributes that are not asked for. for attr in lava.keys(): if attr not in oka: del ava[lava[attr]] return ava
python
def filter_on_demands(ava, required=None, optional=None): # Is all what's required there: if required is None: required = {} lava = dict([(k.lower(), k) for k in ava.keys()]) for attr, vals in required.items(): attr = attr.lower() if attr in lava: if vals: for val in vals: if val not in ava[lava[attr]]: raise MissingValue( "Required attribute value missing: %s,%s" % (attr, val)) else: raise MissingValue("Required attribute missing: %s" % (attr,)) if optional is None: optional = {} oka = [k.lower() for k in required.keys()] oka.extend([k.lower() for k in optional.keys()]) # OK, so I can imaging releasing values that are not absolutely necessary # but not attributes that are not asked for. for attr in lava.keys(): if attr not in oka: del ava[lava[attr]] return ava
[ "def", "filter_on_demands", "(", "ava", ",", "required", "=", "None", ",", "optional", "=", "None", ")", ":", "# Is all what's required there:", "if", "required", "is", "None", ":", "required", "=", "{", "}", "lava", "=", "dict", "(", "[", "(", "k", ".",...
Never return more than is needed. Filters out everything the server is prepared to return but the receiver doesn't ask for :param ava: Attribute value assertion as a dictionary :param required: Required attributes :param optional: Optional attributes :return: The possibly reduced assertion
[ "Never", "return", "more", "than", "is", "needed", ".", "Filters", "out", "everything", "the", "server", "is", "prepared", "to", "return", "but", "the", "receiver", "doesn", "t", "ask", "for" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/assertion.py#L144-L184
232,539
IdentityPython/pysaml2
src/saml2/assertion.py
filter_attribute_value_assertions
def filter_attribute_value_assertions(ava, attribute_restrictions=None): """ Will weed out attribute values and values according to the rules defined in the attribute restrictions. If filtering results in an attribute without values, then the attribute is removed from the assertion. :param ava: The incoming attribute value assertion (dictionary) :param attribute_restrictions: The rules that govern which attributes and values that are allowed. (dictionary) :return: The modified attribute value assertion """ if not attribute_restrictions: return ava for attr, vals in list(ava.items()): _attr = attr.lower() try: _rests = attribute_restrictions[_attr] except KeyError: del ava[attr] else: if _rests is None: continue if isinstance(vals, six.string_types): vals = [vals] rvals = [] for restr in _rests: for val in vals: if restr.match(val): rvals.append(val) if rvals: ava[attr] = list(set(rvals)) else: del ava[attr] return ava
python
def filter_attribute_value_assertions(ava, attribute_restrictions=None): if not attribute_restrictions: return ava for attr, vals in list(ava.items()): _attr = attr.lower() try: _rests = attribute_restrictions[_attr] except KeyError: del ava[attr] else: if _rests is None: continue if isinstance(vals, six.string_types): vals = [vals] rvals = [] for restr in _rests: for val in vals: if restr.match(val): rvals.append(val) if rvals: ava[attr] = list(set(rvals)) else: del ava[attr] return ava
[ "def", "filter_attribute_value_assertions", "(", "ava", ",", "attribute_restrictions", "=", "None", ")", ":", "if", "not", "attribute_restrictions", ":", "return", "ava", "for", "attr", ",", "vals", "in", "list", "(", "ava", ".", "items", "(", ")", ")", ":",...
Will weed out attribute values and values according to the rules defined in the attribute restrictions. If filtering results in an attribute without values, then the attribute is removed from the assertion. :param ava: The incoming attribute value assertion (dictionary) :param attribute_restrictions: The rules that govern which attributes and values that are allowed. (dictionary) :return: The modified attribute value assertion
[ "Will", "weed", "out", "attribute", "values", "and", "values", "according", "to", "the", "rules", "defined", "in", "the", "attribute", "restrictions", ".", "If", "filtering", "results", "in", "an", "attribute", "without", "values", "then", "the", "attribute", ...
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/assertion.py#L228-L263
232,540
IdentityPython/pysaml2
src/saml2/assertion.py
Policy.compile
def compile(self, restrictions): """ This is only for IdPs or AAs, and it's about limiting what is returned to the SP. In the configuration file, restrictions on which values that can be returned are specified with the help of regular expressions. This function goes through and pre-compiles the regular expressions. :param restrictions: :return: The assertion with the string specification replaced with a compiled regular expression. """ self._restrictions = copy.deepcopy(restrictions) for who, spec in self._restrictions.items(): if spec is None: continue try: items = spec["entity_categories"] except KeyError: pass else: ecs = [] for cat in items: _mod = importlib.import_module( "saml2.entity_category.%s" % cat) _ec = {} for key, items in _mod.RELEASE.items(): alist = [k.lower() for k in items] try: _only_required = _mod.ONLY_REQUIRED[key] except (AttributeError, KeyError): _only_required = False _ec[key] = (alist, _only_required) ecs.append(_ec) spec["entity_categories"] = ecs try: restr = spec["attribute_restrictions"] except KeyError: continue if restr is None: continue _are = {} for key, values in restr.items(): if not values: _are[key.lower()] = None continue _are[key.lower()] = [re.compile(value) for value in values] spec["attribute_restrictions"] = _are logger.debug("policy restrictions: %s", self._restrictions) return self._restrictions
python
def compile(self, restrictions): self._restrictions = copy.deepcopy(restrictions) for who, spec in self._restrictions.items(): if spec is None: continue try: items = spec["entity_categories"] except KeyError: pass else: ecs = [] for cat in items: _mod = importlib.import_module( "saml2.entity_category.%s" % cat) _ec = {} for key, items in _mod.RELEASE.items(): alist = [k.lower() for k in items] try: _only_required = _mod.ONLY_REQUIRED[key] except (AttributeError, KeyError): _only_required = False _ec[key] = (alist, _only_required) ecs.append(_ec) spec["entity_categories"] = ecs try: restr = spec["attribute_restrictions"] except KeyError: continue if restr is None: continue _are = {} for key, values in restr.items(): if not values: _are[key.lower()] = None continue _are[key.lower()] = [re.compile(value) for value in values] spec["attribute_restrictions"] = _are logger.debug("policy restrictions: %s", self._restrictions) return self._restrictions
[ "def", "compile", "(", "self", ",", "restrictions", ")", ":", "self", ".", "_restrictions", "=", "copy", ".", "deepcopy", "(", "restrictions", ")", "for", "who", ",", "spec", "in", "self", ".", "_restrictions", ".", "items", "(", ")", ":", "if", "spec"...
This is only for IdPs or AAs, and it's about limiting what is returned to the SP. In the configuration file, restrictions on which values that can be returned are specified with the help of regular expressions. This function goes through and pre-compiles the regular expressions. :param restrictions: :return: The assertion with the string specification replaced with a compiled regular expression.
[ "This", "is", "only", "for", "IdPs", "or", "AAs", "and", "it", "s", "about", "limiting", "what", "is", "returned", "to", "the", "SP", ".", "In", "the", "configuration", "file", "restrictions", "on", "which", "values", "that", "can", "be", "returned", "ar...
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/assertion.py#L332-L386
232,541
IdentityPython/pysaml2
src/saml2/assertion.py
Policy.conditions
def conditions(self, sp_entity_id): """ Return a saml.Condition instance :param sp_entity_id: The SP entity ID :return: A saml.Condition instance """ return factory(saml.Conditions, not_before=instant(), # How long might depend on who's getting it not_on_or_after=self.not_on_or_after(sp_entity_id), audience_restriction=[factory( saml.AudienceRestriction, audience=[factory(saml.Audience, text=sp_entity_id)])])
python
def conditions(self, sp_entity_id): return factory(saml.Conditions, not_before=instant(), # How long might depend on who's getting it not_on_or_after=self.not_on_or_after(sp_entity_id), audience_restriction=[factory( saml.AudienceRestriction, audience=[factory(saml.Audience, text=sp_entity_id)])])
[ "def", "conditions", "(", "self", ",", "sp_entity_id", ")", ":", "return", "factory", "(", "saml", ".", "Conditions", ",", "not_before", "=", "instant", "(", ")", ",", "# How long might depend on who's getting it", "not_on_or_after", "=", "self", ".", "not_on_or_a...
Return a saml.Condition instance :param sp_entity_id: The SP entity ID :return: A saml.Condition instance
[ "Return", "a", "saml", ".", "Condition", "instance" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/assertion.py#L555-L568
232,542
IdentityPython/pysaml2
src/saml2/assertion.py
Assertion.construct
def construct(self, sp_entity_id, attrconvs, policy, issuer, farg, authn_class=None, authn_auth=None, authn_decl=None, encrypt=None, sec_context=None, authn_decl_ref=None, authn_instant="", subject_locality="", authn_statem=None, name_id=None, session_not_on_or_after=None): """ Construct the Assertion :param sp_entity_id: The entityid of the SP :param in_response_to: An identifier of the message, this message is a response to :param name_id: An NameID instance :param attrconvs: AttributeConverters :param policy: The policy that should be adhered to when replying :param issuer: Who is issuing the statement :param authn_class: The authentication class :param authn_auth: The authentication instance :param authn_decl: An Authentication Context declaration :param encrypt: Whether to encrypt parts or all of the Assertion :param sec_context: The security context used when encrypting :param authn_decl_ref: An Authentication Context declaration reference :param authn_instant: When the Authentication was performed :param subject_locality: Specifies the DNS domain name and IP address for the system from which the assertion subject was apparently authenticated. :param authn_statem: A AuthnStatement instance :return: An Assertion instance """ if policy: _name_format = policy.get_name_form(sp_entity_id) else: _name_format = NAME_FORMAT_URI attr_statement = saml.AttributeStatement(attribute=from_local( attrconvs, self, _name_format)) if encrypt == "attributes": for attr in attr_statement.attribute: enc = sec_context.encrypt(text="%s" % attr) encd = xmlenc.encrypted_data_from_string(enc) encattr = saml.EncryptedAttribute(encrypted_data=encd) attr_statement.encrypted_attribute.append(encattr) attr_statement.attribute = [] # start using now and for some time conds = policy.conditions(sp_entity_id) if authn_statem: _authn_statement = authn_statem elif authn_auth or authn_class or authn_decl or authn_decl_ref: _authn_statement = authn_statement(authn_class, authn_auth, authn_decl, authn_decl_ref, authn_instant, subject_locality, session_not_on_or_after=session_not_on_or_after) else: _authn_statement = None subject = do_subject(policy, sp_entity_id, name_id, **farg['subject']) _ass = assertion_factory(issuer=issuer, conditions=conds, subject=subject) if _authn_statement: _ass.authn_statement = [_authn_statement] if not attr_statement.empty(): _ass.attribute_statement = [attr_statement] return _ass
python
def construct(self, sp_entity_id, attrconvs, policy, issuer, farg, authn_class=None, authn_auth=None, authn_decl=None, encrypt=None, sec_context=None, authn_decl_ref=None, authn_instant="", subject_locality="", authn_statem=None, name_id=None, session_not_on_or_after=None): if policy: _name_format = policy.get_name_form(sp_entity_id) else: _name_format = NAME_FORMAT_URI attr_statement = saml.AttributeStatement(attribute=from_local( attrconvs, self, _name_format)) if encrypt == "attributes": for attr in attr_statement.attribute: enc = sec_context.encrypt(text="%s" % attr) encd = xmlenc.encrypted_data_from_string(enc) encattr = saml.EncryptedAttribute(encrypted_data=encd) attr_statement.encrypted_attribute.append(encattr) attr_statement.attribute = [] # start using now and for some time conds = policy.conditions(sp_entity_id) if authn_statem: _authn_statement = authn_statem elif authn_auth or authn_class or authn_decl or authn_decl_ref: _authn_statement = authn_statement(authn_class, authn_auth, authn_decl, authn_decl_ref, authn_instant, subject_locality, session_not_on_or_after=session_not_on_or_after) else: _authn_statement = None subject = do_subject(policy, sp_entity_id, name_id, **farg['subject']) _ass = assertion_factory(issuer=issuer, conditions=conds, subject=subject) if _authn_statement: _ass.authn_statement = [_authn_statement] if not attr_statement.empty(): _ass.attribute_statement = [attr_statement] return _ass
[ "def", "construct", "(", "self", ",", "sp_entity_id", ",", "attrconvs", ",", "policy", ",", "issuer", ",", "farg", ",", "authn_class", "=", "None", ",", "authn_auth", "=", "None", ",", "authn_decl", "=", "None", ",", "encrypt", "=", "None", ",", "sec_con...
Construct the Assertion :param sp_entity_id: The entityid of the SP :param in_response_to: An identifier of the message, this message is a response to :param name_id: An NameID instance :param attrconvs: AttributeConverters :param policy: The policy that should be adhered to when replying :param issuer: Who is issuing the statement :param authn_class: The authentication class :param authn_auth: The authentication instance :param authn_decl: An Authentication Context declaration :param encrypt: Whether to encrypt parts or all of the Assertion :param sec_context: The security context used when encrypting :param authn_decl_ref: An Authentication Context declaration reference :param authn_instant: When the Authentication was performed :param subject_locality: Specifies the DNS domain name and IP address for the system from which the assertion subject was apparently authenticated. :param authn_statem: A AuthnStatement instance :return: An Assertion instance
[ "Construct", "the", "Assertion" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/assertion.py#L736-L808
232,543
IdentityPython/pysaml2
src/saml2/assertion.py
Assertion.apply_policy
def apply_policy(self, sp_entity_id, policy, metadata=None): """ Apply policy to the assertion I'm representing :param sp_entity_id: The SP entity ID :param policy: The policy :param metadata: Metadata to use :return: The resulting AVA after the policy is applied """ policy.acs = self.acs ava = policy.restrict(self, sp_entity_id, metadata) for key, val in list(self.items()): if key in ava: self[key] = ava[key] else: del self[key] return ava
python
def apply_policy(self, sp_entity_id, policy, metadata=None): policy.acs = self.acs ava = policy.restrict(self, sp_entity_id, metadata) for key, val in list(self.items()): if key in ava: self[key] = ava[key] else: del self[key] return ava
[ "def", "apply_policy", "(", "self", ",", "sp_entity_id", ",", "policy", ",", "metadata", "=", "None", ")", ":", "policy", ".", "acs", "=", "self", ".", "acs", "ava", "=", "policy", ".", "restrict", "(", "self", ",", "sp_entity_id", ",", "metadata", ")"...
Apply policy to the assertion I'm representing :param sp_entity_id: The SP entity ID :param policy: The policy :param metadata: Metadata to use :return: The resulting AVA after the policy is applied
[ "Apply", "policy", "to", "the", "assertion", "I", "m", "representing" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/assertion.py#L810-L828
232,544
IdentityPython/pysaml2
example/sp-wsgi/sp.py
application
def application(environ, start_response): """ The main WSGI application. Dispatch the current request to the functions from above. If nothing matches, call the `not_found` function. :param environ: The HTTP application environment :param start_response: The application to run when the handling of the request is done :return: The response as a list of lines """ path = environ.get("PATH_INFO", "").lstrip("/") logger.debug("<application> PATH: '%s'", path) if path == "metadata": return metadata(environ, start_response) logger.debug("Finding callback to run") try: for regex, spec in urls: match = re.search(regex, path) if match is not None: if isinstance(spec, tuple): callback, func_name, _sp = spec cls = callback(_sp, environ, start_response, cache=CACHE) func = getattr(cls, func_name) return func() else: return spec(environ, start_response, SP) if re.match(".*static/.*", path): return handle_static(environ, start_response, path) return not_found(environ, start_response) except StatusError as err: logging.error("StatusError: %s" % err) resp = BadRequest("%s" % err) return resp(environ, start_response) except Exception as err: # _err = exception_trace("RUN", err) # logging.error(exception_trace("RUN", _err)) print(err, file=sys.stderr) resp = ServiceError("%s" % err) return resp(environ, start_response)
python
def application(environ, start_response): path = environ.get("PATH_INFO", "").lstrip("/") logger.debug("<application> PATH: '%s'", path) if path == "metadata": return metadata(environ, start_response) logger.debug("Finding callback to run") try: for regex, spec in urls: match = re.search(regex, path) if match is not None: if isinstance(spec, tuple): callback, func_name, _sp = spec cls = callback(_sp, environ, start_response, cache=CACHE) func = getattr(cls, func_name) return func() else: return spec(environ, start_response, SP) if re.match(".*static/.*", path): return handle_static(environ, start_response, path) return not_found(environ, start_response) except StatusError as err: logging.error("StatusError: %s" % err) resp = BadRequest("%s" % err) return resp(environ, start_response) except Exception as err: # _err = exception_trace("RUN", err) # logging.error(exception_trace("RUN", _err)) print(err, file=sys.stderr) resp = ServiceError("%s" % err) return resp(environ, start_response)
[ "def", "application", "(", "environ", ",", "start_response", ")", ":", "path", "=", "environ", ".", "get", "(", "\"PATH_INFO\"", ",", "\"\"", ")", ".", "lstrip", "(", "\"/\"", ")", "logger", ".", "debug", "(", "\"<application> PATH: '%s'\"", ",", "path", "...
The main WSGI application. Dispatch the current request to the functions from above. If nothing matches, call the `not_found` function. :param environ: The HTTP application environment :param start_response: The application to run when the handling of the request is done :return: The response as a list of lines
[ "The", "main", "WSGI", "application", ".", "Dispatch", "the", "current", "request", "to", "the", "functions", "from", "above", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/sp-wsgi/sp.py#L833-L875
232,545
IdentityPython/pysaml2
example/sp-wsgi/sp.py
Service.soap
def soap(self): """ Single log out using HTTP_SOAP binding """ logger.debug("- SOAP -") _dict = self.unpack_soap() logger.debug("_dict: %s", _dict) return self.operation(_dict, BINDING_SOAP)
python
def soap(self): logger.debug("- SOAP -") _dict = self.unpack_soap() logger.debug("_dict: %s", _dict) return self.operation(_dict, BINDING_SOAP)
[ "def", "soap", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"- SOAP -\"", ")", "_dict", "=", "self", ".", "unpack_soap", "(", ")", "logger", ".", "debug", "(", "\"_dict: %s\"", ",", "_dict", ")", "return", "self", ".", "operation", "(", "_dict...
Single log out using HTTP_SOAP binding
[ "Single", "log", "out", "using", "HTTP_SOAP", "binding" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/sp-wsgi/sp.py#L306-L313
232,546
IdentityPython/pysaml2
example/sp-wsgi/sp.py
SSO._pick_idp
def _pick_idp(self, came_from): """ If more than one idp and if none is selected, I have to do wayf or disco """ _cli = self.sp logger.debug("[_pick_idp] %s", self.environ) if "HTTP_PAOS" in self.environ: if self.environ["HTTP_PAOS"] == PAOS_HEADER_INFO: if MIME_PAOS in self.environ["HTTP_ACCEPT"]: # Where should I redirect the user to # entityid -> the IdP to use # relay_state -> when back from authentication logger.debug("- ECP client detected -") _rstate = rndstr() self.cache.relay_state[_rstate] = geturl(self.environ) _entityid = _cli.config.ecp_endpoint(self.environ["REMOTE_ADDR"]) if not _entityid: return -1, ServiceError("No IdP to talk to") logger.debug("IdP to talk to: %s", _entityid) return ecp.ecp_auth_request(_cli, _entityid, _rstate) else: return -1, ServiceError("Faulty Accept header") else: return -1, ServiceError("unknown ECP version") # Find all IdPs idps = self.sp.metadata.with_descriptor("idpsso") idp_entity_id = None kaka = self.environ.get("HTTP_COOKIE", "") if kaka: try: (idp_entity_id, _) = parse_cookie("ve_disco", "SEED_SAW", kaka) except ValueError: pass except TypeError: pass # Any specific IdP specified in a query part query = self.environ.get("QUERY_STRING") if not idp_entity_id and query: try: _idp_entity_id = dict(parse_qs(query))[self.idp_query_param][0] if _idp_entity_id in idps: idp_entity_id = _idp_entity_id except KeyError: logger.debug("No IdP entity ID in query: %s", query) pass if not idp_entity_id: if self.wayf: if query: try: wayf_selected = dict(parse_qs(query))["wayf_selected"][0] except KeyError: return self._wayf_redirect(came_from) idp_entity_id = wayf_selected else: return self._wayf_redirect(came_from) elif self.discosrv: if query: idp_entity_id = _cli.parse_discovery_service_response( query=self.environ.get("QUERY_STRING") ) if not idp_entity_id: sid_ = sid() self.cache.outstanding_queries[sid_] = came_from logger.debug("Redirect to Discovery Service function") eid = _cli.config.entityid ret = _cli.config.getattr("endpoints", "sp")["discovery_response"][ 0 ][0] ret += "?sid=%s" % sid_ loc = _cli.create_discovery_service_request( self.discosrv, eid, **{"return": ret} ) return -1, SeeOther(loc) elif len(idps) == 1: # idps is a dictionary idp_entity_id = list(idps.keys())[0] elif not len(idps): return -1, ServiceError("Misconfiguration") else: return -1, NotImplemented("No WAYF or DS present!") logger.info("Chosen IdP: '%s'", idp_entity_id) return 0, idp_entity_id
python
def _pick_idp(self, came_from): _cli = self.sp logger.debug("[_pick_idp] %s", self.environ) if "HTTP_PAOS" in self.environ: if self.environ["HTTP_PAOS"] == PAOS_HEADER_INFO: if MIME_PAOS in self.environ["HTTP_ACCEPT"]: # Where should I redirect the user to # entityid -> the IdP to use # relay_state -> when back from authentication logger.debug("- ECP client detected -") _rstate = rndstr() self.cache.relay_state[_rstate] = geturl(self.environ) _entityid = _cli.config.ecp_endpoint(self.environ["REMOTE_ADDR"]) if not _entityid: return -1, ServiceError("No IdP to talk to") logger.debug("IdP to talk to: %s", _entityid) return ecp.ecp_auth_request(_cli, _entityid, _rstate) else: return -1, ServiceError("Faulty Accept header") else: return -1, ServiceError("unknown ECP version") # Find all IdPs idps = self.sp.metadata.with_descriptor("idpsso") idp_entity_id = None kaka = self.environ.get("HTTP_COOKIE", "") if kaka: try: (idp_entity_id, _) = parse_cookie("ve_disco", "SEED_SAW", kaka) except ValueError: pass except TypeError: pass # Any specific IdP specified in a query part query = self.environ.get("QUERY_STRING") if not idp_entity_id and query: try: _idp_entity_id = dict(parse_qs(query))[self.idp_query_param][0] if _idp_entity_id in idps: idp_entity_id = _idp_entity_id except KeyError: logger.debug("No IdP entity ID in query: %s", query) pass if not idp_entity_id: if self.wayf: if query: try: wayf_selected = dict(parse_qs(query))["wayf_selected"][0] except KeyError: return self._wayf_redirect(came_from) idp_entity_id = wayf_selected else: return self._wayf_redirect(came_from) elif self.discosrv: if query: idp_entity_id = _cli.parse_discovery_service_response( query=self.environ.get("QUERY_STRING") ) if not idp_entity_id: sid_ = sid() self.cache.outstanding_queries[sid_] = came_from logger.debug("Redirect to Discovery Service function") eid = _cli.config.entityid ret = _cli.config.getattr("endpoints", "sp")["discovery_response"][ 0 ][0] ret += "?sid=%s" % sid_ loc = _cli.create_discovery_service_request( self.discosrv, eid, **{"return": ret} ) return -1, SeeOther(loc) elif len(idps) == 1: # idps is a dictionary idp_entity_id = list(idps.keys())[0] elif not len(idps): return -1, ServiceError("Misconfiguration") else: return -1, NotImplemented("No WAYF or DS present!") logger.info("Chosen IdP: '%s'", idp_entity_id) return 0, idp_entity_id
[ "def", "_pick_idp", "(", "self", ",", "came_from", ")", ":", "_cli", "=", "self", ".", "sp", "logger", ".", "debug", "(", "\"[_pick_idp] %s\"", ",", "self", ".", "environ", ")", "if", "\"HTTP_PAOS\"", "in", "self", ".", "environ", ":", "if", "self", "....
If more than one idp and if none is selected, I have to do wayf or disco
[ "If", "more", "than", "one", "idp", "and", "if", "none", "is", "selected", "I", "have", "to", "do", "wayf", "or", "disco" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/sp-wsgi/sp.py#L481-L575
232,547
IdentityPython/pysaml2
src/saml2/validate.py
valid_any_uri
def valid_any_uri(item): """very simplistic, ...""" try: part = urlparse(item) except Exception: raise NotValid("AnyURI") if part[0] == "urn" and part[1] == "": # A urn return True # elif part[1] == "localhost" or part[1] == "127.0.0.1": # raise NotValid("AnyURI") return True
python
def valid_any_uri(item): try: part = urlparse(item) except Exception: raise NotValid("AnyURI") if part[0] == "urn" and part[1] == "": # A urn return True # elif part[1] == "localhost" or part[1] == "127.0.0.1": # raise NotValid("AnyURI") return True
[ "def", "valid_any_uri", "(", "item", ")", ":", "try", ":", "part", "=", "urlparse", "(", "item", ")", "except", "Exception", ":", "raise", "NotValid", "(", "\"AnyURI\"", ")", "if", "part", "[", "0", "]", "==", "\"urn\"", "and", "part", "[", "1", "]",...
very simplistic, ...
[ "very", "simplistic", "..." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/validate.py#L55-L67
232,548
IdentityPython/pysaml2
src/saml2/validate.py
valid_anytype
def valid_anytype(val): """ Goes through all known type validators :param val: The value to validate :return: True is value is valid otherwise an exception is raised """ for validator in VALIDATOR.values(): if validator == valid_anytype: # To hinder recursion continue try: if validator(val): return True except NotValid: pass if isinstance(val, type): return True raise NotValid("AnyType")
python
def valid_anytype(val): for validator in VALIDATOR.values(): if validator == valid_anytype: # To hinder recursion continue try: if validator(val): return True except NotValid: pass if isinstance(val, type): return True raise NotValid("AnyType")
[ "def", "valid_anytype", "(", "val", ")", ":", "for", "validator", "in", "VALIDATOR", ".", "values", "(", ")", ":", "if", "validator", "==", "valid_anytype", ":", "# To hinder recursion", "continue", "try", ":", "if", "validator", "(", "val", ")", ":", "ret...
Goes through all known type validators :param val: The value to validate :return: True is value is valid otherwise an exception is raised
[ "Goes", "through", "all", "known", "type", "validators" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/validate.py#L268-L286
232,549
IdentityPython/pysaml2
src/saml2/attribute_converter.py
load_maps
def load_maps(dirspec): """ load the attribute maps :param dirspec: a directory specification :return: a dictionary with the name of the map as key and the map as value. The map itself is a dictionary with two keys: "to" and "fro". The values for those keys are the actual mapping. """ mapd = {} if dirspec not in sys.path: sys.path.insert(0, dirspec) for fil in os.listdir(dirspec): if fil.endswith(".py"): mod = import_module(fil[:-3]) for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: mapd[item["identifier"]] = item return mapd
python
def load_maps(dirspec): mapd = {} if dirspec not in sys.path: sys.path.insert(0, dirspec) for fil in os.listdir(dirspec): if fil.endswith(".py"): mod = import_module(fil[:-3]) for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: mapd[item["identifier"]] = item return mapd
[ "def", "load_maps", "(", "dirspec", ")", ":", "mapd", "=", "{", "}", "if", "dirspec", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "dirspec", ")", "for", "fil", "in", "os", ".", "listdir", "(", "dirspec"...
load the attribute maps :param dirspec: a directory specification :return: a dictionary with the name of the map as key and the map as value. The map itself is a dictionary with two keys: "to" and "fro". The values for those keys are the actual mapping.
[ "load", "the", "attribute", "maps" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L28-L49
232,550
IdentityPython/pysaml2
src/saml2/attribute_converter.py
ac_factory
def ac_factory(path=""): """Attribute Converter factory :param path: The path to a directory where the attribute maps are expected to reside. :return: A AttributeConverter instance """ acs = [] if path: if path not in sys.path: sys.path.insert(0, path) for fil in os.listdir(path): if fil.endswith(".py"): mod = import_module(fil[:-3]) for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: atco = AttributeConverter(item["identifier"]) atco.from_dict(item) acs.append(atco) else: from saml2 import attributemaps for typ in attributemaps.__all__: mod = import_module(".%s" % typ, "saml2.attributemaps") for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: atco = AttributeConverter(item["identifier"]) atco.from_dict(item) acs.append(atco) return acs
python
def ac_factory(path=""): acs = [] if path: if path not in sys.path: sys.path.insert(0, path) for fil in os.listdir(path): if fil.endswith(".py"): mod = import_module(fil[:-3]) for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: atco = AttributeConverter(item["identifier"]) atco.from_dict(item) acs.append(atco) else: from saml2 import attributemaps for typ in attributemaps.__all__: mod = import_module(".%s" % typ, "saml2.attributemaps") for key, item in mod.__dict__.items(): if key.startswith("__"): continue if isinstance(item, dict) and "to" in item and "fro" in item: atco = AttributeConverter(item["identifier"]) atco.from_dict(item) acs.append(atco) return acs
[ "def", "ac_factory", "(", "path", "=", "\"\"", ")", ":", "acs", "=", "[", "]", "if", "path", ":", "if", "path", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "path", ")", "for", "fil", "in", "os", "."...
Attribute Converter factory :param path: The path to a directory where the attribute maps are expected to reside. :return: A AttributeConverter instance
[ "Attribute", "Converter", "factory" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L52-L89
232,551
IdentityPython/pysaml2
src/saml2/attribute_converter.py
AttributeConverter.adjust
def adjust(self): """ If one of the transformations is not defined it is expected to be the mirror image of the other. """ if self._fro is None and self._to is not None: self._fro = dict( [(value.lower(), key) for key, value in self._to.items()]) if self._to is None and self._fro is not None: self._to = dict( [(value.lower(), key) for key, value in self._fro.items()])
python
def adjust(self): if self._fro is None and self._to is not None: self._fro = dict( [(value.lower(), key) for key, value in self._to.items()]) if self._to is None and self._fro is not None: self._to = dict( [(value.lower(), key) for key, value in self._fro.items()])
[ "def", "adjust", "(", "self", ")", ":", "if", "self", ".", "_fro", "is", "None", "and", "self", ".", "_to", "is", "not", "None", ":", "self", ".", "_fro", "=", "dict", "(", "[", "(", "value", ".", "lower", "(", ")", ",", "key", ")", "for", "k...
If one of the transformations is not defined it is expected to be the mirror image of the other.
[ "If", "one", "of", "the", "transformations", "is", "not", "defined", "it", "is", "expected", "to", "be", "the", "mirror", "image", "of", "the", "other", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L224-L234
232,552
IdentityPython/pysaml2
src/saml2/attribute_converter.py
AttributeConverter.from_dict
def from_dict(self, mapdict): """ Import the attribute map from a dictionary :param mapdict: The dictionary """ self.name_format = mapdict["identifier"] try: self._fro = dict( [(k.lower(), v) for k, v in mapdict["fro"].items()]) except KeyError: pass try: self._to = dict([(k.lower(), v) for k, v in mapdict["to"].items()]) except KeyError: pass if self._fro is None and self._to is None: raise ConverterError("Missing specifications") if self._fro is None or self._to is None: self.adjust()
python
def from_dict(self, mapdict): self.name_format = mapdict["identifier"] try: self._fro = dict( [(k.lower(), v) for k, v in mapdict["fro"].items()]) except KeyError: pass try: self._to = dict([(k.lower(), v) for k, v in mapdict["to"].items()]) except KeyError: pass if self._fro is None and self._to is None: raise ConverterError("Missing specifications") if self._fro is None or self._to is None: self.adjust()
[ "def", "from_dict", "(", "self", ",", "mapdict", ")", ":", "self", ".", "name_format", "=", "mapdict", "[", "\"identifier\"", "]", "try", ":", "self", ".", "_fro", "=", "dict", "(", "[", "(", "k", ".", "lower", "(", ")", ",", "v", ")", "for", "k"...
Import the attribute map from a dictionary :param mapdict: The dictionary
[ "Import", "the", "attribute", "map", "from", "a", "dictionary" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L236-L257
232,553
IdentityPython/pysaml2
src/saml2/attribute_converter.py
AttributeConverter.lcd_ava_from
def lcd_ava_from(self, attribute): """ If nothing else works, this should :param attribute: an Attribute instance :return: """ name = attribute.name.strip() values = [ (value.text or '').strip() for value in attribute.attribute_value] return name, values
python
def lcd_ava_from(self, attribute): name = attribute.name.strip() values = [ (value.text or '').strip() for value in attribute.attribute_value] return name, values
[ "def", "lcd_ava_from", "(", "self", ",", "attribute", ")", ":", "name", "=", "attribute", ".", "name", ".", "strip", "(", ")", "values", "=", "[", "(", "value", ".", "text", "or", "''", ")", ".", "strip", "(", ")", "for", "value", "in", "attribute"...
If nothing else works, this should :param attribute: an Attribute instance :return:
[ "If", "nothing", "else", "works", "this", "should" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L259-L270
232,554
IdentityPython/pysaml2
src/saml2/attribute_converter.py
AttributeConverter.fail_safe_fro
def fail_safe_fro(self, statement): """ In case there is not formats defined or if the name format is undefined :param statement: AttributeStatement instance :return: A dictionary with names and values """ result = {} for attribute in statement.attribute: if attribute.name_format and \ attribute.name_format != NAME_FORMAT_UNSPECIFIED: continue try: name = attribute.friendly_name.strip() except AttributeError: name = attribute.name.strip() result[name] = [] for value in attribute.attribute_value: if not value.text: result[name].append('') else: result[name].append(value.text.strip()) return result
python
def fail_safe_fro(self, statement): result = {} for attribute in statement.attribute: if attribute.name_format and \ attribute.name_format != NAME_FORMAT_UNSPECIFIED: continue try: name = attribute.friendly_name.strip() except AttributeError: name = attribute.name.strip() result[name] = [] for value in attribute.attribute_value: if not value.text: result[name].append('') else: result[name].append(value.text.strip()) return result
[ "def", "fail_safe_fro", "(", "self", ",", "statement", ")", ":", "result", "=", "{", "}", "for", "attribute", "in", "statement", ".", "attribute", ":", "if", "attribute", ".", "name_format", "and", "attribute", ".", "name_format", "!=", "NAME_FORMAT_UNSPECIFIE...
In case there is not formats defined or if the name format is undefined :param statement: AttributeStatement instance :return: A dictionary with names and values
[ "In", "case", "there", "is", "not", "formats", "defined", "or", "if", "the", "name", "format", "is", "undefined" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L272-L295
232,555
IdentityPython/pysaml2
src/saml2/attribute_converter.py
AttributeConverter.fro
def fro(self, statement): """ Get the attributes and the attribute values. :param statement: The AttributeStatement. :return: A dictionary containing attributes and values """ if not self.name_format: return self.fail_safe_fro(statement) result = {} for attribute in statement.attribute: if attribute.name_format and self.name_format and \ attribute.name_format != self.name_format: continue try: (key, val) = self.ava_from(attribute) except (KeyError, AttributeError): pass else: result[key] = val return result
python
def fro(self, statement): if not self.name_format: return self.fail_safe_fro(statement) result = {} for attribute in statement.attribute: if attribute.name_format and self.name_format and \ attribute.name_format != self.name_format: continue try: (key, val) = self.ava_from(attribute) except (KeyError, AttributeError): pass else: result[key] = val return result
[ "def", "fro", "(", "self", ",", "statement", ")", ":", "if", "not", "self", ".", "name_format", ":", "return", "self", ".", "fail_safe_fro", "(", "statement", ")", "result", "=", "{", "}", "for", "attribute", "in", "statement", ".", "attribute", ":", "...
Get the attributes and the attribute values. :param statement: The AttributeStatement. :return: A dictionary containing attributes and values
[ "Get", "the", "attributes", "and", "the", "attribute", "values", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L335-L358
232,556
IdentityPython/pysaml2
src/saml2/attribute_converter.py
AttributeConverter.to_format
def to_format(self, attr): """ Creates an Attribute instance with name, name_format and friendly_name :param attr: The local name of the attribute :return: An Attribute instance """ try: _attr = self._to[attr] except KeyError: try: _attr = self._to[attr.lower()] except: _attr = '' if _attr: return factory(saml.Attribute, name=_attr, name_format=self.name_format, friendly_name=attr) else: return factory(saml.Attribute, name=attr)
python
def to_format(self, attr): try: _attr = self._to[attr] except KeyError: try: _attr = self._to[attr.lower()] except: _attr = '' if _attr: return factory(saml.Attribute, name=_attr, name_format=self.name_format, friendly_name=attr) else: return factory(saml.Attribute, name=attr)
[ "def", "to_format", "(", "self", ",", "attr", ")", ":", "try", ":", "_attr", "=", "self", ".", "_to", "[", "attr", "]", "except", "KeyError", ":", "try", ":", "_attr", "=", "self", ".", "_to", "[", "attr", ".", "lower", "(", ")", "]", "except", ...
Creates an Attribute instance with name, name_format and friendly_name :param attr: The local name of the attribute :return: An Attribute instance
[ "Creates", "an", "Attribute", "instance", "with", "name", "name_format", "and", "friendly_name" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L360-L381
232,557
IdentityPython/pysaml2
src/saml2/s2repoze/plugins/challenge_decider.py
my_request_classifier
def my_request_classifier(environ): """ Returns one of the classifiers 'dav', 'xmlpost', or 'browser', depending on the imperative logic below""" request_method = REQUEST_METHOD(environ) if request_method in _DAV_METHODS: return "dav" useragent = USER_AGENT(environ) if useragent: for agent in _DAV_USERAGENTS: if useragent.find(agent) != -1: return "dav" if request_method == "POST": if CONTENT_TYPE(environ) == "text/xml": return "xmlpost" elif CONTENT_TYPE(environ) == "application/soap+xml": return "soap" return "browser"
python
def my_request_classifier(environ): request_method = REQUEST_METHOD(environ) if request_method in _DAV_METHODS: return "dav" useragent = USER_AGENT(environ) if useragent: for agent in _DAV_USERAGENTS: if useragent.find(agent) != -1: return "dav" if request_method == "POST": if CONTENT_TYPE(environ) == "text/xml": return "xmlpost" elif CONTENT_TYPE(environ) == "application/soap+xml": return "soap" return "browser"
[ "def", "my_request_classifier", "(", "environ", ")", ":", "request_method", "=", "REQUEST_METHOD", "(", "environ", ")", "if", "request_method", "in", "_DAV_METHODS", ":", "return", "\"dav\"", "useragent", "=", "USER_AGENT", "(", "environ", ")", "if", "useragent", ...
Returns one of the classifiers 'dav', 'xmlpost', or 'browser', depending on the imperative logic below
[ "Returns", "one", "of", "the", "classifiers", "dav", "xmlpost", "or", "browser", "depending", "on", "the", "imperative", "logic", "below" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/s2repoze/plugins/challenge_decider.py#L37-L53
232,558
IdentityPython/pysaml2
src/saml2/metadata.py
_localized_name
def _localized_name(val, klass): """If no language is defined 'en' is the default""" try: (text, lang) = val return klass(text=text, lang=lang) except ValueError: return klass(text=val, lang="en")
python
def _localized_name(val, klass): try: (text, lang) = val return klass(text=text, lang=lang) except ValueError: return klass(text=val, lang="en")
[ "def", "_localized_name", "(", "val", ",", "klass", ")", ":", "try", ":", "(", "text", ",", "lang", ")", "=", "val", "return", "klass", "(", "text", "=", "text", ",", "lang", "=", "lang", ")", "except", "ValueError", ":", "return", "klass", "(", "t...
If no language is defined 'en' is the default
[ "If", "no", "language", "is", "defined", "en", "is", "the", "default" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/metadata.py#L116-L122
232,559
IdentityPython/pysaml2
src/saml2/metadata.py
do_contact_person_info
def do_contact_person_info(ava): """Create a ContactPerson instance from configuration information.""" cper = md.ContactPerson() cper.loadd(ava) if not cper.contact_type: cper.contact_type = "technical" return cper
python
def do_contact_person_info(ava): cper = md.ContactPerson() cper.loadd(ava) if not cper.contact_type: cper.contact_type = "technical" return cper
[ "def", "do_contact_person_info", "(", "ava", ")", ":", "cper", "=", "md", ".", "ContactPerson", "(", ")", "cper", ".", "loadd", "(", "ava", ")", "if", "not", "cper", ".", "contact_type", ":", "cper", ".", "contact_type", "=", "\"technical\"", "return", "...
Create a ContactPerson instance from configuration information.
[ "Create", "a", "ContactPerson", "instance", "from", "configuration", "information", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/metadata.py#L155-L161
232,560
IdentityPython/pysaml2
src/saml2/metadata.py
do_pdp_descriptor
def do_pdp_descriptor(conf, cert=None, enc_cert=None): """ Create a Policy Decision Point descriptor """ pdp = md.PDPDescriptor() pdp.protocol_support_enumeration = samlp.NAMESPACE endps = conf.getattr("endpoints", "pdp") if endps: for (endpoint, instlist) in do_endpoints(endps, ENDPOINTS["pdp"]).items(): setattr(pdp, endpoint, instlist) _do_nameid_format(pdp, conf, "pdp") if cert: pdp.key_descriptor = do_key_descriptor(cert, enc_cert, use=conf.metadata_key_usage) return pdp
python
def do_pdp_descriptor(conf, cert=None, enc_cert=None): pdp = md.PDPDescriptor() pdp.protocol_support_enumeration = samlp.NAMESPACE endps = conf.getattr("endpoints", "pdp") if endps: for (endpoint, instlist) in do_endpoints(endps, ENDPOINTS["pdp"]).items(): setattr(pdp, endpoint, instlist) _do_nameid_format(pdp, conf, "pdp") if cert: pdp.key_descriptor = do_key_descriptor(cert, enc_cert, use=conf.metadata_key_usage) return pdp
[ "def", "do_pdp_descriptor", "(", "conf", ",", "cert", "=", "None", ",", "enc_cert", "=", "None", ")", ":", "pdp", "=", "md", ".", "PDPDescriptor", "(", ")", "pdp", ".", "protocol_support_enumeration", "=", "samlp", ".", "NAMESPACE", "endps", "=", "conf", ...
Create a Policy Decision Point descriptor
[ "Create", "a", "Policy", "Decision", "Point", "descriptor" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/metadata.py#L648-L667
232,561
IdentityPython/pysaml2
src/saml2/authn.py
create_return_url
def create_return_url(base, query, **kwargs): """ Add a query string plus extra parameters to a base URL which may contain a query part already. :param base: redirect_uri may contain a query part, no fragment allowed. :param query: Old query part as a string :param kwargs: extra query parameters :return: """ part = urlsplit(base) if part.fragment: raise ValueError("Base URL contained parts it shouldn't") for key, values in parse_qs(query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values if part.query: for key, values in parse_qs(part.query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values _pre = base.split("?")[0] else: _pre = base logger.debug("kwargs: %s" % kwargs) return "%s?%s" % (_pre, url_encode_params(kwargs))
python
def create_return_url(base, query, **kwargs): part = urlsplit(base) if part.fragment: raise ValueError("Base URL contained parts it shouldn't") for key, values in parse_qs(query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values if part.query: for key, values in parse_qs(part.query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values _pre = base.split("?")[0] else: _pre = base logger.debug("kwargs: %s" % kwargs) return "%s?%s" % (_pre, url_encode_params(kwargs))
[ "def", "create_return_url", "(", "base", ",", "query", ",", "*", "*", "kwargs", ")", ":", "part", "=", "urlsplit", "(", "base", ")", "if", "part", ".", "fragment", ":", "raise", "ValueError", "(", "\"Base URL contained parts it shouldn't\"", ")", "for", "key...
Add a query string plus extra parameters to a base URL which may contain a query part already. :param base: redirect_uri may contain a query part, no fragment allowed. :param query: Old query part as a string :param kwargs: extra query parameters :return:
[ "Add", "a", "query", "string", "plus", "extra", "parameters", "to", "a", "base", "URL", "which", "may", "contain", "a", "query", "part", "already", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/authn.py#L64-L101
232,562
IdentityPython/pysaml2
src/saml2/entity.py
Entity._issuer
def _issuer(self, entityid=None): """ Return an Issuer instance """ if entityid: if isinstance(entityid, Issuer): return entityid else: return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY) else: return Issuer(text=self.config.entityid, format=NAMEID_FORMAT_ENTITY)
python
def _issuer(self, entityid=None): if entityid: if isinstance(entityid, Issuer): return entityid else: return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY) else: return Issuer(text=self.config.entityid, format=NAMEID_FORMAT_ENTITY)
[ "def", "_issuer", "(", "self", ",", "entityid", "=", "None", ")", ":", "if", "entityid", ":", "if", "isinstance", "(", "entityid", ",", "Issuer", ")", ":", "return", "entityid", "else", ":", "return", "Issuer", "(", "text", "=", "entityid", ",", "forma...
Return an Issuer instance
[ "Return", "an", "Issuer", "instance" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L183-L192
232,563
IdentityPython/pysaml2
src/saml2/entity.py
Entity.apply_binding
def apply_binding(self, binding, msg_str, destination="", relay_state="", response=False, sign=False, **kwargs): """ Construct the necessary HTTP arguments dependent on Binding :param binding: Which binding to use :param msg_str: The return message as a string (XML) if the message is to be signed it MUST contain the signature element. :param destination: Where to send the message :param relay_state: Relay_state if provided :param response: Which type of message this is :param kwargs: response type specific arguments :return: A dictionary """ # unless if BINDING_HTTP_ARTIFACT if response: typ = "SAMLResponse" else: typ = "SAMLRequest" if binding == BINDING_HTTP_POST: logger.info("HTTP POST") # if self.entity_type == 'sp': # info = self.use_http_post(msg_str, destination, relay_state, # typ) # info["url"] = destination # info["method"] = "POST" # else: info = self.use_http_form_post(msg_str, destination, relay_state, typ) info["url"] = destination info["method"] = "POST" elif binding == BINDING_HTTP_REDIRECT: logger.info("HTTP REDIRECT") sigalg = kwargs.get("sigalg") if sign and sigalg: signer = self.sec.sec_backend.get_signer(sigalg) else: signer = None info = self.use_http_get(msg_str, destination, relay_state, typ, signer=signer, **kwargs) info["url"] = str(destination) info["method"] = "GET" elif binding == BINDING_SOAP or binding == BINDING_PAOS: info = self.use_soap(msg_str, destination, sign=sign, **kwargs) elif binding == BINDING_URI: info = self.use_http_uri(msg_str, typ, destination) elif binding == BINDING_HTTP_ARTIFACT: if response: info = self.use_http_artifact(msg_str, destination, relay_state) info["method"] = "GET" info["status"] = 302 else: info = self.use_http_artifact(msg_str, destination, relay_state) else: raise SAMLError("Unknown binding type: %s" % binding) return info
python
def apply_binding(self, binding, msg_str, destination="", relay_state="", response=False, sign=False, **kwargs): # unless if BINDING_HTTP_ARTIFACT if response: typ = "SAMLResponse" else: typ = "SAMLRequest" if binding == BINDING_HTTP_POST: logger.info("HTTP POST") # if self.entity_type == 'sp': # info = self.use_http_post(msg_str, destination, relay_state, # typ) # info["url"] = destination # info["method"] = "POST" # else: info = self.use_http_form_post(msg_str, destination, relay_state, typ) info["url"] = destination info["method"] = "POST" elif binding == BINDING_HTTP_REDIRECT: logger.info("HTTP REDIRECT") sigalg = kwargs.get("sigalg") if sign and sigalg: signer = self.sec.sec_backend.get_signer(sigalg) else: signer = None info = self.use_http_get(msg_str, destination, relay_state, typ, signer=signer, **kwargs) info["url"] = str(destination) info["method"] = "GET" elif binding == BINDING_SOAP or binding == BINDING_PAOS: info = self.use_soap(msg_str, destination, sign=sign, **kwargs) elif binding == BINDING_URI: info = self.use_http_uri(msg_str, typ, destination) elif binding == BINDING_HTTP_ARTIFACT: if response: info = self.use_http_artifact(msg_str, destination, relay_state) info["method"] = "GET" info["status"] = 302 else: info = self.use_http_artifact(msg_str, destination, relay_state) else: raise SAMLError("Unknown binding type: %s" % binding) return info
[ "def", "apply_binding", "(", "self", ",", "binding", ",", "msg_str", ",", "destination", "=", "\"\"", ",", "relay_state", "=", "\"\"", ",", "response", "=", "False", ",", "sign", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# unless if BINDING_HTTP_AR...
Construct the necessary HTTP arguments dependent on Binding :param binding: Which binding to use :param msg_str: The return message as a string (XML) if the message is to be signed it MUST contain the signature element. :param destination: Where to send the message :param relay_state: Relay_state if provided :param response: Which type of message this is :param kwargs: response type specific arguments :return: A dictionary
[ "Construct", "the", "necessary", "HTTP", "arguments", "dependent", "on", "Binding" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L194-L251
232,564
IdentityPython/pysaml2
src/saml2/entity.py
Entity._message
def _message(self, request_cls, destination=None, message_id=0, consent=None, extensions=None, sign=False, sign_prepare=False, nsprefix=None, sign_alg=None, digest_alg=None, **kwargs): """ Some parameters appear in all requests so simplify by doing it in one place :param request_cls: The specific request type :param destination: The recipient :param message_id: A message identifier :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param sign_prepare: Whether the signature should be prepared or not. :param kwargs: Key word arguments specific to one request type :return: A tuple containing the request ID and an instance of the request_cls """ if not message_id: message_id = sid() for key, val in self.message_args(message_id).items(): if key not in kwargs: kwargs[key] = val req = request_cls(**kwargs) if destination: req.destination = destination if consent: req.consent = "true" if extensions: req.extensions = extensions if nsprefix: req.register_prefix(nsprefix) if self.msg_cb: req = self.msg_cb(req) reqid = req.id if sign: return reqid, self.sign(req, sign_prepare=sign_prepare, sign_alg=sign_alg, digest_alg=digest_alg) else: logger.info("REQUEST: %s", req) return reqid, req
python
def _message(self, request_cls, destination=None, message_id=0, consent=None, extensions=None, sign=False, sign_prepare=False, nsprefix=None, sign_alg=None, digest_alg=None, **kwargs): if not message_id: message_id = sid() for key, val in self.message_args(message_id).items(): if key not in kwargs: kwargs[key] = val req = request_cls(**kwargs) if destination: req.destination = destination if consent: req.consent = "true" if extensions: req.extensions = extensions if nsprefix: req.register_prefix(nsprefix) if self.msg_cb: req = self.msg_cb(req) reqid = req.id if sign: return reqid, self.sign(req, sign_prepare=sign_prepare, sign_alg=sign_alg, digest_alg=digest_alg) else: logger.info("REQUEST: %s", req) return reqid, req
[ "def", "_message", "(", "self", ",", "request_cls", ",", "destination", "=", "None", ",", "message_id", "=", "0", ",", "consent", "=", "None", ",", "extensions", "=", "None", ",", "sign", "=", "False", ",", "sign_prepare", "=", "False", ",", "nsprefix", ...
Some parameters appear in all requests so simplify by doing it in one place :param request_cls: The specific request type :param destination: The recipient :param message_id: A message identifier :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param sign_prepare: Whether the signature should be prepared or not. :param kwargs: Key word arguments specific to one request type :return: A tuple containing the request ID and an instance of the request_cls
[ "Some", "parameters", "appear", "in", "all", "requests", "so", "simplify", "by", "doing", "it", "in", "one", "place" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L447-L496
232,565
IdentityPython/pysaml2
src/saml2/entity.py
Entity._add_info
def _add_info(self, msg, **kwargs): """ Add information to a SAML message. If the attribute is not part of what's defined in the SAML standard add it as an extension. :param msg: :param kwargs: :return: """ args, extensions = self._filter_args(msg, **kwargs) for key, val in args.items(): setattr(msg, key, val) if extensions: if msg.extension_elements: msg.extension_elements.extend(extensions) else: msg.extension_elements = extensions
python
def _add_info(self, msg, **kwargs): args, extensions = self._filter_args(msg, **kwargs) for key, val in args.items(): setattr(msg, key, val) if extensions: if msg.extension_elements: msg.extension_elements.extend(extensions) else: msg.extension_elements = extensions
[ "def", "_add_info", "(", "self", ",", "msg", ",", "*", "*", "kwargs", ")", ":", "args", ",", "extensions", "=", "self", ".", "_filter_args", "(", "msg", ",", "*", "*", "kwargs", ")", "for", "key", ",", "val", "in", "args", ".", "items", "(", ")",...
Add information to a SAML message. If the attribute is not part of what's defined in the SAML standard add it as an extension. :param msg: :param kwargs: :return:
[ "Add", "information", "to", "a", "SAML", "message", ".", "If", "the", "attribute", "is", "not", "part", "of", "what", "s", "defined", "in", "the", "SAML", "standard", "add", "it", "as", "an", "extension", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L514-L532
232,566
IdentityPython/pysaml2
src/saml2/entity.py
Entity.has_encrypt_cert_in_metadata
def has_encrypt_cert_in_metadata(self, sp_entity_id): """ Verifies if the metadata contains encryption certificates. :param sp_entity_id: Entity ID for the calling service provider. :return: True if encrypt cert exists in metadata, otherwise False. """ if sp_entity_id is not None: _certs = self.metadata.certs(sp_entity_id, "any", "encryption") if len(_certs) > 0: return True return False
python
def has_encrypt_cert_in_metadata(self, sp_entity_id): if sp_entity_id is not None: _certs = self.metadata.certs(sp_entity_id, "any", "encryption") if len(_certs) > 0: return True return False
[ "def", "has_encrypt_cert_in_metadata", "(", "self", ",", "sp_entity_id", ")", ":", "if", "sp_entity_id", "is", "not", "None", ":", "_certs", "=", "self", ".", "metadata", ".", "certs", "(", "sp_entity_id", ",", "\"any\"", ",", "\"encryption\"", ")", "if", "l...
Verifies if the metadata contains encryption certificates. :param sp_entity_id: Entity ID for the calling service provider. :return: True if encrypt cert exists in metadata, otherwise False.
[ "Verifies", "if", "the", "metadata", "contains", "encryption", "certificates", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L534-L544
232,567
IdentityPython/pysaml2
src/saml2/entity.py
Entity._encrypt_assertion
def _encrypt_assertion(self, encrypt_cert, sp_entity_id, response, node_xpath=None): """ Encryption of assertions. :param encrypt_cert: Certificate to be used for encryption. :param sp_entity_id: Entity ID for the calling service provider. :param response: A samlp.Response :param node_xpath: Unquie path to the element to be encrypted. :return: A new samlp.Resonse with the designated assertion encrypted. """ _certs = [] if encrypt_cert: _certs.append(encrypt_cert) elif sp_entity_id is not None: _certs = self.metadata.certs(sp_entity_id, "any", "encryption") exception = None for _cert in _certs: try: begin_cert = "-----BEGIN CERTIFICATE-----\n" end_cert = "\n-----END CERTIFICATE-----\n" if begin_cert not in _cert: _cert = "%s%s" % (begin_cert, _cert) if end_cert not in _cert: _cert = "%s%s" % (_cert, end_cert) _, cert_file = make_temp(_cert.encode('ascii'), decode=False) response = self.sec.encrypt_assertion(response, cert_file, pre_encryption_part(), node_xpath=node_xpath) return response except Exception as ex: exception = ex pass if exception: raise exception return response
python
def _encrypt_assertion(self, encrypt_cert, sp_entity_id, response, node_xpath=None): _certs = [] if encrypt_cert: _certs.append(encrypt_cert) elif sp_entity_id is not None: _certs = self.metadata.certs(sp_entity_id, "any", "encryption") exception = None for _cert in _certs: try: begin_cert = "-----BEGIN CERTIFICATE-----\n" end_cert = "\n-----END CERTIFICATE-----\n" if begin_cert not in _cert: _cert = "%s%s" % (begin_cert, _cert) if end_cert not in _cert: _cert = "%s%s" % (_cert, end_cert) _, cert_file = make_temp(_cert.encode('ascii'), decode=False) response = self.sec.encrypt_assertion(response, cert_file, pre_encryption_part(), node_xpath=node_xpath) return response except Exception as ex: exception = ex pass if exception: raise exception return response
[ "def", "_encrypt_assertion", "(", "self", ",", "encrypt_cert", ",", "sp_entity_id", ",", "response", ",", "node_xpath", "=", "None", ")", ":", "_certs", "=", "[", "]", "if", "encrypt_cert", ":", "_certs", ".", "append", "(", "encrypt_cert", ")", "elif", "s...
Encryption of assertions. :param encrypt_cert: Certificate to be used for encryption. :param sp_entity_id: Entity ID for the calling service provider. :param response: A samlp.Response :param node_xpath: Unquie path to the element to be encrypted. :return: A new samlp.Resonse with the designated assertion encrypted.
[ "Encryption", "of", "assertions", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L546-L581
232,568
IdentityPython/pysaml2
src/saml2/entity.py
Entity._status_response
def _status_response(self, response_class, issuer, status, sign=False, sign_alg=None, digest_alg=None, **kwargs): """ Create a StatusResponse. :param response_class: Which subclass of StatusResponse that should be used :param issuer: The issuer of the response message :param status: The return status of the response operation :param sign: Whether the response should be signed or not :param kwargs: Extra arguments to the response class :return: Class instance or string representation of the instance """ mid = sid() for key in ["binding"]: try: del kwargs[key] except KeyError: pass if not status: status = success_status_factory() response = response_class(issuer=issuer, id=mid, version=VERSION, issue_instant=instant(), status=status, **kwargs) if sign: return self.sign(response, mid, sign_alg=sign_alg, digest_alg=digest_alg) else: return response
python
def _status_response(self, response_class, issuer, status, sign=False, sign_alg=None, digest_alg=None, **kwargs): mid = sid() for key in ["binding"]: try: del kwargs[key] except KeyError: pass if not status: status = success_status_factory() response = response_class(issuer=issuer, id=mid, version=VERSION, issue_instant=instant(), status=status, **kwargs) if sign: return self.sign(response, mid, sign_alg=sign_alg, digest_alg=digest_alg) else: return response
[ "def", "_status_response", "(", "self", ",", "response_class", ",", "issuer", ",", "status", ",", "sign", "=", "False", ",", "sign_alg", "=", "None", ",", "digest_alg", "=", "None", ",", "*", "*", "kwargs", ")", ":", "mid", "=", "sid", "(", ")", "for...
Create a StatusResponse. :param response_class: Which subclass of StatusResponse that should be used :param issuer: The issuer of the response message :param status: The return status of the response operation :param sign: Whether the response should be signed or not :param kwargs: Extra arguments to the response class :return: Class instance or string representation of the instance
[ "Create", "a", "StatusResponse", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L759-L792
232,569
IdentityPython/pysaml2
src/saml2/entity.py
Entity._parse_request
def _parse_request(self, enc_request, request_cls, service, binding): """Parse a Request :param enc_request: The request in its transport format :param request_cls: The type of requests I expect :param service: :param binding: Which binding that was used to transport the message to this entity. :return: A request instance """ _log_info = logger.info _log_debug = logger.debug # The addresses I should receive messages like this on receiver_addresses = self.config.endpoint(service, binding, self.entity_type) if not receiver_addresses and self.entity_type == "idp": for typ in ["aa", "aq", "pdp"]: receiver_addresses = self.config.endpoint(service, binding, typ) if receiver_addresses: break _log_debug("receiver addresses: %s", receiver_addresses) _log_debug("Binding: %s", binding) try: timeslack = self.config.accepted_time_diff if not timeslack: timeslack = 0 except AttributeError: timeslack = 0 _request = request_cls(self.sec, receiver_addresses, self.config.attribute_converters, timeslack=timeslack) xmlstr = self.unravel(enc_request, binding, request_cls.msgtype) must = self.config.getattr("want_authn_requests_signed", "idp") only_valid_cert = self.config.getattr( "want_authn_requests_only_with_valid_cert", "idp") if only_valid_cert is None: only_valid_cert = False if only_valid_cert: must = True _request = _request.loads(xmlstr, binding, origdoc=enc_request, must=must, only_valid_cert=only_valid_cert) _log_debug("Loaded request") if _request: _request = _request.verify() _log_debug("Verified request") if not _request: return None else: return _request
python
def _parse_request(self, enc_request, request_cls, service, binding): _log_info = logger.info _log_debug = logger.debug # The addresses I should receive messages like this on receiver_addresses = self.config.endpoint(service, binding, self.entity_type) if not receiver_addresses and self.entity_type == "idp": for typ in ["aa", "aq", "pdp"]: receiver_addresses = self.config.endpoint(service, binding, typ) if receiver_addresses: break _log_debug("receiver addresses: %s", receiver_addresses) _log_debug("Binding: %s", binding) try: timeslack = self.config.accepted_time_diff if not timeslack: timeslack = 0 except AttributeError: timeslack = 0 _request = request_cls(self.sec, receiver_addresses, self.config.attribute_converters, timeslack=timeslack) xmlstr = self.unravel(enc_request, binding, request_cls.msgtype) must = self.config.getattr("want_authn_requests_signed", "idp") only_valid_cert = self.config.getattr( "want_authn_requests_only_with_valid_cert", "idp") if only_valid_cert is None: only_valid_cert = False if only_valid_cert: must = True _request = _request.loads(xmlstr, binding, origdoc=enc_request, must=must, only_valid_cert=only_valid_cert) _log_debug("Loaded request") if _request: _request = _request.verify() _log_debug("Verified request") if not _request: return None else: return _request
[ "def", "_parse_request", "(", "self", ",", "enc_request", ",", "request_cls", ",", "service", ",", "binding", ")", ":", "_log_info", "=", "logger", ".", "info", "_log_debug", "=", "logger", ".", "debug", "# The addresses I should receive messages like this on", "rec...
Parse a Request :param enc_request: The request in its transport format :param request_cls: The type of requests I expect :param service: :param binding: Which binding that was used to transport the message to this entity. :return: A request instance
[ "Parse", "a", "Request" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L807-L864
232,570
IdentityPython/pysaml2
src/saml2/entity.py
Entity.create_error_response
def create_error_response(self, in_response_to, destination, info, sign=False, issuer=None, sign_alg=None, digest_alg=None, **kwargs): """ Create a error response. :param in_response_to: The identifier of the message this is a response to. :param destination: The intended recipient of this message :param info: Either an Exception instance or a 2-tuple consisting of error code and descriptive text :param sign: Whether the response should be signed or not :param issuer: The issuer of the response :param kwargs: To capture key,value pairs I don't care about :return: A response instance """ status = error_status_factory(info) return self._response(in_response_to, destination, status, issuer, sign, sign_alg=sign_alg, digest_alg=digest_alg)
python
def create_error_response(self, in_response_to, destination, info, sign=False, issuer=None, sign_alg=None, digest_alg=None, **kwargs): status = error_status_factory(info) return self._response(in_response_to, destination, status, issuer, sign, sign_alg=sign_alg, digest_alg=digest_alg)
[ "def", "create_error_response", "(", "self", ",", "in_response_to", ",", "destination", ",", "info", ",", "sign", "=", "False", ",", "issuer", "=", "None", ",", "sign_alg", "=", "None", ",", "digest_alg", "=", "None", ",", "*", "*", "kwargs", ")", ":", ...
Create a error response. :param in_response_to: The identifier of the message this is a response to. :param destination: The intended recipient of this message :param info: Either an Exception instance or a 2-tuple consisting of error code and descriptive text :param sign: Whether the response should be signed or not :param issuer: The issuer of the response :param kwargs: To capture key,value pairs I don't care about :return: A response instance
[ "Create", "a", "error", "response", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L868-L886
232,571
IdentityPython/pysaml2
src/saml2/entity.py
Entity.create_logout_request
def create_logout_request(self, destination, issuer_entity_id, subject_id=None, name_id=None, reason=None, expire=None, message_id=0, consent=None, extensions=None, sign=False, session_indexes=None, sign_alg=None, digest_alg=None): """ Constructs a LogoutRequest :param destination: Destination of the request :param issuer_entity_id: The entity ID of the IdP the request is target at. :param subject_id: The identifier of the subject :param name_id: A NameID instance identifying the subject :param reason: An indication of the reason for the logout, in the form of a URI reference. :param expire: The time at which the request expires, after which the recipient may discard the message. :param message_id: Request identifier :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the query should be signed or not. :param session_indexes: SessionIndex instances or just values :return: A LogoutRequest instance """ if subject_id: if self.entity_type == "idp": name_id = NameID(text=self.users.get_entityid(subject_id, issuer_entity_id, False)) else: name_id = NameID(text=subject_id) if not name_id: raise SAMLError("Missing subject identification") args = {} if session_indexes: sis = [] for si in session_indexes: if isinstance(si, SessionIndex): sis.append(si) else: sis.append(SessionIndex(text=si)) args["session_index"] = sis return self._message(LogoutRequest, destination, message_id, consent, extensions, sign, name_id=name_id, reason=reason, not_on_or_after=expire, issuer=self._issuer(), sign_alg=sign_alg, digest_alg=digest_alg, **args)
python
def create_logout_request(self, destination, issuer_entity_id, subject_id=None, name_id=None, reason=None, expire=None, message_id=0, consent=None, extensions=None, sign=False, session_indexes=None, sign_alg=None, digest_alg=None): if subject_id: if self.entity_type == "idp": name_id = NameID(text=self.users.get_entityid(subject_id, issuer_entity_id, False)) else: name_id = NameID(text=subject_id) if not name_id: raise SAMLError("Missing subject identification") args = {} if session_indexes: sis = [] for si in session_indexes: if isinstance(si, SessionIndex): sis.append(si) else: sis.append(SessionIndex(text=si)) args["session_index"] = sis return self._message(LogoutRequest, destination, message_id, consent, extensions, sign, name_id=name_id, reason=reason, not_on_or_after=expire, issuer=self._issuer(), sign_alg=sign_alg, digest_alg=digest_alg, **args)
[ "def", "create_logout_request", "(", "self", ",", "destination", ",", "issuer_entity_id", ",", "subject_id", "=", "None", ",", "name_id", "=", "None", ",", "reason", "=", "None", ",", "expire", "=", "None", ",", "message_id", "=", "0", ",", "consent", "=",...
Constructs a LogoutRequest :param destination: Destination of the request :param issuer_entity_id: The entity ID of the IdP the request is target at. :param subject_id: The identifier of the subject :param name_id: A NameID instance identifying the subject :param reason: An indication of the reason for the logout, in the form of a URI reference. :param expire: The time at which the request expires, after which the recipient may discard the message. :param message_id: Request identifier :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the query should be signed or not. :param session_indexes: SessionIndex instances or just values :return: A LogoutRequest instance
[ "Constructs", "a", "LogoutRequest" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L890-L940
232,572
IdentityPython/pysaml2
src/saml2/entity.py
Entity.create_logout_response
def create_logout_response(self, request, bindings=None, status=None, sign=False, issuer=None, sign_alg=None, digest_alg=None): """ Create a LogoutResponse. :param request: The request this is a response to :param bindings: Which bindings that can be used for the response If None the preferred bindings are gathered from the configuration :param status: The return status of the response operation If None the operation is regarded as a Success. :param issuer: The issuer of the message :return: HTTP args """ rinfo = self.response_args(request, bindings) if not issuer: issuer = self._issuer() response = self._status_response(samlp.LogoutResponse, issuer, status, sign, sign_alg=sign_alg, digest_alg=digest_alg, **rinfo) logger.info("Response: %s", response) return response
python
def create_logout_response(self, request, bindings=None, status=None, sign=False, issuer=None, sign_alg=None, digest_alg=None): rinfo = self.response_args(request, bindings) if not issuer: issuer = self._issuer() response = self._status_response(samlp.LogoutResponse, issuer, status, sign, sign_alg=sign_alg, digest_alg=digest_alg, **rinfo) logger.info("Response: %s", response) return response
[ "def", "create_logout_response", "(", "self", ",", "request", ",", "bindings", "=", "None", ",", "status", "=", "None", ",", "sign", "=", "False", ",", "issuer", "=", "None", ",", "sign_alg", "=", "None", ",", "digest_alg", "=", "None", ")", ":", "rinf...
Create a LogoutResponse. :param request: The request this is a response to :param bindings: Which bindings that can be used for the response If None the preferred bindings are gathered from the configuration :param status: The return status of the response operation If None the operation is regarded as a Success. :param issuer: The issuer of the message :return: HTTP args
[ "Create", "a", "LogoutResponse", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L942-L967
232,573
IdentityPython/pysaml2
src/saml2/entity.py
Entity.create_artifact_resolve
def create_artifact_resolve(self, artifact, destination, sessid, consent=None, extensions=None, sign=False, sign_alg=None, digest_alg=None): """ Create a ArtifactResolve request :param artifact: :param destination: :param sessid: session id :param consent: :param extensions: :param sign: :return: The request message """ artifact = Artifact(text=artifact) return self._message(ArtifactResolve, destination, sessid, consent, extensions, sign, artifact=artifact, sign_alg=sign_alg, digest_alg=digest_alg)
python
def create_artifact_resolve(self, artifact, destination, sessid, consent=None, extensions=None, sign=False, sign_alg=None, digest_alg=None): artifact = Artifact(text=artifact) return self._message(ArtifactResolve, destination, sessid, consent, extensions, sign, artifact=artifact, sign_alg=sign_alg, digest_alg=digest_alg)
[ "def", "create_artifact_resolve", "(", "self", ",", "artifact", ",", "destination", ",", "sessid", ",", "consent", "=", "None", ",", "extensions", "=", "None", ",", "sign", "=", "False", ",", "sign_alg", "=", "None", ",", "digest_alg", "=", "None", ")", ...
Create a ArtifactResolve request :param artifact: :param destination: :param sessid: session id :param consent: :param extensions: :param sign: :return: The request message
[ "Create", "a", "ArtifactResolve", "request" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L969-L988
232,574
IdentityPython/pysaml2
src/saml2/entity.py
Entity._parse_response
def _parse_response(self, xmlstr, response_cls, service, binding, outstanding_certs=None, **kwargs): """ Deal with a Response :param xmlstr: The response as a xml string :param response_cls: What type of response it is :param binding: What type of binding this message came through. :param outstanding_certs: Certificates that belongs to me that the IdP may have used to encrypt a response/assertion/.. :param kwargs: Extra key word arguments :return: None if the reply doesn't contain a valid SAML Response, otherwise the response. """ if self.config.accepted_time_diff: kwargs["timeslack"] = self.config.accepted_time_diff if "asynchop" not in kwargs: if binding in [BINDING_SOAP, BINDING_PAOS]: kwargs["asynchop"] = False else: kwargs["asynchop"] = True response = None if not xmlstr: return response if "return_addrs" not in kwargs: bindings = { BINDING_SOAP, BINDING_HTTP_REDIRECT, BINDING_HTTP_POST, } if binding in bindings: # expected return address kwargs["return_addrs"] = self.config.endpoint( service, binding=binding, context=self.entity_type) try: response = response_cls(self.sec, **kwargs) except Exception as exc: logger.info("%s", exc) raise xmlstr = self.unravel(xmlstr, binding, response_cls.msgtype) if not xmlstr: # Not a valid reponse return None try: response_is_signed = False # Record the response signature requirement. require_response_signature = response.require_response_signature # Force the requirement that the response be signed in order to # force signature checking to happen so that we can know whether # or not the response is signed. The attribute on the response class # is reset to the recorded value in the finally clause below. response.require_response_signature = True response = response.loads(xmlstr, False, origxml=xmlstr) except SigverError as err: if require_response_signature: logger.error("Signature Error: %s", err) raise else: # The response is not signed but a signature is not required # so reset the attribute on the response class to the recorded # value and attempt to consume the unpacked XML again. response.require_response_signature = require_response_signature response = response.loads(xmlstr, False, origxml=xmlstr) except UnsolicitedResponse: logger.error("Unsolicited response") raise except Exception as err: if "not well-formed" in "%s" % err: logger.error("Not well-formed XML") raise else: response_is_signed = True finally: response.require_response_signature = require_response_signature logger.debug("XMLSTR: %s", xmlstr) if not response: return response keys = None if outstanding_certs: try: cert = outstanding_certs[response.in_response_to] except KeyError: keys = None else: if not isinstance(cert, list): cert = [cert] keys = [] for _cert in cert: keys.append(_cert["key"]) try: assertions_are_signed = False # Record the assertions signature requirement. require_signature = response.require_signature # Force the requirement that the assertions be signed in order to # force signature checking to happen so that we can know whether # or not the assertions are signed. The attribute on the response class # is reset to the recorded value in the finally clause below. response.require_signature = True # Verify that the assertion is syntactically correct and the # signature on the assertion is correct if present. response = response.verify(keys) except SignatureError as err: if require_signature: logger.error("Signature Error: %s", err) raise else: response.require_signature = require_signature response = response.verify(keys) else: assertions_are_signed = True finally: response.require_signature = require_signature # If so configured enforce that either the response is signed # or the assertions within it are signed. if response.require_signature_or_response_signature: if not response_is_signed and not assertions_are_signed: msg = "Neither the response nor the assertions are signed" logger.error(msg) raise SigverError(msg) return response
python
def _parse_response(self, xmlstr, response_cls, service, binding, outstanding_certs=None, **kwargs): if self.config.accepted_time_diff: kwargs["timeslack"] = self.config.accepted_time_diff if "asynchop" not in kwargs: if binding in [BINDING_SOAP, BINDING_PAOS]: kwargs["asynchop"] = False else: kwargs["asynchop"] = True response = None if not xmlstr: return response if "return_addrs" not in kwargs: bindings = { BINDING_SOAP, BINDING_HTTP_REDIRECT, BINDING_HTTP_POST, } if binding in bindings: # expected return address kwargs["return_addrs"] = self.config.endpoint( service, binding=binding, context=self.entity_type) try: response = response_cls(self.sec, **kwargs) except Exception as exc: logger.info("%s", exc) raise xmlstr = self.unravel(xmlstr, binding, response_cls.msgtype) if not xmlstr: # Not a valid reponse return None try: response_is_signed = False # Record the response signature requirement. require_response_signature = response.require_response_signature # Force the requirement that the response be signed in order to # force signature checking to happen so that we can know whether # or not the response is signed. The attribute on the response class # is reset to the recorded value in the finally clause below. response.require_response_signature = True response = response.loads(xmlstr, False, origxml=xmlstr) except SigverError as err: if require_response_signature: logger.error("Signature Error: %s", err) raise else: # The response is not signed but a signature is not required # so reset the attribute on the response class to the recorded # value and attempt to consume the unpacked XML again. response.require_response_signature = require_response_signature response = response.loads(xmlstr, False, origxml=xmlstr) except UnsolicitedResponse: logger.error("Unsolicited response") raise except Exception as err: if "not well-formed" in "%s" % err: logger.error("Not well-formed XML") raise else: response_is_signed = True finally: response.require_response_signature = require_response_signature logger.debug("XMLSTR: %s", xmlstr) if not response: return response keys = None if outstanding_certs: try: cert = outstanding_certs[response.in_response_to] except KeyError: keys = None else: if not isinstance(cert, list): cert = [cert] keys = [] for _cert in cert: keys.append(_cert["key"]) try: assertions_are_signed = False # Record the assertions signature requirement. require_signature = response.require_signature # Force the requirement that the assertions be signed in order to # force signature checking to happen so that we can know whether # or not the assertions are signed. The attribute on the response class # is reset to the recorded value in the finally clause below. response.require_signature = True # Verify that the assertion is syntactically correct and the # signature on the assertion is correct if present. response = response.verify(keys) except SignatureError as err: if require_signature: logger.error("Signature Error: %s", err) raise else: response.require_signature = require_signature response = response.verify(keys) else: assertions_are_signed = True finally: response.require_signature = require_signature # If so configured enforce that either the response is signed # or the assertions within it are signed. if response.require_signature_or_response_signature: if not response_is_signed and not assertions_are_signed: msg = "Neither the response nor the assertions are signed" logger.error(msg) raise SigverError(msg) return response
[ "def", "_parse_response", "(", "self", ",", "xmlstr", ",", "response_cls", ",", "service", ",", "binding", ",", "outstanding_certs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "config", ".", "accepted_time_diff", ":", "kwargs", "[",...
Deal with a Response :param xmlstr: The response as a xml string :param response_cls: What type of response it is :param binding: What type of binding this message came through. :param outstanding_certs: Certificates that belongs to me that the IdP may have used to encrypt a response/assertion/.. :param kwargs: Extra key word arguments :return: None if the reply doesn't contain a valid SAML Response, otherwise the response.
[ "Deal", "with", "a", "Response" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L1091-L1223
232,575
IdentityPython/pysaml2
src/saml2/entity.py
Entity.artifact2destination
def artifact2destination(self, artifact, descriptor): """ Translate an artifact into a receiver location :param artifact: The Base64 encoded SAML artifact :return: """ _art = base64.b64decode(artifact) assert _art[:2] == ARTIFACT_TYPECODE try: endpoint_index = str(int(_art[2:4])) except ValueError: endpoint_index = str(int(hexlify(_art[2:4]))) entity = self.sourceid[_art[4:24]] destination = None for desc in entity["%s_descriptor" % descriptor]: for srv in desc["artifact_resolution_service"]: if srv["index"] == endpoint_index: destination = srv["location"] break return destination
python
def artifact2destination(self, artifact, descriptor): _art = base64.b64decode(artifact) assert _art[:2] == ARTIFACT_TYPECODE try: endpoint_index = str(int(_art[2:4])) except ValueError: endpoint_index = str(int(hexlify(_art[2:4]))) entity = self.sourceid[_art[4:24]] destination = None for desc in entity["%s_descriptor" % descriptor]: for srv in desc["artifact_resolution_service"]: if srv["index"] == endpoint_index: destination = srv["location"] break return destination
[ "def", "artifact2destination", "(", "self", ",", "artifact", ",", "descriptor", ")", ":", "_art", "=", "base64", ".", "b64decode", "(", "artifact", ")", "assert", "_art", "[", ":", "2", "]", "==", "ARTIFACT_TYPECODE", "try", ":", "endpoint_index", "=", "st...
Translate an artifact into a receiver location :param artifact: The Base64 encoded SAML artifact :return:
[ "Translate", "an", "artifact", "into", "a", "receiver", "location" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/entity.py#L1260-L1285
232,576
IdentityPython/pysaml2
src/saml2/client.py
Saml2Client.prepare_for_authenticate
def prepare_for_authenticate( self, entityid=None, relay_state="", binding=saml2.BINDING_HTTP_REDIRECT, vorg="", nameid_format=None, scoping=None, consent=None, extensions=None, sign=None, response_binding=saml2.BINDING_HTTP_POST, **kwargs): """ Makes all necessary preparations for an authentication request. :param entityid: The entity ID of the IdP to send the request to :param relay_state: To where the user should be returned after successfull log in. :param binding: Which binding to use for sending the request :param vorg: The entity_id of the virtual organization I'm a member of :param nameid_format: :param scoping: For which IdPs this query are aimed. :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param response_binding: Which binding to use for receiving the response :param kwargs: Extra key word arguments :return: session id and AuthnRequest info """ reqid, negotiated_binding, info = \ self.prepare_for_negotiated_authenticate( entityid=entityid, relay_state=relay_state, binding=binding, vorg=vorg, nameid_format=nameid_format, scoping=scoping, consent=consent, extensions=extensions, sign=sign, response_binding=response_binding, **kwargs) assert negotiated_binding == binding return reqid, info
python
def prepare_for_authenticate( self, entityid=None, relay_state="", binding=saml2.BINDING_HTTP_REDIRECT, vorg="", nameid_format=None, scoping=None, consent=None, extensions=None, sign=None, response_binding=saml2.BINDING_HTTP_POST, **kwargs): reqid, negotiated_binding, info = \ self.prepare_for_negotiated_authenticate( entityid=entityid, relay_state=relay_state, binding=binding, vorg=vorg, nameid_format=nameid_format, scoping=scoping, consent=consent, extensions=extensions, sign=sign, response_binding=response_binding, **kwargs) assert negotiated_binding == binding return reqid, info
[ "def", "prepare_for_authenticate", "(", "self", ",", "entityid", "=", "None", ",", "relay_state", "=", "\"\"", ",", "binding", "=", "saml2", ".", "BINDING_HTTP_REDIRECT", ",", "vorg", "=", "\"\"", ",", "nameid_format", "=", "None", ",", "scoping", "=", "None...
Makes all necessary preparations for an authentication request. :param entityid: The entity ID of the IdP to send the request to :param relay_state: To where the user should be returned after successfull log in. :param binding: Which binding to use for sending the request :param vorg: The entity_id of the virtual organization I'm a member of :param nameid_format: :param scoping: For which IdPs this query are aimed. :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param response_binding: Which binding to use for receiving the response :param kwargs: Extra key word arguments :return: session id and AuthnRequest info
[ "Makes", "all", "necessary", "preparations", "for", "an", "authentication", "request", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client.py#L42-L80
232,577
IdentityPython/pysaml2
src/saml2/client.py
Saml2Client.prepare_for_negotiated_authenticate
def prepare_for_negotiated_authenticate( self, entityid=None, relay_state="", binding=None, vorg="", nameid_format=None, scoping=None, consent=None, extensions=None, sign=None, response_binding=saml2.BINDING_HTTP_POST, **kwargs): """ Makes all necessary preparations for an authentication request that negotiates which binding to use for authentication. :param entityid: The entity ID of the IdP to send the request to :param relay_state: To where the user should be returned after successfull log in. :param binding: Which binding to use for sending the request :param vorg: The entity_id of the virtual organization I'm a member of :param nameid_format: :param scoping: For which IdPs this query are aimed. :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param response_binding: Which binding to use for receiving the response :param kwargs: Extra key word arguments :return: session id and AuthnRequest info """ expected_binding = binding for binding in [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]: if expected_binding and binding != expected_binding: continue destination = self._sso_location(entityid, binding) logger.info("destination to provider: %s", destination) reqid, request = self.create_authn_request( destination, vorg, scoping, response_binding, nameid_format, consent=consent, extensions=extensions, sign=sign, **kwargs) _req_str = str(request) logger.info("AuthNReq: %s", _req_str) try: args = {'sigalg': kwargs["sigalg"]} except KeyError: args = {} http_info = self.apply_binding(binding, _req_str, destination, relay_state, sign=sign, **args) return reqid, binding, http_info else: raise SignOnError( "No supported bindings available for authentication")
python
def prepare_for_negotiated_authenticate( self, entityid=None, relay_state="", binding=None, vorg="", nameid_format=None, scoping=None, consent=None, extensions=None, sign=None, response_binding=saml2.BINDING_HTTP_POST, **kwargs): expected_binding = binding for binding in [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]: if expected_binding and binding != expected_binding: continue destination = self._sso_location(entityid, binding) logger.info("destination to provider: %s", destination) reqid, request = self.create_authn_request( destination, vorg, scoping, response_binding, nameid_format, consent=consent, extensions=extensions, sign=sign, **kwargs) _req_str = str(request) logger.info("AuthNReq: %s", _req_str) try: args = {'sigalg': kwargs["sigalg"]} except KeyError: args = {} http_info = self.apply_binding(binding, _req_str, destination, relay_state, sign=sign, **args) return reqid, binding, http_info else: raise SignOnError( "No supported bindings available for authentication")
[ "def", "prepare_for_negotiated_authenticate", "(", "self", ",", "entityid", "=", "None", ",", "relay_state", "=", "\"\"", ",", "binding", "=", "None", ",", "vorg", "=", "\"\"", ",", "nameid_format", "=", "None", ",", "scoping", "=", "None", ",", "consent", ...
Makes all necessary preparations for an authentication request that negotiates which binding to use for authentication. :param entityid: The entity ID of the IdP to send the request to :param relay_state: To where the user should be returned after successfull log in. :param binding: Which binding to use for sending the request :param vorg: The entity_id of the virtual organization I'm a member of :param nameid_format: :param scoping: For which IdPs this query are aimed. :param consent: Whether the principal have given her consent :param extensions: Possible extensions :param sign: Whether the request should be signed or not. :param response_binding: Which binding to use for receiving the response :param kwargs: Extra key word arguments :return: session id and AuthnRequest info
[ "Makes", "all", "necessary", "preparations", "for", "an", "authentication", "request", "that", "negotiates", "which", "binding", "to", "use", "for", "authentication", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client.py#L82-L133
232,578
IdentityPython/pysaml2
src/saml2/client.py
Saml2Client.is_logged_in
def is_logged_in(self, name_id): """ Check if user is in the cache :param name_id: The identifier of the subject """ identity = self.users.get_identity(name_id)[0] return bool(identity)
python
def is_logged_in(self, name_id): identity = self.users.get_identity(name_id)[0] return bool(identity)
[ "def", "is_logged_in", "(", "self", ",", "name_id", ")", ":", "identity", "=", "self", ".", "users", ".", "get_identity", "(", "name_id", ")", "[", "0", "]", "return", "bool", "(", "identity", ")" ]
Check if user is in the cache :param name_id: The identifier of the subject
[ "Check", "if", "user", "is", "in", "the", "cache" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client.py#L287-L293
232,579
IdentityPython/pysaml2
src/saml2/client.py
Saml2Client.handle_logout_response
def handle_logout_response(self, response, sign_alg=None, digest_alg=None): """ handles a Logout response :param response: A response.Response instance :return: 4-tuple of (session_id of the last sent logout request, response message, response headers and message) """ logger.info("state: %s", self.state) status = self.state[response.in_response_to] logger.info("status: %s", status) issuer = response.issuer() logger.info("issuer: %s", issuer) del self.state[response.in_response_to] if status["entity_ids"] == [issuer]: # done self.local_logout(decode(status["name_id"])) return 0, "200 Ok", [("Content-type", "text/html")], [] else: status["entity_ids"].remove(issuer) if "sign_alg" in status: sign_alg = status["sign_alg"] return self.do_logout(decode(status["name_id"]), status["entity_ids"], status["reason"], status["not_on_or_after"], status["sign"], sign_alg=sign_alg, digest_alg=digest_alg)
python
def handle_logout_response(self, response, sign_alg=None, digest_alg=None): logger.info("state: %s", self.state) status = self.state[response.in_response_to] logger.info("status: %s", status) issuer = response.issuer() logger.info("issuer: %s", issuer) del self.state[response.in_response_to] if status["entity_ids"] == [issuer]: # done self.local_logout(decode(status["name_id"])) return 0, "200 Ok", [("Content-type", "text/html")], [] else: status["entity_ids"].remove(issuer) if "sign_alg" in status: sign_alg = status["sign_alg"] return self.do_logout(decode(status["name_id"]), status["entity_ids"], status["reason"], status["not_on_or_after"], status["sign"], sign_alg=sign_alg, digest_alg=digest_alg)
[ "def", "handle_logout_response", "(", "self", ",", "response", ",", "sign_alg", "=", "None", ",", "digest_alg", "=", "None", ")", ":", "logger", ".", "info", "(", "\"state: %s\"", ",", "self", ".", "state", ")", "status", "=", "self", ".", "state", "[", ...
handles a Logout response :param response: A response.Response instance :return: 4-tuple of (session_id of the last sent logout request, response message, response headers and message)
[ "handles", "a", "Logout", "response" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client.py#L295-L320
232,580
IdentityPython/pysaml2
src/saml2/client.py
Saml2Client.do_attribute_query
def do_attribute_query(self, entityid, subject_id, attribute=None, sp_name_qualifier=None, name_qualifier=None, nameid_format=None, real_id=None, consent=None, extensions=None, sign=False, binding=BINDING_SOAP, nsprefix=None): """ Does a attribute request to an attribute authority, this is by default done over SOAP. :param entityid: To whom the query should be sent :param subject_id: The identifier of the subject :param attribute: A dictionary of attributes and values that is asked for :param sp_name_qualifier: The unique identifier of the service provider or affiliation of providers for whom the identifier was generated. :param name_qualifier: The unique identifier of the identity provider that generated the identifier. :param nameid_format: The format of the name ID :param real_id: The identifier which is the key to this entity in the identity database :param binding: Which binding to use :param nsprefix: Namespace prefixes preferred before those automatically produced. :return: The attributes returned if BINDING_SOAP was used. HTTP args if BINDING_HTT_POST was used. """ if real_id: response_args = {"real_id": real_id} else: response_args = {} if not binding: binding, destination = self.pick_binding("attribute_service", None, "attribute_authority", entity_id=entityid) else: srvs = self.metadata.attribute_service(entityid, binding) if srvs is []: raise SAMLError("No attribute service support at entity") destination = destinations(srvs)[0] if binding == BINDING_SOAP: return self._use_soap(destination, "attribute_query", consent=consent, extensions=extensions, sign=sign, subject_id=subject_id, attribute=attribute, sp_name_qualifier=sp_name_qualifier, name_qualifier=name_qualifier, format=nameid_format, response_args=response_args) elif binding == BINDING_HTTP_POST: mid = sid() query = self.create_attribute_query(destination, subject_id, attribute, mid, consent, extensions, sign, nsprefix) self.state[query.id] = {"entity_id": entityid, "operation": "AttributeQuery", "subject_id": subject_id, "sign": sign} relay_state = self._relay_state(query.id) return self.apply_binding(binding, "%s" % query, destination, relay_state, sign=sign) else: raise SAMLError("Unsupported binding")
python
def do_attribute_query(self, entityid, subject_id, attribute=None, sp_name_qualifier=None, name_qualifier=None, nameid_format=None, real_id=None, consent=None, extensions=None, sign=False, binding=BINDING_SOAP, nsprefix=None): if real_id: response_args = {"real_id": real_id} else: response_args = {} if not binding: binding, destination = self.pick_binding("attribute_service", None, "attribute_authority", entity_id=entityid) else: srvs = self.metadata.attribute_service(entityid, binding) if srvs is []: raise SAMLError("No attribute service support at entity") destination = destinations(srvs)[0] if binding == BINDING_SOAP: return self._use_soap(destination, "attribute_query", consent=consent, extensions=extensions, sign=sign, subject_id=subject_id, attribute=attribute, sp_name_qualifier=sp_name_qualifier, name_qualifier=name_qualifier, format=nameid_format, response_args=response_args) elif binding == BINDING_HTTP_POST: mid = sid() query = self.create_attribute_query(destination, subject_id, attribute, mid, consent, extensions, sign, nsprefix) self.state[query.id] = {"entity_id": entityid, "operation": "AttributeQuery", "subject_id": subject_id, "sign": sign} relay_state = self._relay_state(query.id) return self.apply_binding(binding, "%s" % query, destination, relay_state, sign=sign) else: raise SAMLError("Unsupported binding")
[ "def", "do_attribute_query", "(", "self", ",", "entityid", ",", "subject_id", ",", "attribute", "=", "None", ",", "sp_name_qualifier", "=", "None", ",", "name_qualifier", "=", "None", ",", "nameid_format", "=", "None", ",", "real_id", "=", "None", ",", "cons...
Does a attribute request to an attribute authority, this is by default done over SOAP. :param entityid: To whom the query should be sent :param subject_id: The identifier of the subject :param attribute: A dictionary of attributes and values that is asked for :param sp_name_qualifier: The unique identifier of the service provider or affiliation of providers for whom the identifier was generated. :param name_qualifier: The unique identifier of the identity provider that generated the identifier. :param nameid_format: The format of the name ID :param real_id: The identifier which is the key to this entity in the identity database :param binding: Which binding to use :param nsprefix: Namespace prefixes preferred before those automatically produced. :return: The attributes returned if BINDING_SOAP was used. HTTP args if BINDING_HTT_POST was used.
[ "Does", "a", "attribute", "request", "to", "an", "attribute", "authority", "this", "is", "by", "default", "done", "over", "SOAP", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client.py#L417-L483
232,581
IdentityPython/pysaml2
src/saml2/time_util.py
before
def before(point): """ True if point datetime specification is before now. NOTE: If point is specified it is supposed to be in local time. Not UTC/GMT !! This is because that is what gmtime() expects. """ if not point: return True if isinstance(point, six.string_types): point = str_to_time(point) elif isinstance(point, int): point = time.gmtime(point) return time.gmtime() <= point
python
def before(point): if not point: return True if isinstance(point, six.string_types): point = str_to_time(point) elif isinstance(point, int): point = time.gmtime(point) return time.gmtime() <= point
[ "def", "before", "(", "point", ")", ":", "if", "not", "point", ":", "return", "True", "if", "isinstance", "(", "point", ",", "six", ".", "string_types", ")", ":", "point", "=", "str_to_time", "(", "point", ")", "elif", "isinstance", "(", "point", ",", ...
True if point datetime specification is before now. NOTE: If point is specified it is supposed to be in local time. Not UTC/GMT !! This is because that is what gmtime() expects.
[ "True", "if", "point", "datetime", "specification", "is", "before", "now", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/time_util.py#L269-L283
232,582
IdentityPython/pysaml2
src/saml2/ecp_client.py
Client.phase2
def phase2(self, authn_request, rc_url, idp_entity_id, headers=None, sign=False, **kwargs): """ Doing the second phase of the ECP conversation, the conversation with the IdP happens. :param authn_request: The AuthenticationRequest :param rc_url: The assertion consumer service url of the SP :param idp_entity_id: The EntityID of the IdP :param headers: Possible extra headers :param sign: If the message should be signed :return: The response from the IdP """ _, destination = self.pick_binding("single_sign_on_service", [BINDING_SOAP], "idpsso", entity_id=idp_entity_id) ht_args = self.apply_binding(BINDING_SOAP, authn_request, destination, sign=sign) if headers: ht_args["headers"].extend(headers) logger.debug("[P2] Sending request: %s", ht_args["data"]) # POST the request to the IdP response = self.send(**ht_args) logger.debug("[P2] Got IdP response: %s", response) if response.status_code != 200: raise SAMLError( "Request to IdP failed (%s): %s" % (response.status_code, response.text)) # SAMLP response in a SOAP envelope body, ecp response in headers respdict = self.parse_soap_message(response.text) if respdict is None: raise SAMLError("Unexpected reply from the IdP") logger.debug("[P2] IdP response dict: %s", respdict) idp_response = respdict["body"] assert idp_response.c_tag == "Response" logger.debug("[P2] IdP AUTHN response: %s", idp_response) _ecp_response = None for item in respdict["header"]: if item.c_tag == "Response" and item.c_namespace == ecp.NAMESPACE: _ecp_response = item _acs_url = _ecp_response.assertion_consumer_service_url if rc_url != _acs_url: error = ("response_consumer_url '%s' does not match" % rc_url, "assertion_consumer_service_url '%s" % _acs_url) # Send an error message to the SP _ = self.send(rc_url, "POST", data=soap.soap_fault(error)) # Raise an exception so the user knows something went wrong raise SAMLError(error) return idp_response
python
def phase2(self, authn_request, rc_url, idp_entity_id, headers=None, sign=False, **kwargs): _, destination = self.pick_binding("single_sign_on_service", [BINDING_SOAP], "idpsso", entity_id=idp_entity_id) ht_args = self.apply_binding(BINDING_SOAP, authn_request, destination, sign=sign) if headers: ht_args["headers"].extend(headers) logger.debug("[P2] Sending request: %s", ht_args["data"]) # POST the request to the IdP response = self.send(**ht_args) logger.debug("[P2] Got IdP response: %s", response) if response.status_code != 200: raise SAMLError( "Request to IdP failed (%s): %s" % (response.status_code, response.text)) # SAMLP response in a SOAP envelope body, ecp response in headers respdict = self.parse_soap_message(response.text) if respdict is None: raise SAMLError("Unexpected reply from the IdP") logger.debug("[P2] IdP response dict: %s", respdict) idp_response = respdict["body"] assert idp_response.c_tag == "Response" logger.debug("[P2] IdP AUTHN response: %s", idp_response) _ecp_response = None for item in respdict["header"]: if item.c_tag == "Response" and item.c_namespace == ecp.NAMESPACE: _ecp_response = item _acs_url = _ecp_response.assertion_consumer_service_url if rc_url != _acs_url: error = ("response_consumer_url '%s' does not match" % rc_url, "assertion_consumer_service_url '%s" % _acs_url) # Send an error message to the SP _ = self.send(rc_url, "POST", data=soap.soap_fault(error)) # Raise an exception so the user knows something went wrong raise SAMLError(error) return idp_response
[ "def", "phase2", "(", "self", ",", "authn_request", ",", "rc_url", ",", "idp_entity_id", ",", "headers", "=", "None", ",", "sign", "=", "False", ",", "*", "*", "kwargs", ")", ":", "_", ",", "destination", "=", "self", ".", "pick_binding", "(", "\"singl...
Doing the second phase of the ECP conversation, the conversation with the IdP happens. :param authn_request: The AuthenticationRequest :param rc_url: The assertion consumer service url of the SP :param idp_entity_id: The EntityID of the IdP :param headers: Possible extra headers :param sign: If the message should be signed :return: The response from the IdP
[ "Doing", "the", "second", "phase", "of", "the", "ECP", "conversation", "the", "conversation", "with", "the", "IdP", "happens", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ecp_client.py#L94-L157
232,583
IdentityPython/pysaml2
src/saml2/ecp_client.py
Client.operation
def operation(self, url, idp_entity_id, op, **opargs): """ This is the method that should be used by someone that wants to authenticate using SAML ECP :param url: The page that access is sought for :param idp_entity_id: The entity ID of the IdP that should be used for authentication :param op: Which HTTP operation (GET/POST/PUT/DELETE) :param opargs: Arguments to the HTTP call :return: The page """ sp_url = self._sp # ******************************************** # Phase 1 - First conversation with the SP # ******************************************** # headers needed to indicate to the SP that I'm ECP enabled opargs["headers"] = self.add_paos_headers(opargs["headers"]) response = self.send(sp_url, op, **opargs) logger.debug("[Op] SP response: %s" % response) print(response.text) if response.status_code != 200: raise SAMLError( "Request to SP failed: %s" % response.text) # The response might be a AuthnRequest instance in a SOAP envelope # body. If so it's the start of the ECP conversation # Two SOAP header blocks; paos:Request and ecp:Request # may also contain a ecp:RelayState SOAP header block # If channel-binding was part of the PAOS header any number of # <cb:ChannelBindings> header blocks may also be present # if 'holder-of-key' option then one or more <ecp:SubjectConfirmation> # header blocks may also be present try: respdict = self.parse_soap_message(response.text) self.ecp_conversation(respdict, idp_entity_id) # should by now be authenticated so this should go smoothly response = self.send(url, op, **opargs) except (soap.XmlParseError, AssertionError, KeyError): raise if response.status_code >= 400: raise SAMLError("Error performing operation: %s" % ( response.text,)) return response
python
def operation(self, url, idp_entity_id, op, **opargs): sp_url = self._sp # ******************************************** # Phase 1 - First conversation with the SP # ******************************************** # headers needed to indicate to the SP that I'm ECP enabled opargs["headers"] = self.add_paos_headers(opargs["headers"]) response = self.send(sp_url, op, **opargs) logger.debug("[Op] SP response: %s" % response) print(response.text) if response.status_code != 200: raise SAMLError( "Request to SP failed: %s" % response.text) # The response might be a AuthnRequest instance in a SOAP envelope # body. If so it's the start of the ECP conversation # Two SOAP header blocks; paos:Request and ecp:Request # may also contain a ecp:RelayState SOAP header block # If channel-binding was part of the PAOS header any number of # <cb:ChannelBindings> header blocks may also be present # if 'holder-of-key' option then one or more <ecp:SubjectConfirmation> # header blocks may also be present try: respdict = self.parse_soap_message(response.text) self.ecp_conversation(respdict, idp_entity_id) # should by now be authenticated so this should go smoothly response = self.send(url, op, **opargs) except (soap.XmlParseError, AssertionError, KeyError): raise if response.status_code >= 400: raise SAMLError("Error performing operation: %s" % ( response.text,)) return response
[ "def", "operation", "(", "self", ",", "url", ",", "idp_entity_id", ",", "op", ",", "*", "*", "opargs", ")", ":", "sp_url", "=", "self", ".", "_sp", "# ********************************************", "# Phase 1 - First conversation with the SP", "# ***********************...
This is the method that should be used by someone that wants to authenticate using SAML ECP :param url: The page that access is sought for :param idp_entity_id: The entity ID of the IdP that should be used for authentication :param op: Which HTTP operation (GET/POST/PUT/DELETE) :param opargs: Arguments to the HTTP call :return: The page
[ "This", "is", "the", "method", "that", "should", "be", "used", "by", "someone", "that", "wants", "to", "authenticate", "using", "SAML", "ECP" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/ecp_client.py#L250-L299
232,584
IdentityPython/pysaml2
src/saml2/mdbcache.py
Cache.subjects
def subjects(self): """ Return identifiers for all the subjects that are in the cache. :return: list of subject identifiers """ subj = [i["subject_id"] for i in self._cache.find()] return list(set(subj))
python
def subjects(self): subj = [i["subject_id"] for i in self._cache.find()] return list(set(subj))
[ "def", "subjects", "(", "self", ")", ":", "subj", "=", "[", "i", "[", "\"subject_id\"", "]", "for", "i", "in", "self", ".", "_cache", ".", "find", "(", ")", "]", "return", "list", "(", "set", "(", "subj", ")", ")" ]
Return identifiers for all the subjects that are in the cache. :return: list of subject identifiers
[ "Return", "identifiers", "for", "all", "the", "subjects", "that", "are", "in", "the", "cache", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/mdbcache.py#L174-L182
232,585
IdentityPython/pysaml2
src/saml2/cache.py
Cache.set
def set(self, name_id, entity_id, info, not_on_or_after=0): """ Stores session information in the cache. Assumes that the name_id is unique within the context of the Service Provider. :param name_id: The subject identifier, a NameID instance :param entity_id: The identifier of the entity_id/receiver of an assertion :param info: The session info, the assertion is part of this :param not_on_or_after: A time after which the assertion is not valid. """ info = dict(info) if 'name_id' in info and not isinstance(info['name_id'], six.string_types): # make friendly to (JSON) serialization info['name_id'] = code(name_id) cni = code(name_id) if cni not in self._db: self._db[cni] = {} self._db[cni][entity_id] = (not_on_or_after, info) if self._sync: try: self._db.sync() except AttributeError: pass
python
def set(self, name_id, entity_id, info, not_on_or_after=0): info = dict(info) if 'name_id' in info and not isinstance(info['name_id'], six.string_types): # make friendly to (JSON) serialization info['name_id'] = code(name_id) cni = code(name_id) if cni not in self._db: self._db[cni] = {} self._db[cni][entity_id] = (not_on_or_after, info) if self._sync: try: self._db.sync() except AttributeError: pass
[ "def", "set", "(", "self", ",", "name_id", ",", "entity_id", ",", "info", ",", "not_on_or_after", "=", "0", ")", ":", "info", "=", "dict", "(", "info", ")", "if", "'name_id'", "in", "info", "and", "not", "isinstance", "(", "info", "[", "'name_id'", "...
Stores session information in the cache. Assumes that the name_id is unique within the context of the Service Provider. :param name_id: The subject identifier, a NameID instance :param entity_id: The identifier of the entity_id/receiver of an assertion :param info: The session info, the assertion is part of this :param not_on_or_after: A time after which the assertion is not valid.
[ "Stores", "session", "information", "in", "the", "cache", ".", "Assumes", "that", "the", "name_id", "is", "unique", "within", "the", "context", "of", "the", "Service", "Provider", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/cache.py#L107-L131
232,586
IdentityPython/pysaml2
src/saml2/__init__.py
create_class_from_xml_string
def create_class_from_xml_string(target_class, xml_string): """Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param xml_string: A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. :return: An instance of the target class with members assigned according to the contents of the XML - or None if the root XML tag and namespace did not match those of the target class. """ if not isinstance(xml_string, six.binary_type): xml_string = xml_string.encode('utf-8') tree = defusedxml.ElementTree.fromstring(xml_string) return create_class_from_element_tree(target_class, tree)
python
def create_class_from_xml_string(target_class, xml_string): if not isinstance(xml_string, six.binary_type): xml_string = xml_string.encode('utf-8') tree = defusedxml.ElementTree.fromstring(xml_string) return create_class_from_element_tree(target_class, tree)
[ "def", "create_class_from_xml_string", "(", "target_class", ",", "xml_string", ")", ":", "if", "not", "isinstance", "(", "xml_string", ",", "six", ".", "binary_type", ")", ":", "xml_string", "=", "xml_string", ".", "encode", "(", "'utf-8'", ")", "tree", "=", ...
Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param xml_string: A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. :return: An instance of the target class with members assigned according to the contents of the XML - or None if the root XML tag and namespace did not match those of the target class.
[ "Creates", "an", "instance", "of", "the", "target", "class", "from", "a", "string", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L80-L97
232,587
IdentityPython/pysaml2
src/saml2/__init__.py
create_class_from_element_tree
def create_class_from_element_tree(target_class, tree, namespace=None, tag=None): """Instantiates the class and populates members according to the tree. Note: Only use this function with classes that have c_namespace and c_tag class members. :param target_class: The class which will be instantiated and populated with the contents of the XML. :param tree: An element tree whose contents will be converted into members of the new target_class instance. :param namespace: The namespace which the XML tree's root node must match. If omitted, the namespace defaults to the c_namespace of the target class. :param tag: The tag which the XML tree's root node must match. If omitted, the tag defaults to the c_tag class member of the target class. :return: An instance of the target class - or None if the tag and namespace of the XML tree's root node did not match the desired namespace and tag. """ if namespace is None: namespace = target_class.c_namespace if tag is None: tag = target_class.c_tag if tree.tag == '{%s}%s' % (namespace, tag): target = target_class() target.harvest_element_tree(tree) return target else: return None
python
def create_class_from_element_tree(target_class, tree, namespace=None, tag=None): if namespace is None: namespace = target_class.c_namespace if tag is None: tag = target_class.c_tag if tree.tag == '{%s}%s' % (namespace, tag): target = target_class() target.harvest_element_tree(tree) return target else: return None
[ "def", "create_class_from_element_tree", "(", "target_class", ",", "tree", ",", "namespace", "=", "None", ",", "tag", "=", "None", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "target_class", ".", "c_namespace", "if", "tag", "is", "None"...
Instantiates the class and populates members according to the tree. Note: Only use this function with classes that have c_namespace and c_tag class members. :param target_class: The class which will be instantiated and populated with the contents of the XML. :param tree: An element tree whose contents will be converted into members of the new target_class instance. :param namespace: The namespace which the XML tree's root node must match. If omitted, the namespace defaults to the c_namespace of the target class. :param tag: The tag which the XML tree's root node must match. If omitted, the tag defaults to the c_tag class member of the target class. :return: An instance of the target class - or None if the tag and namespace of the XML tree's root node did not match the desired namespace and tag.
[ "Instantiates", "the", "class", "and", "populates", "members", "according", "to", "the", "tree", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L100-L130
232,588
IdentityPython/pysaml2
src/saml2/__init__.py
element_to_extension_element
def element_to_extension_element(element): """ Convert an element into a extension element :param element: The element instance :return: An extension element instance """ exel = ExtensionElement(element.c_tag, element.c_namespace, text=element.text) exel.attributes.update(element.extension_attributes) exel.children.extend(element.extension_elements) for xml_attribute, (member_name, typ, req) in \ iter(element.c_attributes.items()): member_value = getattr(element, member_name) if member_value is not None: exel.attributes[xml_attribute] = member_value exel.children.extend([element_to_extension_element(c) for c in element.children_with_values()]) return exel
python
def element_to_extension_element(element): exel = ExtensionElement(element.c_tag, element.c_namespace, text=element.text) exel.attributes.update(element.extension_attributes) exel.children.extend(element.extension_elements) for xml_attribute, (member_name, typ, req) in \ iter(element.c_attributes.items()): member_value = getattr(element, member_name) if member_value is not None: exel.attributes[xml_attribute] = member_value exel.children.extend([element_to_extension_element(c) for c in element.children_with_values()]) return exel
[ "def", "element_to_extension_element", "(", "element", ")", ":", "exel", "=", "ExtensionElement", "(", "element", ".", "c_tag", ",", "element", ".", "c_namespace", ",", "text", "=", "element", ".", "text", ")", "exel", ".", "attributes", ".", "update", "(", ...
Convert an element into a extension element :param element: The element instance :return: An extension element instance
[ "Convert", "an", "element", "into", "a", "extension", "element" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L926-L949
232,589
IdentityPython/pysaml2
src/saml2/__init__.py
extension_element_to_element
def extension_element_to_element(extension_element, translation_functions, namespace=None): """ Convert an extension element to a normal element. In order to do this you need to have an idea of what type of element it is. Or rather which module it belongs to. :param extension_element: The extension element :param translation_functions: A dictionary with class identifiers as keys and string-to-element translations functions as values :param namespace: The namespace of the translation functions. :return: An element instance or None """ try: element_namespace = extension_element.namespace except AttributeError: element_namespace = extension_element.c_namespace if element_namespace == namespace: try: try: ets = translation_functions[extension_element.tag] except AttributeError: ets = translation_functions[extension_element.c_tag] return ets(extension_element.to_string()) except KeyError: pass return None
python
def extension_element_to_element(extension_element, translation_functions, namespace=None): try: element_namespace = extension_element.namespace except AttributeError: element_namespace = extension_element.c_namespace if element_namespace == namespace: try: try: ets = translation_functions[extension_element.tag] except AttributeError: ets = translation_functions[extension_element.c_tag] return ets(extension_element.to_string()) except KeyError: pass return None
[ "def", "extension_element_to_element", "(", "extension_element", ",", "translation_functions", ",", "namespace", "=", "None", ")", ":", "try", ":", "element_namespace", "=", "extension_element", ".", "namespace", "except", "AttributeError", ":", "element_namespace", "="...
Convert an extension element to a normal element. In order to do this you need to have an idea of what type of element it is. Or rather which module it belongs to. :param extension_element: The extension element :param translation_functions: A dictionary with class identifiers as keys and string-to-element translations functions as values :param namespace: The namespace of the translation functions. :return: An element instance or None
[ "Convert", "an", "extension", "element", "to", "a", "normal", "element", ".", "In", "order", "to", "do", "this", "you", "need", "to", "have", "an", "idea", "of", "what", "type", "of", "element", "it", "is", ".", "Or", "rather", "which", "module", "it",...
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L952-L979
232,590
IdentityPython/pysaml2
src/saml2/__init__.py
extension_elements_to_elements
def extension_elements_to_elements(extension_elements, schemas): """ Create a list of elements each one matching one of the given extension elements. This is of course dependent on the access to schemas that describe the extension elements. :param extension_elements: The list of extension elements :param schemas: Imported Python modules that represent the different known schemas used for the extension elements :return: A list of elements, representing the set of extension elements that was possible to match against a Class in the given schemas. The elements returned are the native representation of the elements according to the schemas. """ res = [] if isinstance(schemas, list): pass elif isinstance(schemas, dict): schemas = list(schemas.values()) else: return res for extension_element in extension_elements: for schema in schemas: inst = extension_element_to_element(extension_element, schema.ELEMENT_FROM_STRING, schema.NAMESPACE) if inst: res.append(inst) break return res
python
def extension_elements_to_elements(extension_elements, schemas): res = [] if isinstance(schemas, list): pass elif isinstance(schemas, dict): schemas = list(schemas.values()) else: return res for extension_element in extension_elements: for schema in schemas: inst = extension_element_to_element(extension_element, schema.ELEMENT_FROM_STRING, schema.NAMESPACE) if inst: res.append(inst) break return res
[ "def", "extension_elements_to_elements", "(", "extension_elements", ",", "schemas", ")", ":", "res", "=", "[", "]", "if", "isinstance", "(", "schemas", ",", "list", ")", ":", "pass", "elif", "isinstance", "(", "schemas", ",", "dict", ")", ":", "schemas", "...
Create a list of elements each one matching one of the given extension elements. This is of course dependent on the access to schemas that describe the extension elements. :param extension_elements: The list of extension elements :param schemas: Imported Python modules that represent the different known schemas used for the extension elements :return: A list of elements, representing the set of extension elements that was possible to match against a Class in the given schemas. The elements returned are the native representation of the elements according to the schemas.
[ "Create", "a", "list", "of", "elements", "each", "one", "matching", "one", "of", "the", "given", "extension", "elements", ".", "This", "is", "of", "course", "dependent", "on", "the", "access", "to", "schemas", "that", "describe", "the", "extension", "element...
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L982-L1013
232,591
IdentityPython/pysaml2
src/saml2/__init__.py
ExtensionElement.loadd
def loadd(self, ava): """ expects a special set of keys """ if "attributes" in ava: for key, val in ava["attributes"].items(): self.attributes[key] = val try: self.tag = ava["tag"] except KeyError: if not self.tag: raise KeyError("ExtensionElement must have a tag") try: self.namespace = ava["namespace"] except KeyError: if not self.namespace: raise KeyError("ExtensionElement must belong to a namespace") try: self.text = ava["text"] except KeyError: pass if "children" in ava: for item in ava["children"]: self.children.append(ExtensionElement(item["tag"]).loadd(item)) return self
python
def loadd(self, ava): if "attributes" in ava: for key, val in ava["attributes"].items(): self.attributes[key] = val try: self.tag = ava["tag"] except KeyError: if not self.tag: raise KeyError("ExtensionElement must have a tag") try: self.namespace = ava["namespace"] except KeyError: if not self.namespace: raise KeyError("ExtensionElement must belong to a namespace") try: self.text = ava["text"] except KeyError: pass if "children" in ava: for item in ava["children"]: self.children.append(ExtensionElement(item["tag"]).loadd(item)) return self
[ "def", "loadd", "(", "self", ",", "ava", ")", ":", "if", "\"attributes\"", "in", "ava", ":", "for", "key", ",", "val", "in", "ava", "[", "\"attributes\"", "]", ".", "items", "(", ")", ":", "self", ".", "attributes", "[", "key", "]", "=", "val", "...
expects a special set of keys
[ "expects", "a", "special", "set", "of", "keys" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L246-L274
232,592
IdentityPython/pysaml2
src/saml2/__init__.py
ExtensionContainer.find_extensions
def find_extensions(self, tag=None, namespace=None): """Searches extension elements for child nodes with the desired name. Returns a list of extension elements within this object whose tag and/or namespace match those passed in. To find all extensions in a particular namespace, specify the namespace but not the tag name. If you specify only the tag, the result list may contain extension elements in multiple namespaces. :param tag: str (optional) The desired tag :param namespace: str (optional) The desired namespace :Return: A list of elements whose tag and/or namespace match the parameters values """ results = [] if tag and namespace: for element in self.extension_elements: if element.tag == tag and element.namespace == namespace: results.append(element) elif tag and not namespace: for element in self.extension_elements: if element.tag == tag: results.append(element) elif namespace and not tag: for element in self.extension_elements: if element.namespace == namespace: results.append(element) else: for element in self.extension_elements: results.append(element) return results
python
def find_extensions(self, tag=None, namespace=None): results = [] if tag and namespace: for element in self.extension_elements: if element.tag == tag and element.namespace == namespace: results.append(element) elif tag and not namespace: for element in self.extension_elements: if element.tag == tag: results.append(element) elif namespace and not tag: for element in self.extension_elements: if element.namespace == namespace: results.append(element) else: for element in self.extension_elements: results.append(element) return results
[ "def", "find_extensions", "(", "self", ",", "tag", "=", "None", ",", "namespace", "=", "None", ")", ":", "results", "=", "[", "]", "if", "tag", "and", "namespace", ":", "for", "element", "in", "self", ".", "extension_elements", ":", "if", "element", "....
Searches extension elements for child nodes with the desired name. Returns a list of extension elements within this object whose tag and/or namespace match those passed in. To find all extensions in a particular namespace, specify the namespace but not the tag name. If you specify only the tag, the result list may contain extension elements in multiple namespaces. :param tag: str (optional) The desired tag :param namespace: str (optional) The desired namespace :Return: A list of elements whose tag and/or namespace match the parameters values
[ "Searches", "extension", "elements", "for", "child", "nodes", "with", "the", "desired", "name", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L335-L369
232,593
IdentityPython/pysaml2
src/saml2/__init__.py
ExtensionContainer.extensions_as_elements
def extensions_as_elements(self, tag, schema): """ Return extensions that has the given tag and belongs to the given schema as native elements of that schema. :param tag: The tag of the element :param schema: Which schema the element should originate from :return: a list of native elements """ result = [] for ext in self.find_extensions(tag, schema.NAMESPACE): ets = schema.ELEMENT_FROM_STRING[tag] result.append(ets(ext.to_string())) return result
python
def extensions_as_elements(self, tag, schema): result = [] for ext in self.find_extensions(tag, schema.NAMESPACE): ets = schema.ELEMENT_FROM_STRING[tag] result.append(ets(ext.to_string())) return result
[ "def", "extensions_as_elements", "(", "self", ",", "tag", ",", "schema", ")", ":", "result", "=", "[", "]", "for", "ext", "in", "self", ".", "find_extensions", "(", "tag", ",", "schema", ".", "NAMESPACE", ")", ":", "ets", "=", "schema", ".", "ELEMENT_F...
Return extensions that has the given tag and belongs to the given schema as native elements of that schema. :param tag: The tag of the element :param schema: Which schema the element should originate from :return: a list of native elements
[ "Return", "extensions", "that", "has", "the", "given", "tag", "and", "belongs", "to", "the", "given", "schema", "as", "native", "elements", "of", "that", "schema", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L371-L383
232,594
IdentityPython/pysaml2
src/saml2/__init__.py
SamlBase.register_prefix
def register_prefix(self, nspair): """ Register with ElementTree a set of namespaces :param nspair: A dictionary of prefixes and uris to use when constructing the text representation. :return: """ for prefix, uri in nspair.items(): try: ElementTree.register_namespace(prefix, uri) except AttributeError: # Backwards compatibility with ET < 1.3 ElementTree._namespace_map[uri] = prefix except ValueError: pass
python
def register_prefix(self, nspair): for prefix, uri in nspair.items(): try: ElementTree.register_namespace(prefix, uri) except AttributeError: # Backwards compatibility with ET < 1.3 ElementTree._namespace_map[uri] = prefix except ValueError: pass
[ "def", "register_prefix", "(", "self", ",", "nspair", ")", ":", "for", "prefix", ",", "uri", "in", "nspair", ".", "items", "(", ")", ":", "try", ":", "ElementTree", ".", "register_namespace", "(", "prefix", ",", "uri", ")", "except", "AttributeError", ":...
Register with ElementTree a set of namespaces :param nspair: A dictionary of prefixes and uris to use when constructing the text representation. :return:
[ "Register", "with", "ElementTree", "a", "set", "of", "namespaces" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L555-L570
232,595
IdentityPython/pysaml2
src/saml2/__init__.py
SamlBase.get_xml_string_with_self_contained_assertion_within_encrypted_assertion
def get_xml_string_with_self_contained_assertion_within_encrypted_assertion( self, assertion_tag): """ Makes a encrypted assertion only containing self contained namespaces. :param assertion_tag: Tag for the assertion to be transformed. :return: A new samlp.Resonse in string representation. """ prefix_map = self.get_prefix_map( [self.encrypted_assertion._to_element_tree().find(assertion_tag)]) tree = self._to_element_tree() self.set_prefixes( tree.find( self.encrypted_assertion._to_element_tree().tag).find( assertion_tag), prefix_map) return ElementTree.tostring(tree, encoding="UTF-8").decode('utf-8')
python
def get_xml_string_with_self_contained_assertion_within_encrypted_assertion( self, assertion_tag): prefix_map = self.get_prefix_map( [self.encrypted_assertion._to_element_tree().find(assertion_tag)]) tree = self._to_element_tree() self.set_prefixes( tree.find( self.encrypted_assertion._to_element_tree().tag).find( assertion_tag), prefix_map) return ElementTree.tostring(tree, encoding="UTF-8").decode('utf-8')
[ "def", "get_xml_string_with_self_contained_assertion_within_encrypted_assertion", "(", "self", ",", "assertion_tag", ")", ":", "prefix_map", "=", "self", ".", "get_prefix_map", "(", "[", "self", ".", "encrypted_assertion", ".", "_to_element_tree", "(", ")", ".", "find",...
Makes a encrypted assertion only containing self contained namespaces. :param assertion_tag: Tag for the assertion to be transformed. :return: A new samlp.Resonse in string representation.
[ "Makes", "a", "encrypted", "assertion", "only", "containing", "self", "contained", "namespaces", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L621-L639
232,596
IdentityPython/pysaml2
src/saml2/__init__.py
SamlBase.to_string
def to_string(self, nspair=None): """Converts the Saml object to a string containing XML. :param nspair: A dictionary of prefixes and uris to use when constructing the text representation. :return: String representation of the object """ if not nspair and self.c_ns_prefix: nspair = self.c_ns_prefix if nspair: self.register_prefix(nspair) return ElementTree.tostring(self._to_element_tree(), encoding="UTF-8")
python
def to_string(self, nspair=None): if not nspair and self.c_ns_prefix: nspair = self.c_ns_prefix if nspair: self.register_prefix(nspair) return ElementTree.tostring(self._to_element_tree(), encoding="UTF-8")
[ "def", "to_string", "(", "self", ",", "nspair", "=", "None", ")", ":", "if", "not", "nspair", "and", "self", ".", "c_ns_prefix", ":", "nspair", "=", "self", ".", "c_ns_prefix", "if", "nspair", ":", "self", ".", "register_prefix", "(", "nspair", ")", "r...
Converts the Saml object to a string containing XML. :param nspair: A dictionary of prefixes and uris to use when constructing the text representation. :return: String representation of the object
[ "Converts", "the", "Saml", "object", "to", "a", "string", "containing", "XML", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L690-L703
232,597
IdentityPython/pysaml2
src/saml2/__init__.py
SamlBase.keys
def keys(self): """ Return all the keys that represent possible attributes and children. :return: list of keys """ keys = ['text'] keys.extend([n for (n, t, r) in self.c_attributes.values()]) keys.extend([v[0] for v in self.c_children.values()]) return keys
python
def keys(self): keys = ['text'] keys.extend([n for (n, t, r) in self.c_attributes.values()]) keys.extend([v[0] for v in self.c_children.values()]) return keys
[ "def", "keys", "(", "self", ")", ":", "keys", "=", "[", "'text'", "]", "keys", ".", "extend", "(", "[", "n", "for", "(", "n", ",", "t", ",", "r", ")", "in", "self", ".", "c_attributes", ".", "values", "(", ")", "]", ")", "keys", ".", "extend"...
Return all the keys that represent possible attributes and children. :return: list of keys
[ "Return", "all", "the", "keys", "that", "represent", "possible", "attributes", "and", "children", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L719-L728
232,598
IdentityPython/pysaml2
src/saml2/__init__.py
SamlBase.children_with_values
def children_with_values(self): """ Returns all children that has values :return: Possibly empty list of children. """ childs = [] for attribute in self._get_all_c_children_with_order(): member = getattr(self, attribute) if member is None or member == []: pass elif isinstance(member, list): for instance in member: childs.append(instance) else: childs.append(member) return childs
python
def children_with_values(self): childs = [] for attribute in self._get_all_c_children_with_order(): member = getattr(self, attribute) if member is None or member == []: pass elif isinstance(member, list): for instance in member: childs.append(instance) else: childs.append(member) return childs
[ "def", "children_with_values", "(", "self", ")", ":", "childs", "=", "[", "]", "for", "attribute", "in", "self", ".", "_get_all_c_children_with_order", "(", ")", ":", "member", "=", "getattr", "(", "self", ",", "attribute", ")", "if", "member", "is", "None...
Returns all children that has values :return: Possibly empty list of children.
[ "Returns", "all", "children", "that", "has", "values" ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L730-L745
232,599
IdentityPython/pysaml2
src/saml2/__init__.py
SamlBase.set_text
def set_text(self, val, base64encode=False): """ Sets the text property of this instance. :param val: The value of the text property :param base64encode: Whether the value should be base64encoded :return: The instance """ # print("set_text: %s" % (val,)) if isinstance(val, bool): if val: setattr(self, "text", "true") else: setattr(self, "text", "false") elif isinstance(val, int): setattr(self, "text", "%d" % val) elif isinstance(val, six.string_types): setattr(self, "text", val) elif val is None: pass else: raise ValueError("Type shouldn't be '%s'" % (val,)) return self
python
def set_text(self, val, base64encode=False): # print("set_text: %s" % (val,)) if isinstance(val, bool): if val: setattr(self, "text", "true") else: setattr(self, "text", "false") elif isinstance(val, int): setattr(self, "text", "%d" % val) elif isinstance(val, six.string_types): setattr(self, "text", val) elif val is None: pass else: raise ValueError("Type shouldn't be '%s'" % (val,)) return self
[ "def", "set_text", "(", "self", ",", "val", ",", "base64encode", "=", "False", ")", ":", "# print(\"set_text: %s\" % (val,))", "if", "isinstance", "(", "val", ",", "bool", ")", ":", "if", "val", ":", "setattr", "(", "self", ",", "\"text\"", ",", "\"true\""...
Sets the text property of this instance. :param val: The value of the text property :param base64encode: Whether the value should be base64encoded :return: The instance
[ "Sets", "the", "text", "property", "of", "this", "instance", "." ]
d3aa78eeb7d37c12688f783cb4db1c7263a14ad6
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L748-L771