Example #1
0
    def inline_authz(self, permission_s: list, authc_token: AuthenticationToken=None):
        """
        Non-decorator impl of the @requires() decorator for isolated and inline invocation.
        Returns authenticated user identity on success or raises an exception

        :param permission_s: list of Permission objects
        :param authc_token: optional authc token to use for the authc portion, if omitted or None, the flask request context is used
        :return: IdentityContext object
        """
        try:
            with Yosai.context(self._yosai):
                # Context Manager functions
                try:
                    try:
                        if not authc_token:
                            identity = self.authenticate(request_proxy)
                        else:
                            identity = self.authenticate_token(authc_token)

                        if not identity.username:
                            raise UnauthenticatedError('Authentication Required')

                    except:
                        raise UnauthenticatedError('Authentication Required')

                    ApiRequestContextProxy.set_identity(identity)
                    permissions_final = []

                    # Bind all the permissions as needed
                    for perm in permission_s:
                        domain = perm.domain if perm.domain else '*'
                        action = perm.action if perm.action else '*'
                        target = perm.target if perm.target else '*'
                        permissions_final.append(Permission(domain, action, target))

                    # Do the authz on the bound permissions
                    try:
                        self.authorize(ApiRequestContextProxy.identity(), permissions_final)
                    except UnauthorizedError as ex:
                        raise ex
                    except Exception as e:
                        logger.exception('Error doing authz: {}'.format(e))
                        raise UnauthorizedError(permissions_final)

                    return ApiRequestContextProxy.identity()
                finally:
                    # Teardown the request context
                    ApiRequestContextProxy.set_identity(None)
        except UnauthorizedError as ex:
            return make_response_error(str(ex), in_httpcode=403), 403
        except UnauthenticatedError as ex:
            return Response(response='Unauthorized', status=401,
                            headers=[('WWW-Authenticate', 'basic realm="Authentication required"')])
        except AnchoreApiError:
            raise
        except Exception as ex:
            logger.exception('Unexpected exception: {}'.format(ex))
            return make_response_error('Internal error', in_httpcode=500), 500
Example #2
0
def add_credential(credential):
    """
    POST /user/credentials

    The same logic as /users/{userId}/credentials, but gets the userId from the auth context rather than path.
    This is for use by regular (non-admin) users to update their own credentials.
    :param credential:
    :return: credential json object

    """

    try:
        if credential['type'] != UserAccessCredentialTypes.password.value:
            return make_response_error('Invalid credential type',
                                       in_httpcode=400), 400
        else:
            cred_type = UserAccessCredentialTypes(credential['type'])

        with session_scope() as session:
            mgr = identities.manager_factory.for_session(session)
            user = ApiRequestContextProxy.identity().username
            result = mgr.add_user_credential(username=user,
                                             credential_type=cred_type,
                                             value=credential['value'])
            return credential_db_to_msg(result), 200
    except Exception as ex:
        logger.exception('API Error')
        return make_response_error(errmsg=str(ex), in_httpcode=500), 500
Example #3
0
def get_user():
    """
    GET /user

    :return: User json object
    """
    try:
        with session_scope() as session:
            mgr = identities.manager_factory.for_session(session)
            usr = mgr.get_user(ApiRequestContextProxy.identity().username)
            return user_db_to_msg(usr), 200
    except Exception as ex:
        logger.exception('API Error')
        return make_response_error(errmsg=str(ex), in_httpcode=500), 500
Example #4
0
def create_analysis_archive_rule(rule):
    """
    POST /archives/rules

    :param rule: the rule's json object definition
    :return:
    """

    # Permission check on the system_global field, only admins
    if rule.get('system_global'):
        perm = ':'.join(
            ['createArchiveTransitionRule', GLOBAL_RESOURCE_DOMAIN, '*'])

        # Will raise exception if unauthorized
        authorizer.authorize(ApiRequestContextProxy.identity(), [perm])

    client = internal_client_for(CatalogClient,
                                 ApiRequestContextProxy.namespace())
    try:
        return handle_proxy_response(client.add_analysis_archive_rule(rule))
    except Exception as ex:
        return handle_proxy_response(ex)
Example #5
0
def get_credentials():
    """
    GET /user/credentials

    Fetches the credentials list for the authenticated user
    :return:
    """
    try:
        with session_scope() as session:
            mgr = identities.manager_factory.for_session(session)
            usr = mgr.get_user(ApiRequestContextProxy.identity().username)

            creds = [
                credential_db_to_msg(
                    usr.get('credentials')[UserAccessCredentialTypes.password])
            ]
            if creds is None:
                return [], 200
            else:
                return creds, 200
    except Exception as ex:
        logger.exception('API Error')
        return make_response_error(errmsg=str(ex), in_httpcode=500), 500
Example #6
0
def lookup_account_type_from_identity(identity):
    if ApiRequestContextProxy.identity().username == identity:
        return ApiRequestContextProxy.identity().user_account_type
    else:
        return None