Esempio n. 1
0
def list_sessions(request):
    """
    Tags: sessions
    ---
    Lists active sessions
    ---
    """
    auth_context = auth_context_from_request(request)
    session = request.environ['session']
    # Get active sessions for the current user
    session_tokens = SessionToken.objects(user_id=auth_context.user.id,
                                          revoked=False)
    sessions_list = []
    for token in session_tokens:
        if token.is_valid():
            public_view = token.get_public_view()
            if isinstance(session, SessionToken) and session.id == token.id:
                public_view['active'] = True
            sessions_list.append(public_view)

    # If user is owner include all active sessions in the org context
    if auth_context.is_owner():
        org_tokens = SessionToken.objects(org=auth_context.org, revoked=False)
        for token in org_tokens:
            if token.is_valid():
                public_view = token.get_public_view()
                if isinstance(session, SessionToken) and \
                   session.id == token.id:
                    public_view['active'] = True
                try:
                    sessions_list.index(public_view)
                except ValueError:
                    sessions_list.append(public_view)

    return sessions_list
Esempio n. 2
0
def info_from_CookieAuth(api_key, required_scopes):
    """
    Check and retrieve authentication information from api_key.
    Returned value will be passed in 'token_info' parameter of your operation
    function, if there is one. 'sub' or 'uid' will be set in 'user' parameter
    of your operation function, if there is one.

    :param api_key API key provided by Authorization header
    :type api_key: str
    :param required_scopes Always None. Used for other authentication method
    :type required_scopes: None
    :return: Information attached to provided api_key or None if api_key is
        invalid or does not allow access to called API
    :rtype: dict | None
    """
    from mist.api.auth.models import SessionToken
    from mist.api import config
    if config.HAS_RBAC:
        # from mist.rbac.tokens import SuperToken
        from mist.rbac.methods import AuthContext
    else:
        from mist.api.dummy.rbac import AuthContext

    auth_context = session = None
    token_from_request = api_key.lower()
    try:
        api_token = SessionToken.objects.get(token=token_from_request)
    except DoesNotExist:
        api_token = None
    # try:
    #     if not api_token and config.HAS_RBAC:
    #         api_token = SuperToken.objects.get(
    #             token=token_from_request)
    # except DoesNotExist:
    #     pass
    if api_token and api_token.is_valid():
        session = api_token
    else:
        session = SessionToken()
        session.name = 'dummy_token'
    if session:
        user = session.get_user()
        if user:
            auth_context = AuthContext(user, session)
            return {'uid': user.id, 'user': user, 'auth_context': auth_context}
    return None
Esempio n. 3
0
def session_from_request(request):
    """Get SessionToken or ApiToken instance from request"""
    if 'session' in request.environ:
        return request.environ['session']
    session = migrate_old_api_token(request)
    if session is None:
        auth_value = request.headers.get('Authorization', '').lower()
        if auth_value.startswith('internal'):
            parts = auth_value.split(' ')
            if len(parts) == 3:
                internal_api_key, session_id = parts[1:]
                if internal_api_key == Portal.get_singleton().internal_api_key:
                    try:
                        session_token = SessionToken.objects.get(
                            token=session_id)
                    except SessionToken.DoesNotExist:
                        pass
                    else:
                        if session_token.is_valid():
                            session_token.internal = True
                            session = session_token
        elif auth_value:
            token_from_request = auth_value
            try:
                api_token = ApiToken.objects.get(token=token_from_request)
            except DoesNotExist:
                api_token = None
            try:
                if not api_token and config.HAS_RBAC:
                    api_token = SuperToken.objects.get(
                        token=token_from_request)
            except DoesNotExist:
                pass
            if api_token and api_token.is_valid():
                session = api_token
            else:
                session = ApiToken()
                session.name = 'dummy_token'
    if session is None:
        try:
            session_token = SessionToken.objects.get(
                token=request.cookies.get('session.id'))
            if session_token.is_valid():
                session = session_token
        except DoesNotExist:
            pass
    if session is None:
        session = SessionToken(
            user_agent=request.user_agent,
            ip_address=mist.api.helpers.ip_from_request(request))
        session.save()
    request.environ['session'] = session
    return session
Esempio n. 4
0
def session_from_request(request):
    """Get SessionToken or ApiToken instance from request"""
    if 'session' in request.environ:
        return request.environ['session']
    session = migrate_old_api_token(request)
    if session is None:
        token_from_request = request.headers.get('Authorization', '').lower()
        if token_from_request:
            try:
                api_token = ApiToken.objects.get(
                    token=token_from_request
                )
            except DoesNotExist:
                api_token = None
            try:
                if not api_token and SUPER_EXISTS:
                    api_token = SuperToken.objects.get(
                                token=token_from_request)
            except DoesNotExist:
                pass
            if api_token and api_token.is_valid():
                session = api_token
            else:
                session = ApiToken()
                session.name = 'dummy_token'
    if session is None:
        try:
            session_token = SessionToken.objects.get(
                token=request.cookies.get('session.id')
            )
            if session_token.is_valid():
                session = session_token
        except DoesNotExist:
            pass
    if session is None:
        session = SessionToken(
            user_agent=request.user_agent,
            ip_address=mist.api.helpers.ip_from_request(request)
        )
        session.save()
    request.environ['session'] = session
    return session
Esempio n. 5
0
def reissue_cookie_session(request,
                           user_id='',
                           su='',
                           org=None,
                           after=0,
                           TokenClass=SessionToken,
                           **kwargs):
    """Invalidate previous cookie session and issue a fresh one

    Params `user_id` and `su` can be instances of `User`, `user_id`s or emails.

    """
    # First invalidate the current empty session
    session = session_from_request(request)
    if not isinstance(session, SessionToken):
        raise Exception("Can not reissue an API token session.")

    if after:
        revoke_token.apply_async(args=(session.token, ), countdown=after)
    else:
        session.invalidate()
        session.save()

    kwargs.update({
        'ip_address': mist.api.helpers.ip_from_request(request),
        'user_agent': request.user_agent,
    })

    # And then issue the new session
    new_session = TokenClass(**kwargs)

    # Pass on fingerprint & experiment choice to new session
    if session.fingerprint:
        new_session.fingerprint = session.fingerprint
    if session.experiment:
        new_session.experiment = session.experiment
    if session.choice:
        new_session.choice = session.choice

    session = new_session
    if user_id or su:
        # A user will be set to the session
        user_for_session = su if su else user_id
        user_is_effective = not user_id
        if isinstance(user_for_session, basestring):
            # Get the user object if an id has been provided
            if '@' in user_for_session:
                user_for_session = User.objects.get(email=user_for_session)
            else:
                user_for_session = User.objects.get(id=user_for_session)

        session.set_user(user_for_session, effective=user_is_effective)

        if not org:
            # If no org is provided then get the org from the last session
            old_session = SessionToken.objects(
                user_id=user_for_session.id).first()
            if old_session and old_session.org and \
                    user_for_session in old_session.org.members:
                # if the old session has an organization and user is still a
                # member of that organization then use that context
                org = old_session.org
            else:
                # If there is no previous session just get the first
                # organization that the user is a member of.
                orgs = Organization.objects(members=user_for_session)
                if len(orgs) > 0:
                    org = orgs.first()
                else:
                    # if for some reason the user is not a member of any
                    # existing organization then create an anonymous one now
                    from mist.api.users.methods import create_org_for_user
                    org = create_org_for_user(user_for_session)

    session.org = org
    session.su = su
    session.save()
    request.environ['session'] = session
    return session