Ejemplo n.º 1
0
def current_user_can_edit_user(user):
    '''
    Determines whether or not the currently loaded user can edit the specified user

    Parameters
    ----------
    user : `models.user_models.User
        The user object that the current user wants to modify

    Returns
    -------
    bool
        True if the user is authorized and False otherwise
    '''

    # If we create an administrator type who can perform most administrative tasks,
    # ensure that they cannot edit superusers unless they are also superusers.
    if user.is_superuser() and not current_user_is_superuser():
        g.request_logger.warning(
            'User \'%s\' attempted to edit '
            'Superuser \'%s\' but was not a superuser.',
            get_user_string(current_user),
            get_user_string(user),
        )
        return False
    return True
Ejemplo n.º 2
0
def api_bulk_transfer_dashboard_ownership(old_author, new_author):
    logger = g.request_logger if hasattr(g, 'request_logger') else LOG
    new_author_string = get_user_string(new_author)
    old_author_string = get_user_string(old_author)
    logger.info(
        'Attempting to transfer ownership of ALL Dashboards owned by %s to %s',
        old_author_string,
        new_author_string,
    )
    with Transaction() as transaction:
        bulk_transfer_dashboard_ownership(transaction, old_author, new_author)
    logger.info('Transfer was successful.')
Ejemplo n.º 3
0
        def auth_decorator_inner(*args, **kwargs):
            user_string = get_user_string(current_user)
            resource_string = get_resource_string(resource_id, resource_type)

            if is_authorized(permission, resource_type, resource_id, False):
                if log_request:
                    g.request_logger.debug(
                        'User \'%s\' successfully authorized to perform \'%s\' on %s.',
                        user_string,
                        permission,
                        resource_string,
                    )
                return protected_operation(*args, **kwargs)

            if log_request:
                g.request_logger.info(
                    'User \'%s\' attempted to perform \'%s\' on %s but was unauthorized.',
                    user_string,
                    permission,
                    resource_string,
                )

            if is_api_request:
                message = ('You do not have the \'%s\' permission on %s. ') % (
                    permission,
                    resource_string,
                )
                raise Unauthorized(description=message)
            else:
                return current_app.user_manager.unauthorized_view_function()
Ejemplo n.º 4
0
def before_delete_user(sender, item):
    if current_user.is_authenticated and item.id == current_user.id:
        g.request_logger.warning(
            'User \'%s\' attempted to delete their own user account.',
            get_user_string(item),
        )
        raise BadRequest('You are unable to delete your own user account.')
Ejemplo n.º 5
0
def api_transfer_dashboard_ownership(dashboard, new_author):
    logger = g.request_logger if hasattr(g, 'request_logger') else LOG
    with Transaction() as transaction:
        new_author_string = get_user_string(new_author)
        old_author_string = get_user_string(dashboard.author)
        dashboard_string = ('slug: %s, resource_id: %s') % (
            dashboard.slug,
            dashboard.resource_id,
        )

        logger.info(
            'Attempting to transfer ownership of Dashboard \'%s\' from %s to %s',
            dashboard_string,
            old_author_string,
            new_author_string,
        )
        bulk_transfer_dashboard_ownership(transaction, dashboard, new_author)
        logger.info('Transfer was successful.')
Ejemplo n.º 6
0
 def update_users(self, group, request):
     with AuthorizedOperation('edit_resource', 'group', group.id):
         users = update_group_users(group, request)
         directory_listing = [
             get_user_string(user, include_ip=False) for user in users
         ]
         message = (
             'Updated the member list for group \'%s\'. The current users are \'%s\'.'
             % (group.name, directory_listing))
         g.request_logger.info(message)
         return StandardResponse(message, OK, True)
Ejemplo n.º 7
0
 def delete_user_by_username(self, group, request):
     with AuthorizedOperation('edit_resource', 'group', group.id):
         user, exists = delete_group_user(group, request)
         action = ('has been deleted from the member list of'
                   if exists else 'is not a member of')
         message = 'User \'%s\' %s group \'%s\'. ' % (
             get_user_string(user, include_ip=False),
             action,
             group.name,
         )
         g.request_logger.info(message)
         return StandardResponse(message, OK, True)
Ejemplo n.º 8
0
def compute_authorization_label(alert_definition):
    user_string = get_user_string(
        alert_definition.user or current_user, include_ip=False
    )
    text_label = (
        'Alert on {indicator} by {time_bucket} and {granularity}. ' 'Created by {user}'
    ).format(
        indicator=alert_definition.field_id,
        time_bucket=alert_definition.time_granularity,
        granularity=alert_definition.dimension_name,
        user=user_string,
    )
    return text_label
Ejemplo n.º 9
0
    def __enter__(self):
        required_permission = QueryPermission(self.query_needs)

        if not required_permission.can():
            if self.log_request:
                g.request_logger.info(
                    'User \'%s\' attempted to execute query defined by: \'%s\' but was '
                    'unauthorized.',
                    get_user_string(current_user),
                    self.query_needs,
                )

            message = (
                'You do not have the permission to run this query. '
                'One of the following needs is required: {needs}.').format(
                    needs=self.query_needs)
            raise Unauthorized(description=message)
        else:
            g.request_logger.debug(
                'User \'%s\' authorized to run query defined by: \'%s\'.',
                get_user_string(current_user),
                self.query_needs,
            )
Ejemplo n.º 10
0
def on_identity_loaded(sender, identity):
    '''A signal handler that updates the current user's identity with claims
    from the database.
    '''

    # If the user is authenticated and registered in the system,
    # install the default user permissions.
    if not isinstance(identity, AnonymousIdentity):
        # Set the identity user object
        identity.user = current_user
        install_default_user_permissions(identity)

    # sender is a flask app that has cache service
    cache = sender.cache

    cached_permissions = (cache.get(current_user.username)
                          if not isinstance(identity, AnonymousIdentity) else
                          None)

    if cached_permissions:
        identity.provides = cached_permissions
    else:
        # Add specific permission claims to the identity object
        # (e.g.) 'edit_resource' on the 'jsc' dashboard
        for permission in enumerate_permissions(current_user):
            identity.provides.add(permission)

        # cache the user permissions added to the identity provider
        if not isinstance(identity, AnonymousIdentity):
            cache.set(
                current_user.username,
                identity.provides,
                timeout=sender.config['CACHE_TIMEOUT_SECONDS'],
            )

    g.request_logger.debug(
        'Identity for User \'%s\' was loaded. '
        'Permissions are: \'%s\'',
        get_user_string(current_user),
        identity.provides,
    )
Ejemplo n.º 11
0
    def login_from_request(request_object=None):
        request_object = request_object or request

        access_key = request.cookies.get('accessKey')
        if access_key:
            LOG.info('Received access key in cookie: %s' % access_key)
            if KeyManager.is_valid_key(access_key):
                LOG.info('Accessing %s with renderbot access key',
                         request.path)
                bot = User.query.filter_by(
                    username=global_config.RENDERBOT_EMAIL).first()
                return bot
            else:
                LOG.warn('Received invalid access key')

        try:
            username = request.headers.get('X-Username')
            password = request.headers.get('X-Password')

            if not (username and password):
                LOG.debug(
                    'Username or Password not provided via Login Headers. ')
                return None

            LOG.debug('Attempting to authenticate user: \'%s\'.', username)
            user = try_authenticate_user(username, password)

            if user:
                LOG.debug('User: \'%s\' authenticated successfully.',
                          get_user_string(user))
                return user
            else:
                LOG.warn('User: \'%s\' failed to authenticate.', username)
                return None
        except BadRequest:
            return None
        return None
Ejemplo n.º 12
0
        def auth_decorator_inner(*args, **kwargs):
            user_is_authenticated = current_user.is_authenticated
            public_access_enabled = get_configuration(PUBLIC_ACCESS_KEY)
            user_string = get_user_string(current_user)

            # User must be authenticated
            if not user_is_authenticated:
                # Redirect to unauthenticated page
                if force_authentication or not public_access_enabled:
                    LOG.info(
                        'Unauthenticated user \'%s\' attempted to access %s but was denied.',
                        user_string,
                        request.full_path,
                    )

                    if is_api_request:
                        # Contrary to the name, this is actually the appropriate HTTP
                        # Error Code to raise when the user is unauthenticated.
                        raise Unauthorized()
                    else:
                        return current_app.user_manager.unauthenticated_view_function(
                        )

            if user_is_authenticated:
                LOG.debug('User \'%s\' accessed %s.', user_string,
                          request.full_path)
            else:
                LOG.debug(
                    'Unauthenticated user \'%s\' will be allowed to access '
                    'resource \'%s\' because public access is enabled. ',
                    user_string,
                    request.full_path,
                )

            # Call the actual view
            return protected_operation(*args, **kwargs)
Ejemplo n.º 13
0
def is_authorized(permission,
                  resource_type,
                  resource_id=None,
                  log_request=True):
    '''
    Determines whether or not the currently loaded user can perform the specified operation
    on the specified resource.

    Parameters
    ----------
    permission : string
        The desired object permission that the user must possess (e.g. 'edit_resource')

    resource_type : string
        The type of resource that the operation is being performed on (e.g. 'dashboard')

        resource_id (optional): int
            The id of the resource in question (based on the `id` attribute of the `Resource`
            model). Do not specify if you are attempting to determine whether the user has a
            sitewide permission for a given resource type.

    log_request (optional): string
        Whether or not to log the authorization check. This should generally be true unless
        the user is simply querying whether or not they have the permission to do so.

    Returns
    -------
    bool
        True if the user is authorized and False otherwise
    '''

    # WARNING: Please be careful what changes you make to this function. It is ultimately
    # the function that decides whether or not to authorize ANY action on the website.
    permission = str(permission).lower()
    resource_type = str(resource_type).lower()
    resource_name = int(resource_id) if resource_id else None
    resource_specific_need = [
        ItemNeed(permission, resource_name, resource_type)
    ]
    required_permission = WhitelistedPermission(resource_specific_need)

    if required_permission.can():
        if log_request:
            g.request_logger.debug(
                'User \'%s\' successfully authorized to perform '
                '\'%s\' on resource \'%s\' of type \'%s\'.',
                get_user_string(current_user),
                permission,
                resource_id,
                resource_type,
            )
        return True

    if log_request:
        g.request_logger.info(
            'User \'%s\' attempted to perform '
            '\'%s\' on resource \'%s\' of type \'%s\' but was unauthorized.',
            get_user_string(current_user),
            permission,
            resource_id,
            resource_type,
        )
    return False
Ejemplo n.º 14
0
 def on_user_logged_out(sender, user):
     if user.is_authenticated:
         g.request_logger.info('User \'%s\' logged out',
                               get_user_string(user))
     identity_changed.send(sender, identity=AnonymousIdentity())
     sender.cache.delete(user.username)
Ejemplo n.º 15
0
 def on_user_logged_in(sender, user):
     g.request_logger.info('User \'%s\' logged in', get_user_string(user))
     identity_changed.send(sender, identity=Identity(user.id))
Ejemplo n.º 16
0
 def on_user_registered(sender, user):
     g.request_logger.info(
         'Invited user \'%s\' has successfully registered for an account. ',
         get_user_string(user),
     )