def get(self, session_id): """Get the session dict based on the ID :param session_id: ID of the session :type session_id: `int` :return: Session dict :rtype: `dict` """ session_obj = self.db.session.query(models.Session).get(session_id) if session_obj is None: raise exceptions.InvalidSessionReference("No session with id: %s" % str(session_id)) return self.derive_session_dict(session_obj)
def set_session(self, session_id): """Sets the session based on the session id :param session_id: Session id :type session_id: `int` :return: None :rtype: None """ query = self.db.session.query(models.Session) session_obj = query.get(session_id) if session_obj is None: raise exceptions.InvalidSessionReference("No session with session_id: %s" % str(session_id)) query.update({'active': False}) session_obj.active = True self.db.session.commit()
def delete_session(self, session_id): """Deletes a session from the DB :param session_id: ID of the session to delete :type session_id: `int` :return: None :rtype: None """ session_obj = self.db.session.query(models.Session).get(session_id) if session_obj is None: raise exceptions.InvalidSessionReference("No session with id: %s" % str(session_id)) for target in session_obj.targets: # Means attached to only this session obj if len(target.sessions) == 1: self.db.target.delete_target(ID=target.id) self.db.session.delete(session_obj) self._ensure_default_session() # i.e if there are no sessions, add one self.db.session.commit()
def add_target_to_session(self, target_id, session_id=None): """Adds the target to the session :param target_id: ID of the target to add :type target_id: `int` :param session_id: ID of the session :type session_id: `int` :return: None :rtype: None """ session_obj = self.db.session.query(models.Session).get(session_id) target_obj = self.db.session.query(models.Target).get(target_id) if session_obj is None: raise exceptions.InvalidSessionReference("No session with id: %s" % str(session_id)) if target_obj is None: raise exceptions.InvalidTargetReference("No target with id: %s" % str(target_id)) if session_obj not in target_obj.sessions: session_obj.targets.append(target_obj) self.db.session.commit()
def remove_target_from_session(self, target_id, session_id=None): """Remove target from a session :param target_id: ID of the target :type target_id: `int` :param session_id: ID of the session :type session_id: `int` :return: None :rtype: None """ session_obj = self.db.session.query(models.Session).get(session_id) target_obj = self.db.session.query(models.Target).get(target_id) if session_obj is None: raise exceptions.InvalidSessionReference("No session with id: %s" % str(session_id)) if target_obj is None: raise exceptions.InvalidTargetReference("No target with id: %s" % str(target_id)) session_obj.targets.remove(target_obj) # Delete target whole together if present in this session alone if len(target_obj.sessions) == 0: self.db.target.delete_target(ID=target_obj.id) self.db.session.commit()