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)))
    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))
    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')
 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')
     })
 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)))
 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)
Beispiel #7
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
        })
Beispiel #8
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)
Beispiel #9
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)
Beispiel #10
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)))
 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)
Beispiel #12
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)
Beispiel #13
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
        })
Beispiel #14
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)
Beispiel #15
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))
Beispiel #16
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
        })
Beispiel #17
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))))
Beispiel #18
0
    def launch(self):
        """
        Worker method for saving changes to an endpoint.
        """

        # Make sure the endpoint exists
        if not DBAuthEndpoints.objects.filter(uuid=self.endpoint).count():
            return invalid(self.api.log.error('Could not save endpoint <%s>, not found in database' % self.endpoint))

        # Validate the endpoint attributes
        #ep_status = self.api.util.AuthEndpointsValidate.launch()
        #if not ep_status['valid']:
        #    return ep_status

        # Get the endpoint details
        endpoint_row = DBAuthEndpoints.objects.filter(uuid=self.endpoint).values()[0]
    
        # Default values
        path       = endpoint_row['path'] if not ('path' in self.api.data) else self.api.data['path']
        action     = endpoint_row['action'] if not ('action' in self.api.data) else self.api.data['action']
        method     = endpoint_row['method'] if not ('method' in self.api.data) else self.api.data['method']
        enabled    = endpoint_row['enabled'] if not ('enabled' in self.api.data) else self.api.data['enabled']
        mod        = endpoint_row['mod'] if not ('mod' in self.api.data) else self.api.data['mod']
        cls        = endpoint_row['cls'] if not ('cls' in self.api.data) else self.api.data['cls']
        utils      = endpoint_row['utils'] if not ('utils' in self.api.data) else self.api.data['utils']
        rmap       = endpoint_row['rmap'] if not ('rmap' in self.api.data) else self.api.data['rmap']
        protected  = endpoint_row['protected'] if not ('protected' in self.api.data) else self.api.data['protected']
        object     = endpoint_row['object'] if not ('object' in self.api.data) else self.api.data['object']
        object_key = endpoint_row['object_key'] if not ('object_key' in self.api.data) else self.api.data['object_key']
        name       = '%s/%s' % (path, action)

        # Attempt to update the endpoint
        try:
            DBAuthEndpoints.objects.filter(uuid=self.endpoint).update(
                name       = name,
                path       = path,
                action     = action,
                method     = method,
                enabled    = enabled,
                mod        = mod,
                cls        = cls,
                utils      = json.dumps(utils),
                protected  = protected,
                object     = object,
                object_key = object_key,
                rmap       = rmap
            )
            return valid('Successfully updated endpoint.')
        except Exception as e:
            return invalid(self.api.log.exception('Failed to update endpoint: %s' % str(e)))
Beispiel #19
0
    def launch(self):
        """
        Worker method for saving changes to a utility.
        """

        # Make sure the utility exists
        if not DBGatewayUtilities.objects.filter(uuid=self.utility).count():
            return invalid(self.api.log.error('Could not save utility [%s], not found in database' % self.utility))

        # Validate the utility attributes
        #util_status = self.api.util.GatewayUtilitiesValidate.launch()
        #if not util_status['valid']:
        #    return util_status

        # Get the utility details
        util_row = DBGatewayUtilities.objects.filter(uuid=self.utility).values()[0]
    
        # Update parameters
        params = {
            'path': self.api.data.get('path', util_row['path']),
            'method': self.api.data.get('method', util_row['method']),
            'mod': self.api.data.get('mod', util_row['mod']),
            'cls': self.api.data.get('cls', util_row['cls']),
            'utils': self.api.data.get('utils', util_row['utils']),
            'rmap': self.api.data.get('rmap', util_row['rmap']),
            'enabled': self.api.data.get('enabled', util_row['enabled']),
            'protected': self.api.data.get('protected', util_row['protected']),
            'object': self.api.data.get('object', util_row['object']),
            'object_key': self.api.data.get('object_key', util_row['object_key'])
        }
    
        # Make sure utilities value is a string
        if isinstance(params['utils'], list):
            params['utils'] = json.dumps(params['utils'])
    
        # Make sure the request map value is a string'
        if isinstance(params['rmap'], dict):
            params['rmap'] = json.dumps(params['rmap'])

        # Attempt to update the utility
        try:
            DBGatewayUtilities.objects.filter(uuid=self.utility).update(**params)
            
        # Critical error when updating utility
        except Exception as e:
            return invalid(self.api.log.exception('Failed to update utility: %s' % str(e)))

        # Successfully updated utility
        return valid('Successfully updated utility.')
Beispiel #20
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))
Beispiel #21
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)
Beispiel #22
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))
Beispiel #23
0
    def launch(self):
        """
        Worker method to handle resetting a user's password.
        """
        
        # 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 reset password for user <%s>, not found or access denied' % self.user)
        self.api.log.info('Resetting password for user <%s>' % self.user)
        
        # Generate a new random password
        new_pw = gen_password()

        # Get the user object and set the new password
        try:
            user_obj = DBUserDetails.objects.get(username=self.user)
            user_obj.set_password(new_pw)
            user_obj.save()
            self.api.log.info('Successfully reset password for user <%s>' % self.user)
            
        # Critical error when resetting user password
        except Exception as e:
            return invalid('Failed to reset password for user <%s>: %s' % (self.user, str(e)))
        
        # Send the email
        try:
            
            # Email properties
            email_sub  = 'CloudScape Password Reset: %s' % self.user
            email_txt  = 'Your password has been reset. You may login with your new password "%s".' % new_pw
            email_from = '*****@*****.**'
            email_to   = [user_obj.email]
            
            # Send the email
            send_mail(email_sub, email_txt, from_email=email_from, recipient_list=email_to, fail_silently=False)
            self.api.log.info('Sent email confirmation for password reset to user <%s>' % self.user)
            
            # Return the response
            return valid('Successfully reset user password')
        
        # Critical error when sending password reset notification
        except Exception as e:
            return invalid(self.api.log.error('Failed to send password reset confirmation: %s' % str(e)))
Beispiel #24
0
 def launch(self):
     """
     Worker method for creating a new ACL object definition.
     """
     
     # Make sure the type definition is not already used
     if DBGatewayACLObjects.objects.filter(type=self.attr['type']).count():
         return invalid('Failed to create ACL object type [%s], already defined' % self.attr['type'])
     
     # Check the ACL and object module/class definitions
     for key,status in {
         'acl': mod_has_class(self.attr['acl_mod'], self.attr['acl_cls'], no_launch=True),
         'obj': mod_has_class(self.attr['obj_mod'], self.attr['obj_cls'], no_launch=True)
     }.iteritems():
         if not status['valid']:
             return status
     
     # Set a unique ID for the ACL object
     self.attr['uuid'] = str(uuid4())
     
     # If a default ACL UUID is supplied
     if ('def_acl' in self.api.data):
         if not DBGatewayACLKeys.objects.filter(uuid=self.attr['def_acl']).count():
             return invalid('Failed to create ACL object type [%s], default ACL [%s] not found' % (self.attr['type'], self.attr['def_acl']))
     
         # Get the default ACL object
         self.attr['def_acl'] = DBGatewayACLKeys.objects.get(uuid=self.api.data['def_acl'])
         
         # Make sure the ACL has object type authentication enabled
         if not self.attr['def_acl'].type_object:
             return invalid('Failed to create ACL object type [%s], default ACL [%s] must have object authentication enabled' % (self.attr['type'], self.attr['def_acl']['uuid']))
     
     # Create the ACL object definition
     try:
         DBGatewayACLObjects(**self.attr).save()
         
     # Critical error when saving ACL object definition
     except Exception as e:
         return invalid(self.api.log.exception('Failed to create ACL object type [%s]: %s' % (self.attr['type'], str(e))))
     
     # Return the response
     return valid('Successfully created ACL object definition', {
         'type': self.attr['type'],
         'uuid': self.attr['uuid'],
         'name': self.attr['name']
     })
Beispiel #25
0
    def launch(self):
        """
        Worker method that handles the addition of members to the group.
        """

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

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

        # If the user does not exist or access denied
        if not self.user in auth_users.ids:
            return invalid('Failed to add user <%s> to group <%s>, user not found or access denied' % (self.user, self.group))
        
        # Get the group object
        group = DBGroupDetails.objects.get(uuid=self.group)
        
        # Check if the user is already a member of the group
        if self.user in group.members_list():
            return invalid('User <%s> is already a member of group <%s>' % (self.user, self.group))
        
        # Get the user object
        user = DBUser.objects.get(uuid=self.user)

        # Add the user to the group
        try:
            group.members_set(user)
            
        # Failed to add user to group
        except Exception as e:
            return invalid(self.api.log.exception('Failed to add user to group: %s' % str(e)))
        
        # Update the cached group data
        self.api.cache.save_object('group', self.group)
        
        # Return the response
        return valid('Successfully added group member', {
            'group': {
                'name':   group.name,
                'uuid':   self.group,
                'member': user.uuid
            }
        })
Beispiel #26
0
 def _update_profile(self):
     """
     Update the group profile
     """
     if 'profile' in self.api.data:
         try:
             p = self.api.data['profile']
 
             # Changing group protected state
             if 'protected' in p:
                 if not (self.group_obj.protected == p['protected']):
                     
                     # Cannot disable protected for default administrator group
                     if (self.group == G_ADMIN) and (p['protected'] != True):
                         return invalid('Cannot disable the protected flag for the default administrator group')
                     
                     # Update the protected flag
                     self.group_obj.protected = p['protected']
                     self.group_obj.save()
 
             # Changing the group description
             if 'desc' in p:
                 if not (self.group_obj.desc == p['desc']):
                     self.group_obj.desc = p['desc']
                     self.group_obj.save()
     
             # Changing the group name
             if 'name' in p:
                 if not (self.group_obj.name == p['name']):
                     self.api.log.info('Renaming group <%s> to <%s>' % (self.group_obj.name, p['name']))
                     
                     # Toggle the name change flag and rename the group
                     self.name_change = True
                     self.name_old    = self.group_obj.name
                     self.group_obj.name = p['name']
                     self.group_obj.save()
                     
                     # Set the new group name to be returned
                     self.name_return = p['name']
         except Exception as e:
             return invalid(self.api.log.exception('Failed to update group profile: %s' % str(e)))
     else:
         self.name_return = self.group_obj.name
     return valid()
Beispiel #27
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)))
Beispiel #28
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()
Beispiel #29
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()
Beispiel #30
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)))