def register_participant(enrollment_id, plugin_id, plugin_scratch,
                             owner_name, owner_domain):
        # Checking that owner exists, is using a valid password, and the plugin is registered to that owner
        if OwnerService.does_owner_exist(owner_name, owner_domain):
            if PluginService.is_plugin_registered(plugin_id):
                owner = OwnerService.get(owner_name, owner_domain)
                enrollment = EnrollmentService.get(enrollment_id)
                plugin = PluginService.get_plugin(plugin_id)

                if owner.id == enrollment.owner_id == plugin.owner_id:
                    if EnrollmentService.is_enrollment_open(enrollment_id):
                        participants = Model.repository.participants
                        participant = participants.create()

                        participant.enrollment_id = enrollment_id
                        participant.plugin_id = plugin_id
                        participant.plugin_scratch = plugin_scratch

                        return participant.save()
                    else:
                        raise secure.SecurityException("Enrollment not open")
                else:
                    raise secure.SecurityException(
                        "Owner is not valid for enrollment or plugin")
            else:
                raise secure.SecurityException("Plugin is not valid")
    def delete(self, enrollment_id):
        logger.debug("Removing an enrollment")
        auth_response = authenticate(self, [Permissions.WRITE_ENROLLMENT])

        if auth_response['valid']:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if enrollment is None or owner.id == enrollment.owner_id:
                if enrollment is not None:  # DELETE is idempotent
                    EnrollmentService.delete_enrollment(enrollment_id)

                self.set_status(200)
                response = {"status": "success"}
            else:
                self.set_status(401)
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer this enrollment"
                }

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self):
        logger.debug("User attempting to retrieve all enrollments")
        auth_response = authenticate(self, [Permissions.READ_ENROLLMENT])

        if auth_response["valid"]:
            enrollments = EnrollmentService.get_by_owner(
                auth_response["owner_id"])

            enrollments_list = []

            for enrollment in enrollments:
                enrollment_dict = {
                    "id":
                    enrollment.id,
                    "name":
                    enrollment.name,
                    "participants":
                    EnrollmentService.participant_count(enrollment.id)
                }

                if enrollment.open_date is not None:
                    enrollment_dict[
                        "open_date"] = enrollment.open_date.strftime(
                            '%Y-%m-%d')
                else:
                    enrollment_dict["open_date"] = None

                if enrollment.close_date is not None:
                    enrollment_dict[
                        "close_date"] = enrollment.close_date.strftime(
                            '%Y-%m-%d')
                else:
                    enrollment_dict["close_date"] = None

                if enrollment.expiry_date is not None:
                    enrollment_dict[
                        "expiry_date"] = enrollment.expiry_date.strftime(
                            '%Y-%m-%d')
                else:
                    enrollment_dict["expiry_date"] = None

                enrollments_list.append(enrollment_dict)

            response = {"status": "success", "enrollments": enrollments_list}
            self.set_status(200)
        else:
            response = {
                "status": "error",
                "message": "Do not have authorization to make this request"
            }
            self.set_status(401)

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
Ejemplo n.º 4
0
    def get(self):
        logger.debug("Querying for tasks")
        auth = authenticate(self, [Permissions.READ_TASK])

        if auth["valid"]:
            surveys = SurveyService.get_surveys_by_owner(auth["owner_id"])

            surveys_tasks = {}

            for survey in surveys:
                surveys_tasks[survey] = TaskService.get_tasks_by_survey_id(
                    survey.id)

            tasks = []

            for survey, task_list in surveys_tasks.items():
                for task in task_list:
                    tasks.append({
                        "id":
                        task.id,
                        "name":
                        task.name,
                        "protocol_name":
                        ProtocolService.get_protocol(survey.protocol_id).name,
                        "enrollment_name":
                        EnrollmentService.get(survey.enrollment_id).name
                    })

            response = {"status": "success", "tasks": tasks}
            self.set_status(200)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self, enrollment_id):
        logger.debug("Getting list of enrolled participants")
        auth_response = authenticate(
            self, [Permissions.READ_ENROLLMENT, Permissions.READ_PARTICIPANT])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if owner.id == enrollment.owner_id:
                participants = ParticipantService.get_participants_in_enrollment(
                    enrollment.id)

                response = {
                    "status":
                    "success",
                    "participant_ids":
                    [participant.id for participant in participants]
                }
                self.set_status(200)
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer this enrollment"
                }
                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self, enrollment_id):
        logger.debug("Getting metadata about an enrollment")
        auth_response = authenticate(self, [Permissions.READ_ENROLLMENT])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if enrollment.owner_id == owner.id:

                enrollment_dict = {
                    "id": enrollment.id,
                    "open_date": enrollment.open_date.strftime('%Y-%m-%d'),
                    "close_date": enrollment.close_date.strftime('%Y-%m-%d'),
                    "expiry_date": enrollment.expiry_date.strftime('%Y-%m-%d')
                }

                response = {"status": "success", "enrollment": enrollment_dict}
                self.set_status(200)
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer this enrollment"
                }
                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get(self, enrollment_id, participant_id):
        logger.debug("Retrieving participant info")
        auth_response = authenticate(
            self,
            [[Permissions.READ_ENROLLMENT, Permissions.READ_PARTICIPANT]])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if owner.id == enrollment.owner_id:
                try:
                    participant = ParticipantService.get_participant(
                        participant_id)
                except SecurityException as e:
                    response = {"status": "error", "message": e.message}
                    self.set_status(410)
                else:
                    if participant is None:
                        response = {
                            "status": "error",
                            "message": "Participant does not exist"
                        }

                        self.set_status(410)
                    elif participant.enrollment_id == enrollment_id:
                        participant_dict = {
                            "participant_id": participant.id,
                            "plugin_id": participant.plugin_id,
                            "plugin_scratch": participant.plugin_scratch,
                            "enrollment_id": participant.enrollment_id
                        }

                        response = {
                            "status": "success",
                            "participant": participant_dict
                        }

                        self.set_status(200)
                    else:
                        response = {
                            "status": "error",
                            "message":
                            "Participant does not belong to enrollment"
                        }
                        self.set_status(400)
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer enrollment"
                }

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def post(self, enrollment_id):
        logger.debug("Adding participant to enrollment")
        plugin_id = self.get_argument("plugin_id")
        plugin_name = self.get_argument("plugin_name")
        plugin_scratch = self.get_argument("plugin_scratch")
        ParticipantDetails.participantEnrollment.append(enrollment_id)
        auth_response = authenticate(
            self, [Permissions.READ_ENROLLMENT, Permissions.WRITE_PARTICIPANT])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])

            if PluginService.is_owned_by(plugin_id, owner.id):
                enrollment = EnrollmentService.get(int(enrollment_id))

                if owner.id == enrollment.owner_id:
                    try:
                        ParticipantService.register_participant(
                            enrollment.id, plugin_id, plugin_scratch,
                            owner.name, owner.domain)

                        participants = ParticipantService.get_participants_in_enrollment(
                            enrollment_id)
                        for participant in participants:
                            lastparticipantid = participant.id
                        ParticipantDetails.participantEnrollment.append(
                            lastparticipantid)
                        ParticipantDetails.participantEnrollment.append(
                            plugin_name)
                        ParticipantDetails.participantEnrollment.append(
                            plugin_scratch)
                        ParticipantDetails.get_enrollment()
                    except SecurityException as e:
                        response = {"status": "error", "message": e.message}
                    else:
                        response = {"status": "success"}
                else:
                    response = {
                        "status":
                        "error",
                        "message":
                        "Owner does not have authorization to administer this enrollment"
                    }
            else:
                response = {
                    "status": "error",
                    "message":
                    "Participant's plugin is not registered with owner"
                }

                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def get_participant(participant_id):
        participants = Model.repository.participants
        participant = participants.select(
            Where(participants.id, Where.EQUAL, participant_id))

        if participant is None:
            return None

        if EnrollmentService.is_enrollment_open(participant.enrollment_id):
            return participant

        else:
            raise secure.SecurityException("Participant no longer accessible")
    def post(self, enrollment_id):
        logger.debug("Updating metadata about an enrollment")

        name = self.get_argument("name", None)
        open_date = self.get_argument("open_date", None)
        close_date = self.get_argument("close_date", None)
        expiry_date = self.get_argument("expiry_date", None)

        auth_response = authenticate(self, [Permissions.WRITE_ENROLLMENT])

        if auth_response['valid']:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if enrollment.owner_id == owner.id:

                if name is not None:
                    enrollment.name = name

                if open_date is not None:
                    enrollment.open_date = parser.parse(open_date)

                if close_date is not None:
                    enrollment.close_date = parser.parse(close_date)

                if expiry_date is not None:
                    enrollment.expiry_date = parser.parse(expiry_date)

                enrollment.save()

                response = {"status": "success"}
                self.set_status(200)
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer this enrollment"
                }
                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def delete(self, enrollment_id, participant_id):
        logger.debug("Removing participant from enrollment")
        auth_response = authenticate(
            self, [Permissions.READ_ENROLLMENT, Permissions.WRITE_PARTICIPANT])

        if auth_response["valid"]:
            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.get(enrollment_id)

            if owner.id == enrollment.owner_id:
                participant = ParticipantService.get_participant(
                    participant_id)

                if participant is None or participant.enrollment_id == enrollment.id:
                    if participant is not None:
                        ParticipantService.delete_participant(participant_id)

                    response = {
                        "status": "success",
                    }
                    self.set_status(200)
                else:
                    response = {
                        "status": "error",
                        "message": "Participant does not belong to enrollment"
                    }
            else:
                response = {
                    "status":
                    "error",
                    "message":
                    "Owner does not have authorization to administer enrollment"
                }
                self.set_status(401)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
    def post(self):
        logger.debug("Adding new enrollment")

        name = self.get_argument("name")
        open_date = self.get_argument("open_date", None)
        close_date = self.get_argument("close_date", None)
        expiry_date = self.get_argument("expiry_date", None)

        auth_response = authenticate(self, [Permissions.WRITE_ENROLLMENT])

        if auth_response["valid"]:
            if open_date is not None:
                open_date = parser.parse(open_date)

            if close_date is not None:
                close_date = parser.parse(close_date)

            if expiry_date is not None:
                expiry_date = parser.parse(expiry_date)

            owner = OwnerService.get_by_id(auth_response["owner_id"])
            enrollment = EnrollmentService.add_enrollment(
                name, owner.id, open_date, close_date, expiry_date)
            response = {"status": "success", "enrollment_id": enrollment.id}
            self.set_status(200)
        else:
            response = {
                "status": "error",
                "message": "Do not have authorization to make this request"
            }
            self.set_status(401)

        response_json = json.dumps(response)
        logger.debug(response_json)
        self.write(response_json)
        self.flush()
Ejemplo n.º 13
0
    def post(self):
        logger.debug("Posting new task")

        task_name = self.get_argument("name")
        protocol_id = int(self.get_argument("protocol_id"))
        enrollment_id = int(self.get_argument("enrollment_id"))
        time_rule = json.loads(self.get_argument("time_rule"))
        enable_notes = self.get_argument("enable_notes", False)
        timeout = int(self.get_argument("timeout"), 20)
        enable_warnings = self.get_argument("enable_warnings", True)
        enable_notes = 1 if enable_notes else 0
        enable_warnings = 1 if enable_warnings else 0

        all_run_times = []
        all_run_dates = []
        local_tz = pytz.timezone(time_rule['timezone'])
        date_conversion = time_rule["run_date"]
        time_conversion = time_rule["run_times"]
        for several_run_time in time_conversion:
            datetime_without_tz = datetime.strptime(
                str(date_conversion) + " " + str(several_run_time),
                "%Y-%m-%d %H:%M")
            datetime_with_tz = local_tz.localize(
                datetime_without_tz, is_dst=True)  # No daylight saving time
            datetime_in_utc = datetime_with_tz.astimezone(pytz.utc)
            str_utc_time = datetime_in_utc.strftime('%Y-%m-%d %H:%M %Z')
            all_run_dates.append(str_utc_time[:10])
            all_run_times.append(str_utc_time[11:16])

        time_rule["run_date"] = str_utc_time[:10]
        time_rule["run_times"] = all_run_times

        auth = authenticate(self,
                            [Permissions.WRITE_TASK, Permissions.WRITE_SURVEY])

        if auth["valid"]:
            owner_id = int(auth['owner_id'])
            response = None

            if ProtocolService.is_owned_by(protocol_id, int(auth['owner_id'])):
                if EnrollmentService.is_owned_by(enrollment_id, owner_id):
                    params = time_rule["params"]
                    run_time_values = time_rule["run_times"]

                    run_times = []

                    for run_time_value in run_time_values:
                        rtv = run_time_value.split(":")
                        hour = int(rtv[0])
                        minute = int(rtv[1])
                        run_times.append(
                            datetime.now(tz=pytz.utc).replace(hour=hour,
                                                              minute=minute,
                                                              second=0))
                    until = datetime.strptime(
                        time_rule["run_date"],
                        "%Y-%m-%d").replace(tzinfo=pytz.utc)
                    run_date = datetime.strptime(
                        time_rule["run_date"],
                        "%Y-%m-%d").replace(tzinfo=pytz.utc)
                    last_date = datetime.strptime(time_rule["run_date"],
                                                  "%Y-%m-%d")
                    start_date = datetime.strptime(time_rule["run_date"],
                                                   "%Y-%m-%d")
                    intervalcount = 'no_repeat'
                    every = 0
                    if time_rule["type"] == 'no_repeat':
                        intervalcount = 'no_repeat'
                        time_rule = NoRepeat(run_date, run_times)
                    elif time_rule["type"] == 'daily':
                        intervalcount = 'daily'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        last_date = datetime.strptime(time_rule['until'],
                                                      "%Y-%m-%d")
                        time_rule = RepeatsDaily(run_date, every, until,
                                                 run_times)
                    elif time_rule["type"] == 'weekly':
                        intervalcount = 'weekly'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsWeekly(every, params['days'],
                                                  run_times, run_date, until)
                    elif time_rule["type"] == 'monthly_date':
                        intervalcount = 'monthly_date'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsMonthlyDate(every, params['dates'],
                                                       until, run_times)
                    elif time_rule["type"] == 'monthly_day':
                        intervalcount = 'monthly_day'
                        every = int(params["every"])
                        until = datetime.strptime(
                            time_rule['until'],
                            "%Y-%m-%d").replace(tzinfo=pytz.utc)
                        time_rule = RepeatsMonthlyDay(every, params['param1'],
                                                      params['days'], until,
                                                      run_times)
                    else:
                        response = {
                            "status":
                            "error",
                            "message":
                            time_rule['type'] + " is not a valid time rule"
                        }
                        self.set_status(400)

                    for daysNo in range((last_date - start_date).days + 1):
                        DataManagement.dataStorage.append(enrollment_id)
                        listParticipants = []
                        participants = ParticipantService.get_participants_in_enrollment(
                            enrollment_id)
                        for participant in participants:
                            listParticipants.append(participant.id)
                        DataManagement.dataStorage.append(listParticipants)
                        DataManagement.dataStorage.append(start_date)
                        DataManagement.dataStorage.append(run_time_values)
                        DataManagement.dataStorage.append("cig_ecig")
                        DataManagement.dataStorage.append(until)
                        DataManagement.dataStorage.append(intervalcount)
                        DataManagement.dataStorage.append(protocol_id)
                        DataManagement.dataStorage.append("scheduled")
                        DataManagement.get_schedule()
                        start_date = start_date + timedelta(days=every)
                else:
                    response = {
                        "status": "error",
                        "message": "Enrollment not owned by account"
                    }
                    self.set_status(401)
            else:
                response = {
                    "status": "error",
                    "message": "Protocol not owned by account"
                }
                self.set_status(401)

            if response is None:
                survey = SurveyService.create_survey(owner_id, protocol_id,
                                                     enrollment_id,
                                                     enable_notes, timeout,
                                                     enable_warnings)
                time_rule_id = TimeRuleService().insert(survey.id, time_rule)
                TaskService.create_task(task_name, survey.id, time_rule_id)
                DataManagement.getSurveyid(survey.id)
                response = {"status": "success"}
                self.set_status(200)

            response_json = json.dumps(response)
            logger.debug(response_json)
            self.write(response_json)
            self.flush()
Ejemplo n.º 14
0
from smsurvey.core.model.model import Model

from smsurvey import config
from smsurvey.core.services.instance_service import InstanceService
from smsurvey.core.services.owner_service import OwnerService
from smsurvey.core.services.enrollment_service import EnrollmentService
from smsurvey.core.services.survey_service import SurveyService
from smsurvey.core.services.protocol_service import ProtocolService

Model.from_database(config.DAO)

owner = OwnerService.get("sam", "mhealth")

enrollment = EnrollmentService.get_by_owner(owner.id)[0]
survey = SurveyService.create_survey(owner.id,
                                     ProtocolService.get_all_protocols()[0].id,
                                     enrollment.id, 1, 20, 1)

instances = InstanceService.create_instances(survey.id)