Beispiel #1
0
    def __init__(self,
                 identifiers=None,
                 remembered=False,
                 authenticated=False,
                 host=None,
                 session=None,
                 session_creation_enabled=True,
                 security_manager=None):

        self._identifiers = None

        self.security_manager = security_manager
        self.identifiers = identifiers
        self.remembered = remembered
        self.authenticated = authenticated
        self.host = host
        if session is not None:
            session.stop_session_callback = self.session_stopped
            self.session = session
        else:
            self.session = None

        self.session_creation_enabled = session_creation_enabled
        self.run_as_identifiers_session_key = 'run_as_identifiers_session_key'
        self._logger = get_logger()
Beispiel #2
0
 def __init__(self, settings, session_handler=NativeSessionHandler()):
     session_settings = SessionSettings(settings)
     self.absolute_timeout = session_settings.absolute_timeout
     self.idle_timeout = session_settings.idle_timeout
     self.event_bus = None
     self.session_handler = session_handler
     self._logger = get_logger()
Beispiel #3
0
    def __init__(self,
                 yosai,
                 settings,
                 realms=None,
                 cache_handler=None,
                 authenticator=None,
                 authorizer=ModularRealmAuthorizer(),
                 serialization_manager=None,
                 session_manager=None,
                 remember_me_manager=None,
                 subject_store=SubjectStore()):
        self._logger = get_logger()
        self.yosai = yosai
        self.subject_store = subject_store
        self.realms = realms
        self.remember_me_manager = remember_me_manager

        if not session_manager:
            session_manager = NativeSessionManager(settings)
        self.session_manager = session_manager

        self.authorizer = authorizer

        if not authenticator:
            authenticator = DefaultAuthenticator(settings)
        self.authenticator = authenticator

        if serialization_manager and self.remember_me_manager:
            self.remember_me_manager.serialization_manager = serialization_manager

        self.apply_event_bus(event_bus)

        self.apply_cache_handler(cache_handler)
        self.apply_realms()
Beispiel #4
0
    def __init__(self, settings):
        self._logger = get_logger()
        default_cipher_key = RememberMeSettings(settings).default_cipher_key

        # new to yosai.core.
        self.serialization_manager = None

        self.encryption_cipher_key = default_cipher_key
        self.decryption_cipher_key = default_cipher_key
Beispiel #5
0
 def __init__(self, yosai, security_manager):
     self.account_id = None
     self.authentication_token = None
     self.authenticated = None
     self.identifiers = None
     self.host = None
     self.security_manager = security_manager
     self.yosai = yosai
     self.session = None
     self.session_id = None
     self.session_creation_enabled = True
     self.subject = None
     self._logger = get_logger()
Beispiel #6
0
 def __init__(self, settings):
     # type: (LazySettings) -> None
     """
     :param settings: lazy settings from yosai
     """
     settings = settings.ACCOUNT_STORE
     self._settings = settings
     self._uri = settings['uri']
     self._dbname = settings['dbname']
     self._retry_limit = settings['retry_limit']
     self._client = MongoClient(self._uri)
     self._db = self._client[self._dbname]
     self._logger = get_logger()
Beispiel #7
0
    def __init__(self, eventbus):
        self._logger = get_logger()
        eventbus.subscribe(self.log_session_event, 'SESSION.START')
        eventbus.subscribe(self.log_session_event, 'SESSION.STOP')
        eventbus.subscribe(self.log_session_event, 'SESSION.EXPIRE')

        eventbus.subscribe(self.log_authc_event, 'AUTHENTICATION.ACCOUNT_NOT_FOUND')
        eventbus.subscribe(self.log_authc_event, 'AUTHENTICATION.PROGRESS')
        eventbus.subscribe(self.log_authc_event, 'AUTHENTICATION.SUCCEEDED')

        eventbus.subscribe(self.log_authc_event, 'AUTHENTICATION.FAILED')
        eventbus.subscribe(self.log_authz_event, 'AUTHORIZATION.GRANTED')
        eventbus.subscribe(self.log_authz_event, 'AUTHORIZATION.DENIED')
        eventbus.subscribe(self.log_authz_event, 'AUTHORIZATION.RESULTS')
Beispiel #8
0
 def __init__(self,
              source_name=None,
              identifier=None,
              identifier_collection=None):
     """
     :type source_name: String
     :type identifier: String or ?
     :type identifier_collection:  subject_abcs.IdentifierCollection
     """
     self.source_identifiers = collections.OrderedDict()
     self._primary_identifier = None
     self._logger = get_logger()
     if identifier_collection:
         self.add_collection(identifier_collection=identifier_collection)
     elif source_name and identifier:
         self.add(source_name=source_name, identifier=identifier)
Beispiel #9
0
    def __init__(self,
                 name='AccountStoreRealm_' + str(uuid4()),
                 account_store=None,
                 authc_verifiers=None,
                 permission_verifier=DefaultPermissionVerifier()):
        """
        :authc_verifiers: tuple of Verifier objects
        """
        self.name = name
        self._logger = get_logger()
        self.account_store = account_store
        self.authc_verifiers = authc_verifiers  # a tuple
        self.permission_verifier = permission_verifier

        self.cache_handler = None
        self.token_resolver = self.init_token_resolver()
Beispiel #10
0
    def __init__(self, settings, strategy=first_realm_successful_strategy):

        self.authc_settings = AuthenticationSettings(settings)
        self.authentication_strategy = strategy

        try:
            dconfig = self.authc_settings.mfa_dispatcher_config
            self.mfa_dispatcher = self.authc_settings.mfa_dispatcher(dconfig)
        except TypeError:
            self.mfa_dispatcher = None

        self.realms = None
        self.token_realm_resolver = None
        self.locking_realm = None
        self.locking_limit = None
        self.event_bus = None
        self._logger = get_logger()
Beispiel #11
0
    def __init__(self, absolute_timeout, idle_timeout, host=None):
        super(SimpleSession, self).__init__()
        self.attributes = {}
        self.internal_attributes = {
            'run_as_identifiers_session_key': None,
            'authenticated_session_key': None,
            'identifiers_session_key': None
        }
        self.is_expired = None

        self.stop_timestamp = None
        self.start_timestamp = round(time.time() * 1000)  # milliseconds

        self.last_access_time = self.start_timestamp

        self.absolute_timeout = absolute_timeout
        self.idle_timeout = idle_timeout

        self.host = host
        self._logger = get_logger()
Beispiel #12
0
 def __init__(self):
     self._schemas = {list.__name__: ListSchema, dict.__name__: DictSchema}
     self._logger = get_logger()
Beispiel #13
0
 def __init__(self):
     self._logger = get_logger()
Beispiel #14
0
class Yosai(object):
    _logger = get_logger()

    def __init__(self, env_var=None, file_path=None, session_attributes=None):
        """
        :type session_attributes: tuple
        """
        # you can configure LazySettings in one of two ways: env or file_path
        self.settings = LazySettings(env_var=env_var, file_path=file_path)
        self.security_manager = \
            self.generate_security_manager(self.settings, session_attributes)

    def generate_security_manager(self, settings, session_attributes):
        # don't forget to pass default_cipher_key into the WebSecurityManager
        mgr_builder = SecurityManagerCreator()
        return mgr_builder.create_manager(self, settings, session_attributes)

    def _get_subject(self):
        """
        Returns the currently accessible Subject available to the calling code
        depending on runtime environment.

        :returns: the Subject currently accessible to the calling code
        """
        subject_context = SubjectContext(
            yosai=self, security_manager=self.security_manager)
        subject = self.security_manager.create_subject(
            subject_context=subject_context)
        global_subject_context.stack.append(subject)
        return subject

    @staticmethod
    @contextmanager
    def context(yosai):
        global_yosai_context.stack.append(yosai)

        try:
            yield
        except:
            raise
        finally:
            global_yosai_context.stack = []
            global_subject_context.stack = []

    @classmethod
    def get_current_subject(cls):
        try:
            subject = global_subject_context.stack[-1]
            msg = ('A subject instance DOES exist in the global context. '
                   'Touching and then returning it.')
            cls._logger.debug(msg)
            subject.get_session().touch()
            return subject

        except IndexError:
            msg = 'A subject instance _DOES NOT_ exist in the global context.  Creating one.'
            cls._logger.debug(msg)

            subject = Yosai.get_current_yosai()._get_subject()

            global_subject_context.stack.append(subject)
            return subject

    @staticmethod
    def get_current_yosai():
        try:
            return global_yosai_context.stack[-1]
        except IndexError:
            msg = 'A yosai instance does not exist in the global context.'
            raise IndexError(msg)

    @staticmethod
    def requires_authentication(fn):
        """
        Requires that the calling Subject be authenticated before allowing access.

        :raises UnauthenticatedException: indicating that the decorated method is
                                          not allowed to be executed because the
                                          Subject failed to authenticate
        """
        @functools.wraps(fn)
        def wrap(*args, **kwargs):
            subject = Yosai.get_current_subject()

            if not subject.authenticated:
                msg = "The current Subject is not authenticated.  ACCESS DENIED."
                raise UnauthenticatedException(msg)

            return fn(*args, **kwargs)

        return wrap

    @staticmethod
    def requires_user(fn):
        """
        Requires that the calling Subject be *either* authenticated *or* remembered
        via RememberMe services before allowing access.

        This method essentially ensures that subject.identifiers IS NOT None

        :raises UnauthenticatedException: indicating that the decorated method is
                                          not allowed to be executed because the
                                          Subject attempted to perform a user-only
                                          operation
        """
        @functools.wraps(fn)
        def wrap(*args, **kwargs):
            subject = Yosai.get_current_subject()

            if subject.identifiers is None:
                msg = ("Attempting to perform a user-only operation.  The "
                       "current Subject is NOT a user (they haven't been "
                       "authenticated or remembered from a previous login). "
                       "ACCESS DENIED.")
                raise UnauthenticatedException(msg)

            return fn(*args, **kwargs)

        return wrap

    @staticmethod
    def requires_guest(fn):
        """
        Requires that the calling Subject be NOT (yet) recognized in the system as
        a user -- the Subject is not yet authenticated nor remembered through
        RememberMe services.

        This method essentially ensures that subject.identifiers IS None

        :raises UnauthenticatedException: indicating that the decorated method is
                                          not allowed to be executed because the
                                          Subject attempted to perform a guest-only
                                          operation
        """
        @functools.wraps(fn)
        def wrap(*args, **kwargs):
            subject = Yosai.get_current_subject()

            if subject.identifiers is not None:
                msg = ("Attempting to perform a guest-only operation.  The "
                       "current Subject is NOT a guest (they have either been "
                       "authenticated or remembered from a previous login). "
                       "ACCESS DENIED.")
                raise UnauthenticatedException(msg)

            return fn(*args, **kwargs)

        return wrap

    @staticmethod
    def requires_permission(permission_s, logical_operator=all):
        """
        Requires that the calling Subject be authorized to the extent that is
        required to satisfy the permission_s specified and the logical operation
        upon them.

        :param permission_s:   the permission(s) required
        :type permission_s:  a List of Strings or List of Permission instances

        :param logical_operator:  indicates whether all or at least one permission
                                  is true (and, any)
        :type: and OR all (from python standard library)

        :raises  AuthorizationException:  if the user does not have sufficient
                                          permission

        Elaborate Example:
            requires_permission(
                permission_s=['domain1:action1,action2', 'domain2:action1'],
                logical_operator=any)

        Basic Example:
            requires_permission(['domain1:action1,action2'])
        """
        def outer_wrap(fn):
            @functools.wraps(fn)
            def inner_wrap(*args, **kwargs):
                subject = Yosai.get_current_subject()
                subject.check_permission(permission_s, logical_operator)

                return fn(*args, **kwargs)

            return inner_wrap

        return outer_wrap

    @staticmethod
    def requires_dynamic_permission(permission_s, logical_operator=all):
        """
        This method requires that the calling Subject be authorized to the extent
        that is required to satisfy the dynamic permission_s specified and the logical
        operation upon them.  Unlike ``requires_permission``, which uses statically
        defined permissions, this function derives a permission from arguments
        specified at declaration.

        Dynamic permissioning requires that the dynamic arguments be keyword
        arguments of the decorated method.

        :param permission_s:   the permission(s) required
        :type permission_s:  a List of Strings or List of Permission instances

        :param logical_operator:  indicates whether all or at least one permission
                                  is true (and, any)
        :type: and OR all (from python standard library)

        :raises  AuthorizationException:  if the user does not have sufficient
                                          permission

        Elaborate Example:
            requires_permission(
                permission_s=['{kwarg1.domainid}:action1,action2',
                               '{kwarg2.domainid}:action1'],
                logical_operator=any)

        Basic Example:
            requires_permission(['{kwarg.domainid}:action1,action2'])
        """
        def outer_wrap(fn):
            @functools.wraps(fn)
            def inner_wrap(*args, **kwargs):
                newperms = [perm.format(**kwargs) for perm in permission_s]

                subject = Yosai.get_current_subject()

                subject.check_permission(newperms, logical_operator)

                return fn(*args, **kwargs)

            return inner_wrap

        return outer_wrap

    @staticmethod
    def requires_role(role_s, logical_operator=all):
        """
        Requires that the calling Subject be authorized to the extent that is
        required to satisfy the role_s specified and the logical operation
        upon them.

        :param role_s:   a collection of the role(s) required, specified by
                           identifiers (such as a role name)
        :type role_s:  a List of Strings

        :param logical_operator:  indicates whether all or at least one permission
                                  is true (and, any)
        :type: and OR all (from python standard library)

        :raises  AuthorizationException:  if the user does not have sufficient
                                          role membership

        Elaborate Example:
            requires_role(role_s=['sysadmin', 'developer'], logical_operator=any)

        Basic Example:
            requires_role('physician')
        """
        def outer_wrap(fn):
            @functools.wraps(fn)
            def inner_wrap(*args, **kwargs):
                subject = Yosai.get_current_subject()

                subject.check_role(role_s, logical_operator)

                return fn(*args, **kwargs)

            return inner_wrap

        return outer_wrap

    def __eq__(self, other):
        return self.security_manager == other.security_manager
Beispiel #15
0
 def __init__(self, ss_evaluator=SessionStorageEvaluator()):
     self.session_storage_evaluator = ss_evaluator
     self.dsc_isk = 'identifiers_session_key'
     self.dsc_ask = 'authenticated_session_key'
     self._logger = get_logger()
Beispiel #16
0
 def __init__(self, delete_invalid_sessions=True):
     super(WebSessionHandler,
           self).__init__(delete_invalid_sessions=delete_invalid_sessions)
     self.is_session_id_cookie_enabled = True
     self._logger = get_logger()
Beispiel #17
0
 def __init__(self, settings):
     authc_settings = AuthenticationSettings(settings)
     self.password_cc = self.create_password_crypt_context(authc_settings)
     self.totp_factory = create_totp_factory(authc_settings=authc_settings)
     self.supported_tokens = [UsernamePasswordToken, TOTPToken]
     self._logger = get_logger()
Beispiel #18
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from marshmallow import fields, post_load, pre_dump
from session import SimpleSession
from yosaipy2.core.serialize.serializer import BaseSchema
from yosaipy2.core.subject.schema import SimpleIdentifierSchema
from yosaipy2.core.utils.utils import get_logger
from copy import copy

logger = get_logger()


class SimpleSessionSchema(BaseSchema):
    under_type = SimpleSession

    session_id = fields.String(allow_none=True)
    start_timestamp = fields.Integer(allow_none=True)
    stop_timestamp = fields.Integer(allow_none=True)
    last_access_time = fields.Integer(allow_none=True)
    idle_timeout = fields.Integer(allow_none=True)
    absolute_timeout = fields.Integer(allow_none=True)
    is_expired = fields.Boolean(allow_none=True)
    host = fields.String(allow_none=True)
    internal_attributes = fields.Dict(allow_none=True)
    attributes = fields.Dict(allow_none=True)

    @pre_dump
    def encode_attribute(self, data):
        # type:(SimpleSession) -> SimpleSession
        internal_attributes = data.internal_attributes
        if 'identifiers_session_key' not in internal_attributes: