Ejemplo n.º 1
0
 def launch(self):
     """
     Worker method that does the work of retrieving user details.
     
     :rtype: valid|invalid
     """
     
     # Construct a list of authorized user objects
     auth_users = self.api.acl.authorized_objects('user')
     
     # If retrieving a specific user
     if self.user:
         
         # If the user does not exist or access is denied
         if not self.user in auth_users.ids:
             return invalid('User <%s> does not exist or access denied' % self.user)
         
         # Return the user details
         return valid(self._get_user(self.user))
         
     # If retrieving all users
     else:
     
         # Construct a detailed users object
         users_obj = []
         for user in auth_users.details:
             users_obj.append(self._get_user(user['username']))
     
         # Return the constructed users object
         return valid(users_obj)
Ejemplo n.º 2
0
 def launch(self):
     """
     Worker method used to construct the ACL endpoint definitions object.
     """
     
     # Construct the ACL object
     try:
         
         # If retrieving a single ACL definition
         if self.acl:
             
             # Get the ACL definition
             acl_definition = DBAuthACLKeys.objects.filter(uuid=self.acl).values()
             
             # If the ACL definition doesn't exist
             if not acl_definition:
                 return invalid('Could not locate ACL <%s> in the database' % self.acl)
             
             # Return the ACL definition
             return valid(json.dumps(acl_definition[0]))
         
         # If retrieving all ACL definitions
         else:
             return valid(json.dumps(list(DBAuthACLKeys.objects.all().values())))
         
     # Error during ACL construction
     except Exception as e:
         return invalid(self.api.log.exception('Failed to retrieve ACL definition(s): %s' % str(e)))
Ejemplo n.º 3
0
 def launch(self):
     """
     Worker method used to saving formula run status to the database.
     """
     self.api.log.info('Updating formula <%s> run status for host <%s>' % (self.formula, self.host))
     
     # Check if the formula ID for the specific host is already in the database
     if DBHostFormulas.objects.filter(host=self.host).filter(formula=self.formula).count():
         
         # Filter parameters
         filter = {
             'host':    self.host,
             'formula': self.formula,
             'current': True
         }
         
         # Updating status for a previous formula run
         try:
             DBHostFormulas.objects.filter(**filter).update(
                 formula     = self.formula,
                 exit_status = self.api.data['exit_status'],
                 exit_code   = self.api.data['exit_code'],
                 exit_msg    = self.api.data['exit_msg'],
                 log         = self.api.data['log'])
             return valid('Successfully updated formula <%s> entry for host <%s>' % (self.formula, self.host))
         
         # Critical error when updating host formula entry
         except Exception as e:
             return invalid(self.api.log.exception('Failed to update formula <%s> entry for host <%s>: %s' % (self.formula, self.host, str(e))))
         
     # Setting status for a new formula run
     else:
         
         # Get the parent host details
         host_details = DBHostDetails.objects.get(uuid=self.host)
         
         # Create the new formula status entry
         try:
             DBHostFormulas(
                 id          = None, 
                 host        = host_details,
                 formula     = self.formula,
                 exit_status = self.api.data['exit_status'],
                 exit_code   = self.api.data['exit_code'],
                 exit_msg    = self.api.data['exit_msg'],
                 log         = self.api.data['log']
             ).save()
             
             # Formula run status update success
             return valid('Successfully updated formula <%s> run status for host <%s>' % (self.formula, self.host))
         
         # Critical error when creating host formula entry
         except Exception as e:
             return invalid(self.api.log.exception('Failed to create formula <%s> entry for host <%s>: %s' % (self.formula, self.host, str(e))))
Ejemplo n.º 4
0
    def launch(self):
    
        # Construct a list of authorized formulas
        auth_formulas = self.api.acl.authorized_objects('formula', 'formula/get')

        # Make sure the formula exists and is accessible
        if not self.formula in auth_formulas.ids:
            return invalid(self.api.log.error('Requested formula <%s> not found or access denied' % self.formula))
        
        # Get the formula details row
        formula_details = auth_formulas.extract(self.formula)
        
        # Check if the formula is already checked out
        if formula_details['locked'] == False:
            return invalid(self.api.log.error('Could not check in formula <%s>, already checked in' % self.formula))
        
        # Lock the formula for editing
        self.api.log.info('Check in formula <%s> by user <%s>' % (self.formula, self.api.user))
        try:
            DBFormulaDetails.objects.filter(uuid=self.formula).update(
                locked    = False,
                locked_by = None
            )
            return valid('Successfully checked in formula')
            
        # Failed to check out the formula
        except Exception as e:
            return invalid(self.api.log.error('Failed to check in formula with error: %s' % e))
Ejemplo n.º 5
0
 def launch(self):
     """
     Worker method for closing an endpoint and releasing the editing lock.
     """
 
     # Make sure the endpoint exists
     if not DBAuthEndpoints.objects.filter(uuid=self.endpoint).count():
         return invalid(self.api.log.error('Could not check in endpoint <%s>, not found in database' % self.endpoint))
     
     # Get the endpoint details row
     endpoint_row = DBAuthEndpoints.objects.filter(uuid=self.endpoint).values()[0]
     
     # Check if the endpoint is already checked out
     if endpoint_row['locked'] == False:
         return invalid(self.api.log.error('Could not check in endpoint <%s>, already checked in' % self.endpoint))
     
     # Unlock the endpoint
     self.api.log.info('Checked in endpoint <%s> by user <%s>' % (self.endpoint, self.api.user))
     try:
         DBAuthEndpoints.objects.filter(uuid=self.endpoint).update(
             locked    = False,
             locked_by = None
         )
         return valid('Successfully checked in endpoint')
         
     # Failed to check out the formula
     except Exception as e:
         return invalid(self.api.log.error('Failed to check in endpoint with error: %s' % str(e)))
Ejemplo n.º 6
0
 def launch(self):
     """
     Worker method used for deleting an endpoint.
     """
     
     # Make sure the endpoint exists
     if not DBAuthEndpoints.objects.filter(uuid=self.endpoint).count():
         return invalid(self.api.log.error('Could not delete endpoint <%s>, not found in database' % self.endpoint))
     
     # Get the endpoint details
     endpoint_row = DBAuthEndpoints.objects.filter(uuid=self.endpoint).values()[0]
     
     # Make sure the endpoint isn't protected
     if endpoint_row['protected']:
         return invalid('Cannot delete a protected endpoint')
     
     # Delete the endpoint
     try:
         DBAuthEndpoints.objects.filter(uuid=self.endpoint).delete()
     except Exception as e:
         return invalid(self.api.log.exeption('Failed to delete endpoint: %s' % str(e)))
     
     # Construct and return the web data
     web_data = {
         'uuid': self.endpoint
     }
     return valid('Successfully deleted endpoint', web_data)
Ejemplo n.º 7
0
 def launch(self):
     
     # If filtering by host group
     hgroup = False
     if 'hgroup' in self.filters:
         hgroup = copy.copy(self.filters['hgroup'])
         del self.filters['hgroup']
     
     # Build a list of all authorized hosts
     authorized_hosts = self.api.acl.authorized_objects('host', 'host/get', self.filters)
     
     # If filtering by host group
     hgroup_members = False
     if hgroup:
         
         # Get all member hosts for the group
         hgroup_members = [x['host_id'] for x in list(DBHostGroupMembers.objects.filter(group=hgroup).values())]
     
     # Construct the statistics for each host
     for host in authorized_hosts.details:
         
         # If filtering by host group
         if hgroup_members:
             if not host['uuid'] in hgroup_members:
                 continue
         
         # Get the stats row
         stat_rows = DBHostStats(host['uuid']).get(latest=30)
         
         # Start calculating statistics
         self.totals['host']['total'] += 1
         if host['os_type'] == 'windows':
             self.totals['host']['windows'] += 1
         else:
             self.totals['host']['linux'] += 1
         
         # Get the statistics for the host if it meets the criteria
         if (host['agent_status'] == A_RUNNING) and (len(stat_rows) >= 30):
             self._get_latest_stat(host['uuid'], stat_rows)
             
             # Get the size of all disks
             for disk in host['sys']['disk']:
                 self.totals['disk']['total'] += float(disk['size'])
             
             # Count the number of cores and Hz
             for cpu in host['sys']['cpu']:
                 
                 # Get the number of cores per CPU
                 num_cores       = int(cpu['cores'])
                 self.cpu_cores += num_cores
                 
                 # Calculate the total speed of the physical CPU
                 ghz_str         = re.compile(r'^.*[ ]([0-9\.]*)GHz.*$').sub(r'\g<1>', cpu['model'])
                 self.cpu_ghz   += float(ghz_str) * int(cpu['cores'])
         
     # Get the averages
     self.stats = self._crunch_totals()
     
     # Return the global statistics object
     return valid(json.dumps(self.stats, cls=DjangoJSONEncoder))
Ejemplo n.º 8
0
 def launch(self):
     """
     Worker method for closing a utility and releasing the editing lock.
     """
 
     # Make sure the utility exists
     if not DBGatewayUtilities.objects.filter(uuid=self.utility).count():
         return invalid(self.api.log.error('Could not check in utility [%s], not found in database' % self.utility))
     
     # Get the utility details row
     util_row = DBGatewayUtilities.objects.filter(uuid=self.utility).values()[0]
     
     # Check if the utility is already checked out
     if util_row['locked'] == False:
         return invalid(self.api.log.error('Could not check in utility [%s], already checked in' % self.utility))
     
     # Unlock the utility
     self.api.log.info('Checked in utility [%s] by user [%s]' % (self.utility, self.api.user))
     try:
         DBGatewayUtilities.objects.filter(uuid=self.utility).update(
             locked    = False,
             locked_by = None
         )
         return valid('Successfully checked in utility')
         
     # Failed to check out the utility
     except Exception as e:
         return invalid(self.api.log.error('Failed to check in utility with error: %s' % str(e)))
Ejemplo n.º 9
0
    def launch(self):
        """
        Worker method for searching the cluster index.
        
        WARNING
        
        This is a really weak class right now. I'm not sanitizing the SQL search string yet.
        """
        
        # Define the search string and query
        search_string  = MySQLdb.escape_string(self.api.data['string'])
        search_query   = 'SELECT * FROM cluster_index WHERE string LIKE \'%%%s%%\'' % search_string

        # Log the search query
        self.api.log.info('Constructed cluster search query: <%s>' % search_query)

        # Run the search
        try:
            
            # Open a manual connection and run the query
            cursor = connection.cursor()
            cursor.execute(search_query)
            
            # Fetch the results
            search_results = self._get_rows(cursor)
        except Exception as e:
            return invalid(self.api.log.exception('Failed to run cluster search: %s' % str(e)))
        
        # Return the results
        return valid(json.dumps(search_results))
Ejemplo n.º 10
0
    def launch(self):
        """
        Worker method that handles the deletion of the group.
        """

        # Construct a list of authorized groups
        auth_groups = self.api.acl.authorized_objects('group', path='group', method=HTTP_GET)

        # If the group does not exist or access denied
        if not self.group in auth_groups.ids:
            return invalid('Failed to delete group <%s>, not found in database or access denied' % self.group)

        # If the group is protected
        if auth_groups.extract(self.group)['protected']:
            return invalid('Failed to delete group <%s>, group is protected')

        # If the group has any members
        if DBGroupMembers.objects.filter(group=self.group).count():
            return invalid('Failed to delete group <%s>, must remove all group members first' % self.group)

        # Delete the group
        DBGroupDetails.objects.filter(uuid=self.group).delete()
        
        # Return the response
        return valid('Successfully deleted group', {
            'uuid': self.group
        })
Ejemplo n.º 11
0
 def handler(self):
     """
     Main method for constructing and returning the endpoint map.
     
     @return valid|invalid
     """
     map_rsp = self._build_map()
     if not map_rsp['valid']:
         return map_rsp
     
     # Request path missing
     if not self.endpoint:
         return invalid(LOG.error('Missing request endpoint'))
     
     # Invalid request path
     if not self.endpoint in self.map:
         return invalid(LOG.error('Unsupported request endpoint: <%s>' % self.endpoint))
     
     # Verify the request method
     if self.method != self.map[self.endpoint]['method']:
         return invalid(LOG.error('Unsupported request method <%s> for endpoint <%s>' % (self.method, self.endpoint)))
     
     # Get the API module, class handler, and name
     self.handler_obj = {
         'api_mod':   self.map[self.endpoint]['module'],
         'api_class': self.map[self.endpoint]['class'],
         'api_name':  self.map[self.endpoint]['name'],
         'api_utils': self.map[self.endpoint]['utils'],
         'api_map':   self.map[self.endpoint]['json']
     }
     LOG.info('Parsed handler object for API endpoint <%s>: %s' % (self.endpoint, self.handler_obj))
     
     # Return the handler module path
     return valid(self.handler_obj)
Ejemplo n.º 12
0
    def launch(self):
        """
        Worker method used to handle enabling a user account.
        """
        
        # Construct a list of authorized users
        auth_users = self.api.acl.authorized_objects('user', 'user/get')
        
        # If the user does not exist or access is denied
        if not self.user in auth_users.ids:
            return invalid('Cannot enable user <%s>, not found or access denied' % self.user)
        self.api.log.info('Enabling user account <%s>' % self.user)

        # Cannot enable/disable default administrator
        if self.user == U_ADMIN:
            return invalid('Cannot enable/disable the default administrator account')

        # Get the user object and disable the account
        user_obj = DBUserDetails.objects.get(username=self.user)
        user_obj.is_active = True
        user_obj.save()
        
        # Return the response
        return valid('Successfully enabled user account', {
            'username': self.user
        })
Ejemplo n.º 13
0
 def launch(self):
     """
     Worker method that handles the creation of the group.
     """
         
     # Make sure the group doesn't exist
     if DBGroupDetails.objects.filter(name=self.api.data['name']).count():
         return invalid(self.api.log.error('Group name <%s> already exists' % self.api.data['name']))
     
     # Generate a unique ID for the group
     group_uuid = uuid4()
     
     # Create the group
     try:
         DBGroupDetails(
             uuid      = str(group_uuid),
             name      = self.api.data['name'],
             desc      = self.api.data['desc'],
             protected = self.api.get_data('protected')
         ).save()
         
     # Failed to create group
     except Exception as e:
         return invalid(self.api.log.exception('Failed to create group: %s' % str(e)))
     
     # Update the cached group data
     self.api.cache.save_object('group', self.group)
     
     # Return the response
     return valid('Successfully created group', {
         'name':      self.api.data['name'],
         'desc':      self.api.data['desc'],
         'uuid':      str(group_uuid),
         'protected': self.api.get_data('protected')
     })
Ejemplo n.º 14
0
    def launch(self):
        
        # Construct a list of authorized formulas
        auth_formulas = self.api.acl.authorized_objects('formula', 'formula/get')

        # Make sure the formula exists and is accessible
        if not self.formula in auth_formulas.ids:
            return invalid(self.api.log.error('Requested formula <%s> not found or access denied' % self.formula))

        # Get the formula details
        formula_details = auth_formulas.extract(self.formula)
        
        # Get the formula templates
        formula_templates = {}
        for template_row in DBFormulaTemplates.objects.filter(formula=self.formula).values():
            formula_templates[template_row['template_name']] = template_row['template_file']

        # Encode the manifest
        formula_details['manifest']  = base64.encodestring(json.dumps(formula_details['manifest']))
        
        # Set the templates
        formula_details['templates'] = formula_templates

        # Return the response
        return valid(json.dumps(formula_details))
Ejemplo n.º 15
0
    def launch(self):
        self.api.log.info('Running formula editor contents validation')
        
        # Required templates
        required_templates = []
        
        # Make sure all the required templates are set
        for required_template in required_templates:
            if not required_template in self.api.data['formula_templates']:
                return invalid(self.api.log.error('Missing required template \'%s\' in request data' % required_template))
        
        # Decode the base64 versions of the formula manifest and templates
        try:
            self.api.log.info('Decoding formula <%s> manifest' % self.formula)
            manifest  = base64.decodestring(self.api.data['manifest'])
            templates = {}
            if 'templates' in self.api.data:
                for t_name, t_content in self.api.data['templates'].iteritems():
                    self.api.log.info('Validating formula <%s> template <%s>' % (self.formula, t_name))
                    if not t_content == 'delete':
                        templates[t_name] = base64.decodestring(self.api.data['templates'][t_name])
                    else:
                        templates[t_name] = t_content

        # Objects not base64 encoded
        except Exception as e:
            return invalid(self.api.log.error('An error occured when Base64 decoding formula objects during validation: %s' % e))

        # Validate the formula JSON
        json_err = JSONTemplate(json.load(open(settings.FORMULA_TEMPLATE, 'r'))).validate(json.loads(manifest))
        if json_err:
            return invalid(self.api.log.error(json_err))
        return valid('Successfully validated formula editor contents')
Ejemplo n.º 16
0
 def launch(self):
     """
     Worker method used for deleting a utility.
     """
     
     # Make sure the utility exists
     if not DBGatewayUtilities.objects.filter(uuid=self.utility).count():
         return invalid(self.api.log.error('Could not delete utility [%s], not found in database' % self.utility))
     
     # Get the utility details
     utility_row = DBGatewayUtilities.objects.filter(uuid=self.utility).values()[0]
     
     # Make sure the utility isn't protected
     if utility_row['protected']:
         return invalid('Cannot delete a protected utility')
     
     # Delete the utility
     try:
         DBGatewayUtilities.objects.filter(uuid=self.utility).delete()
     except Exception as e:
         return invalid(self.api.log.exeption('Failed to delete utility: %s' % str(e)))
     
     # Construct and return the web data
     web_data = {
         'uuid': self.utility
     }
     return valid('Successfully deleted utility', web_data)
Ejemplo n.º 17
0
    def launch(self):
        """
        Worker method for deleting an ACL object definition.
        """
        
        # If the ACL object doesn't exist
        if not DBAuthACLObjects.objects.filter(type=self.type).count():
            return invalid('Cannot delete ACL object <%s>, not found in database' % self.type)
        self.api.log.info('BLARGLE')
        
        # Get the ACL object definition
        acl_object = DBAuthACLObjects.objects.filter(type=self.type).values(detailed=True)[0]
        
        # If the ACL object has any assigned object
        if acl_object['objects']:
            return invalid('Cannot delete ACL object <%s> definition, contains <%s> child objects' % (self.type, str(len(acl_object['objects']))))

        # Delete the ACL object definition
        try:
            DBAuthACLObjects.objects.filter(type=self.type).delete()
            
        # Critical error when deleting ACL object
        except Exception as e:
            return invalid(self.api.log.exception('Failed to delete ACL object <%s> definition: %s' % (self.type, str(e))))

        # Return the response
        return valid('Successfully deleted ACL object definition', {
            'type': self.type
        })
Ejemplo n.º 18
0
    def launch(self):
        
        # Make sure the host exists
        if not DBHostDetails.objects.filter(uuid=self.host).count():
            return invalid('Failed to update host <%s> status, could not locate host in database' % self.host)
        
        # Get the current host details
        host_details = DBHostDetails.objects.filter(uuid=self.host).values()[0]
        
        # Update the agent status
        try:
            DBHostDetails.objects.filter(uuid=self.host).update(agent_status=self.status, last_checkin=time.strftime('%Y-%m-%d %H:%M:%S'))
        
            # Update the host cache
            self.api.cache.save_object('host', self.host)
        
        # Critical error when updating host agent status
        except Exception as e:
            return invalid('Failed to update host <%s> agent status in the database: %s' % (self.host, str(e)))

        # Broadcast the status to web portal clients if the agent status changed
        if host_details['agent_status'] != self.status:
            self.api.socket.broadcast('agent.status', {
                'uuid':   self.host,
                'status': self.status
            })

        # Agent status successfully updated
        return valid('Successfully updated host <%s> agent status to <%s>' % (self.host, self.status))
Ejemplo n.º 19
0
 def construct(self, request):
     """
     Construct and return the request object and logger.
     
     @param request: The raw Django request object
     @type  request: 
     """
     
     # Construct the request object
     self.request = APIRequest(request)
     
     # Client address and API user
     self.client  = self.request.raw.META['REMOTE_ADDR']
     self.user    = self._get_request_data('api_user')
     self.group   = self._get_request_data('api_group')
     
     # Check if a web socket is making an API call
     self._set_websock()
     
     # Set the request data and action for non-authentication requests
     if not self.endpoint == 'auth/get':
         
         # Set API data / action
         self._set_data()
         self._set_action()
     
     # Set the logger object
     self.log = APILogger(self)
     
     # Import the utility classes
     self._utils()
     
     # Return the constructed API object, ready for authentication or other requests
     return valid(self)
Ejemplo n.º 20
0
    def launch(self):

        # Make sure the host exists
        if not DBHostDetails.objects.filter(uuid=self.host).count():
            return invalid('Cannot update system information, could not locate host <%s> in database' % self.host)

        # Get the host parent object
        self.host_obj = DBHostDetails.objects.get(uuid=self.host)

        # Make sure the host system information row exists
        self._set_defaults()

        # Get the current system information
        sys_info = DBHostSystemInfo.objects.filter(host=self.host).values()[0]

        # Set the updated database parameters
        db_params = {}
        for key in ['network', 'firewall', 'partition', 'memory', 'disk', 'os', 'cpu']:
            db_params[key] = sys_info[key] if not (key in self.api.data['sys']) else json.dumps(self.api.data['sys'][key])
        
        # Update the host system information
        try:
            
            # Update the host system information table
            DBHostSystemInfo.objects.filter(host=self.host).update(**db_params)
            
            # Update the host services table
            self._set_services()
            
        # Critical error when updating system information
        except Exception as e:
            return invalid('Failed to update host <%s> system information in the database: %s' % (self.host, str(e)))
        
        # Host system information updated
        return valid('Successfully updated host <%s> system information' % self.host)
Ejemplo n.º 21
0
    def _get_api_key(self, id):
        """
        Retrieve the API key for a user or host account.
        """
        
        # Check if a user or host
        api_user = DBUserDetails.objects.filter(username=id).count()
        api_host = DBHostDetails.objects.filter(uuid=id).count()

        # If not an existing host or user
        if not api_user and not api_host:
            return invalid('Authentication failed, account <> not found in the database' % id)
        
        # If for some reason both a user and host
        if api_user and api_host:
            return invalid('Authentication failed, account <> is both user and host' % id)

        # Get the API key
        if api_user:
            
            # Make sure the user is enabled
            user_obj = DBUserDetails.objects.get(username=id)
            if not user_obj.is_active:
                return invalid('Authentication failed, account <%s> is disabled' % id)
            
            # Return the API key row
            api_key_row = DBUserAPIKeys.objects.filter(user=id).values('api_key')
        if api_host:
            api_key_row = DBHostAPIKeys.objects.filter(host=id).values('api_key')
        db_api_key  = api_key_row[0]['api_key']

        # User or host has no API key
        if not db_api_key: 
            return invalid('Authentication failed, no API key found for account <%s>' % id)
        return valid(db_api_key)
Ejemplo n.º 22
0
 def handler(self):
     """
     Main method for constructing and returning the utility map.
     
     @return valid|invalid
     """
     map_rsp = self._build_map()
     if not map_rsp['valid']:
         return map_rsp
     
     # Request path missing
     if not self.path:
         return invalid(JSONError(error='Missing request path', status=400).response())
     
     # Invalid request path
     if not self.path in self.map:
         return invalid(JSONError(error='Unsupported request path: [%s]' % self.path, status=400).response())
     
     # Verify the request method
     if self.method != self.map[self.path]['method']:
         return invalid(JSONError(error='Unsupported request method [%s] for path [%s]' % (self.method, self.path), status=400).response())
     
     # Get the API module, class handler, and name
     self.handler_obj = {
         'api_mod':   self.map[self.path]['module'],
         'api_class': self.map[self.path]['class'],
         'api_path':  self.map[self.path]['path'],
         'api_utils': self.map[self.path]['utils'],
         'api_map':   self.map[self.path]['json']
     }
     LOG.info('Parsed handler object for API utility [%s]: %s' % (self.path, self.handler_obj))
     
     # Return the handler module path
     return valid(self.handler_obj)
Ejemplo n.º 23
0
 def launch(self):
     """
     Worker method to retrieve a listing of API utilities.
     """
     try:
         
         # If grabbing a specific utility
         if 'uuid' in self.api.data:
             
             # If the utility doesn't exist
             if not DBGatewayUtilities.objects.filter(uuid=self.api.data['uuid']).count():
                 return invalid('Utility [%s] does not exist' % self.api.data['uuid'])
             return valid(json.dumps(DBGatewayUtilities.objects.filter(uuid=self.api.data['uuid']).values()[0]))
             
         # Return all utilities
         else:
             return valid(json.dumps(list(DBGatewayUtilities.objects.all().values())))
     except Exception as e:
         return invalid(self.api.log.exception('Failed to retrieve utilities listing: %s' % str(e)))
Ejemplo n.º 24
0
 def launch(self):
     """
     Worker method to retrieve a listing of API endpoints.
     """
     try:
         
         # If grabbing a specific endpoint
         if 'uuid' in self.api.data:
             
             # If the endpoint doesn't exist
             if not DBAuthEndpoints.objects.filter(uuid=self.api.data['uuid']).count():
                 return invalid('Endpoint <%s> does not exist' % self.api.data['uuid'])
             return valid(json.dumps(DBAuthEndpoints.objects.filter(uuid=self.api.data['uuid']).values()[0]))
             
         # Return all endpoints
         else:
             return valid(json.dumps(list(DBAuthEndpoints.objects.all().values())))
     except Exception as e:
         return invalid(self.api.log.exception('Failed to retrieve endpoints listing: %s' % str(e)))
Ejemplo n.º 25
0
 def _update_object_permissions(self):
     """
     Update the group object permissions.
     """
     if ('permissions' in self.api.data) and ('object' in self.api.data['permissions']):
         try:
             self.group_obj.object_permissions_set(self.api.data['permissions']['object'])
         except Exception as e:
             return invalid(self.api.log.exception('Failed to update object permissions: %s' % str(e)))
     return valid()
Ejemplo n.º 26
0
 def _update_global_permissions(self):
     """
     Update the group global permissions.
     """
     if ('permissions' in self.api.data) and ('global' in self.api.data['permissions']):
         try:
             self.group_obj.global_permissions_set(self.api.data['permissions']['global'])
         except Exception as e:
             return invalid(self.api.log.exception('Failed to update global permissions: %s' % str(e)))
     return valid()
Ejemplo n.º 27
0
 def _check_object_access(self, object_acls, group):
     """
     Determine if the user has object level access to the utility.
     """
     
     # Make sure the utility has an object type association
     if not self.utility.model.object:
         return invalid('')
     object_type = self.utility.model.object
     
     # Get the object authorization class
     obj_def   = get_obj_def(object_type)
     acl_mod   = importlib.import_module(obj_def['acl_mod'])
     acl_class = getattr(acl_mod, obj_def['acl_cls'])
         
     # Utility object key and target object value
     self.obj_key = self.utility.model.object_key
     
     # Specific object key found
     if (self.request.data) and (self.obj_key in self.request.data):
         
         # Process each ACL for the object type
         tgt_obj = None
         for object_acl in object_acls[object_type]['details']:
             tgt_obj = self.request.data[self.obj_key]
         
             # Object filter
             filter = {}
             filter['owner']            = group
             filter['allowed']          = True
             filter[obj_def['acl_key']] = tgt_obj
         
             # Check if the user has access to this object
             if acl_class.objects.filter(**filter).count():
                 return valid(LOG.info('Object level access granted for user [%s] to utility [%s] for object [%s:%s]' % (self.user.name, self.utility.path, self.utility.model.object, tgt_obj)))
     
         # Access denied
         return invalid(' for object <%s:%s>' % (self.utility.model.object, tgt_obj))
     
     # User not accessing a specific object
     else:
         return valid()
Ejemplo n.º 28
0
 def launch(self):
     """
     Worker method for returning a list of ACL object types.
     """
     
     # If retrieving a specific object type
     if self.type:
         object_details = [x for x in self.objects if x['type'] == self.type]
         
         # Make sure the object type exists
         if not object_details:
             return invalid('Could not locate ACL object of type <%s> in the database' % self.type)
         
         # Return the ACL object
         return valid(object_details[0])
     
     # Retrieving all ACL object definitions
     else:
         
         # Return ACL object definitions
         return valid(self.objects)
Ejemplo n.º 29
0
 def launch(self):
     """
     Worker method to open the endpoint for editing.
     """
     self.api.log.info('Preparing to checkout endpoint <%s> for editing' % self.endpoint)
 
     # Make sure the endpoint exists
     if not DBAuthEndpoints.objects.filter(uuid=self.endpoint).count():
         return invalid(self.api.log.error('Could not open endpoint <%s> for editing, not found in database' % self.endpoint))
     
     # Get the endpoint details row
     endpoint_row = DBAuthEndpoints.objects.filter(uuid=self.endpoint).values()[0]
     
     # Check if the endpoint is locked
     if endpoint_row['locked'] == True:
         self.api.log.info('Endpoint \'%s\' already checked out by user \'%s\'' % (self.endpoint, endpoint_row['locked_by']))
         
         # If the formula is checked out by the current user
         if endpoint_row['locked_by'] == self.api.user:
             self.api.log.info('Endpoint checkout request OK, requestor \'%s\' is the same as the locking user \'%s\'' % (self.api.user, endpoint_row['locked_by']))
             return valid('Endpoint already checked out by the current user')
         else:
             return invalid(self.api.log.error('Could not open endpoint <%s> for editing, already checked out by %s' % (self.endpoint, formula_row['locked_by'])))
 
     # Set the locking user
     locked_by = self.api.user
     
     # Lock the endpoint for editing
     self.api.log.info('Checkout out endpoint \'%s\' for editing by user \'%s\'' % (self.endpoint, locked_by))
     try:
         DBAuthEndpoints.objects.filter(uuid=self.endpoint).update(
             locked    = True,
             locked_by = self.api.user
         )
         return valid('Successfully checked out endpoint for editing')
         
     # Failed to check out the formula
     except Exception as e:
         return invalid(self.api.log.error('Failed to check out endpoint for editing with error: %s' % str(e)))
Ejemplo n.º 30
0
 def launch(self):
     """
     Worker method to open the utility for editing.
     """
     self.api.log.info('Preparing to checkout utility [%s] for editing' % self.utility)
 
     # Make sure the utility exists
     if not DBGatewayUtilities.objects.filter(uuid=self.utility).count():
         return invalid(self.api.log.error('Could not open utility [%s] for editing, not found in database' % self.utility))
     
     # Get the utility details row
     util_row = DBGatewayUtilities.objects.filter(uuid=self.utility).values()[0]
     
     # Check if the utility is locked
     if util_row['locked'] == True:
         self.api.log.info('Utility [%s] already checked out by user [%s]' % (self.utility, util_row['locked_by']))
         
         # If the utility is checked out by the current user
         if util_row['locked_by'] == self.api.user:
             self.api.log.info('Utility checkout request OK, requestor [%s] is the same as the locking user [%s]' % (self.api.user, util_row['locked_by']))
             return valid('Utility already checked out by the current user')
         else:
             return invalid(self.api.log.error('Could not open utility [%s] for editing, already checked out by %s' % (self.utility, util_row['locked_by'])))
 
     # Set the locking user
     locked_by = self.api.user
     
     # Lock the utility for editing
     self.api.log.info('Checkout out utility [%s] for editing by user [%s]' % (self.utility, locked_by))
     try:
         DBGatewayUtilities.objects.filter(uuid=self.utility).update(
             locked    = True,
             locked_by = self.api.user
         )
         return valid('Successfully checked out utility for editing')
         
     # Failed to check out the utility
     except Exception as e:
         return invalid(self.api.log.error('Failed to check out utility for editing with error: %s' % str(e)))