Exemple #1
0
 def _find_rois_annotation_step(self, label):
     try:
         annotation_step = ROIsAnnotationStep.objects.get(label=label)
         return annotation_step
     except ROIsAnnotationStep.DoesNotExist:
         raise NotFound('No ROIs annotation step with label \'%s\'' % label)
Exemple #2
0
    def test_exception_handler(self):
        response_404 = exception_handler(NotFound(), None)
        response_400 = exception_handler(ParseError(), None)

        self.assertEqual(404, response_404.status_code)
        self.assertEqual(400, response_400.status_code)
Exemple #3
0
 def filter_queryset_by_parents_lookups(self, queryset):
     parents_query_dict = self.get_parents_query_dict()
     try:
         return queryset.filter(Q(**parents_query_dict) | Q(is_global=True))
     except ValueError:
         raise NotFound()
Exemple #4
0
def get_location(pk):
    try:
        return Location.objects.get(pk=pk)
    except Location.DoesNotExist:
        raise NotFound()
Exemple #5
0
def authorize(request,
              res_id,
              needed_permission=ACTION_TO_AUTHORIZE.VIEW_RESOURCE,
              raises_exception=True):
    """
    This function checks if a user has authorization for resource related actions as outlined
    below. This function doesn't check authorization for user sharing resource with another user.

    How this function should be called for different actions on a resource by a specific user?
    1. User wants to view a resource (both metadata and content files) which includes
       downloading resource bag or resource content files:
       authorize(request, res_id=id_of_resource,
       needed_permission=ACTION_TO_AUTHORIZE.VIEW_RESOURCE)
    2. User wants to view resource metadata only:
       authorize(request, res_id=id_of_resource,
       needed_permission=ACTION_TO_AUTHORIZE.VIEW_METADATA)
    3. User wants to edit a resource which includes:
       a. edit metadata
       b. add file to resource
       c. delete a file from the resource
       authorize(request, res_id=id_of_resource,
       needed_permission=ACTION_TO_AUTHORIZE.EDIT_RESOURCE)
    4. User wants to set resource flag (public, published, shareable etc):
       authorize(request, res_id=id_of_resource,
       needed_permission=ACTION_TO_AUTHORIZE.SET_RESOURCE_FLAG)
    5. User wants to delete a resource:
       authorize(request, res_id=id_of_resource,
       needed_permission=ACTION_TO_AUTHORIZE.DELETE_RESOURCE)
    6. User wants to create new version of a resource:
       authorize(request, res_id=id_of_resource,
       needed_permission=ACTION_TO_AUTHORIZE.CREATE_RESOURCE_VERSION)

    Note: resource 'shareable' status has no effect on authorization
    """
    authorized = False
    user = get_user(request)

    try:
        res = hydroshare.utils.get_resource_by_shortkey(res_id, or_404=False)
    except ObjectDoesNotExist:
        raise NotFound(detail="No resource was found for resource id:%s" %
                       res_id)

    if needed_permission == ACTION_TO_AUTHORIZE.VIEW_METADATA:
        if res.raccess.discoverable or res.raccess.public:
            authorized = True
        elif user.is_authenticated() and user.is_active:
            authorized = user.uaccess.can_view_resource(res)
    elif user.is_authenticated() and user.is_active:
        if needed_permission == ACTION_TO_AUTHORIZE.VIEW_RESOURCE:
            authorized = user.uaccess.can_view_resource(res)
        elif needed_permission == ACTION_TO_AUTHORIZE.EDIT_RESOURCE:
            authorized = user.uaccess.can_change_resource(res)
        elif needed_permission == ACTION_TO_AUTHORIZE.DELETE_RESOURCE:
            authorized = user.uaccess.can_delete_resource(res)
        elif needed_permission == ACTION_TO_AUTHORIZE.SET_RESOURCE_FLAG:
            authorized = user.uaccess.can_change_resource_flags(res)
        elif needed_permission == ACTION_TO_AUTHORIZE.CREATE_RESOURCE_VERSION:
            authorized = user.uaccess.owns_resource(res)
        elif needed_permission == ACTION_TO_AUTHORIZE.VIEW_RESOURCE_ACCESS:
            authorized = user.uaccess.can_view_resource(res)
        elif needed_permission == ACTION_TO_AUTHORIZE.EDIT_RESOURCE_ACCESS:
            authorized = user.uaccess.can_share_resource(res, 2)
    elif needed_permission == ACTION_TO_AUTHORIZE.VIEW_RESOURCE:
        authorized = res.raccess.public

    if raises_exception and not authorized:
        raise PermissionDenied()
    else:
        return res, authorized, user
Exemple #6
0
 def get_queryset(self):
     try:
         company = Company.objects.get(id=self.kwargs["company_id"])
     except ObjectDoesNotExist:
         raise NotFound(detail="Company Does not exist")
     return company.job_set.all()
Exemple #7
0
 def find_user(self, pk):
     try:
         return User.objects.get(pk=pk)
     except User.DoesNotExist:
         raise NotFound({'message': 'Not a valid user'})
Exemple #8
0
 def _find_clinical_annotation(self, case_id):
     try:
         return ClinicalAnnotation.objects.filter(case=case_id)
     except ClinicalAnnotation.DoesNotExist:
         raise NotFound('No clinical annotations found for case ID \'%s\'' % case_id)
Exemple #9
0
    def get_report_data(self, *args, **kwargs):
        """Route reports based on report_type param."""
        report_type = self.request.query_params.get(
            "report_type", "facility_count_by_county")
        if report_type == "facility_count_by_facility_type_detailed":
            return self._get_facility_type_data()

        if report_type == "facility_count_by_county":
            return self._get_facility_count_by_county()

        if report_type == "facility_keph_level_report":
            return self._get_facility_count(keph=True)

        if report_type == "facility_constituency_report":
            return self._get_facility_constituency_data()

        if report_type == "facility_count_by_sub_county":
            return self._get_facility_sub_county_data()

        if report_type == "individual_facility_beds_and_cots":
            return self._get_facilities_beds_and_cots()

        if report_type == "facility_count_by_owner_category":
            return self._get_facility_count(category=True)

        if report_type == "facility_count_by_owner":
            return self._get_facility_count(category=False)

        if report_type == "facility_count_by_facility_type":
            return self._get_facility_count(category=False, f_type=True)

        if report_type == "gis":
            return self._get_gis_report()

        if report_type == "beds_and_cots_by_county":
            return self._get_beds_and_cots({
                'ward__sub_county__county__name': 'county_name',
                'ward__sub_county__county': 'county'
            })

        if report_type == "beds_and_cots_by_constituency":
            county_id = self.request.query_params.get("county", None)
            filters = (
                {} if county_id is None
                else {"ward__sub_county__county": county_id}
            )
            return self._get_beds_and_cots(vals={
                'ward__sub_county__name': 'sub_county_name',
                'ward__sub_county': 'sub_county'
            }, filters=filters)

        if report_type == "beds_and_cots_by_ward":
            constituency_id = self.request.query_params.get(
                "constituency", None
            )
            filters = (
                {} if constituency_id is None
                else {"ward__sub_county": constituency_id}
            )
            return self._get_beds_and_cots(
                vals={'ward__name': 'ward_name', 'ward': "ward"},
                filters=filters
            )

        more_filters_params = self.request.query_params.get("filters", None)

        report_config = REPORTS.get(report_type, None)
        if report_config is None:
            raise NotFound(detail="Report not found.")

        group_by = report_config.get("group_by")
        app_label, model_name = report_config.get(
            "filter_fields").get("model").split('.')
        filter_field_name = report_config.get(
            "filter_fields").get("filter_field_name")
        model = apps.get_model(app_label, model_name)
        model_instances = model.objects.all()

        if more_filters_params:
            model_instances = self._filter_by_extra_params(
                report_config, more_filters_params, model)

        return_instance_name = report_config.get(
            "filter_fields").get("return_field")[0]
        return_count_name = report_config.get(
            "filter_fields").get("return_field")[1]
        if group_by:
            pass
        else:
            data = self._get_return_data(
                filter_field_name, model_instances, return_instance_name,
                return_count_name)
        return data, self.queryset.count()
Exemple #10
0
 def _find_prediction_by_review(self, review_label):
     try:
         prediction_review = PredictionReview.objects.get(label=review_label)
         return prediction_review.prediction
     except PredictionReview.DoesNotExist:
         raise NotFound(f'No prediction review with label {review_label}')
Exemple #11
0
 def _find_rois_annotation(self, case_id):
     try:
         return ROIsAnnotation.objects.filter(case=case_id)
     except ROIsAnnotation.DoesNotExist:
         raise NotFound('No ROIs annotations found for case ID \'%s\'' % case_id)
Exemple #12
0
 def _find_clinical_annotation_step(self, label):
     try:
         annotation_step = ClinicalAnnotationStep.objects.get(label=label)
         return annotation_step
     except ClinicalAnnotationStep.DoesNotExist:
         raise NotFound('No clinical annotation step with label \'%s\'' % label)
Exemple #13
0
 def _find_rois_review_step(self, rois_review_id, slide_id):
     try:
         return ROIsAnnotationStep.objects.get(rois_annotation=rois_review_id, slide=slide_id)
     except ROIsAnnotationStep.DoesNotExist:
         raise NotFound('No ROIs annotation step for ROIs Annotation %s related to slide %s' %
                        (rois_review_id, slide_id))
Exemple #14
0
 def _find_rois_annotation_step(self, annotation_step_label):
     try:
         return ROIsAnnotationStep.objects.get(label=annotation_step_label)
     except ROIsAnnotationStep.DoesNotExist:
         raise NotFound('No ROIs annotation step with label %s' % annotation_step_label)
Exemple #15
0
 def next(self, request, pk=None):
     try:
         return Response({'id': QuestionSet.objects.get_next(pk).pk})
     except QuestionSet.DoesNotExist as e:
         raise NotFound({'message': e.message})
Exemple #16
0
 def get_object_or_404(self, pk=None):
     try:
         return integrationLib.get(pk)
     except IntegrationNotFound:
         raise NotFound('That integration does not exist')
 def permission_denied(self, request, message=None):
     if (settings.HIDE_USERS and request.user.is_authenticated
             and self.action
             in ["update", "partial_update", "list", "retrieve"]):
         raise NotFound()
     super().permission_denied(request, message=message)
Exemple #18
0
 def get_object_or_404(self, pk=None):
     try:
         return ThemeManager.Zones.get(pk)
     except ZoneNotFound:
         raise NotFound("The zone with id '%s' does not exist" % pk)
Exemple #19
0
 def _find_questionnaire_request(self, label):
     try:
         return QuestionnaireRequest.objects.get(label=label)
     except QuestionnaireRequest.DoesNotExist:
         raise NotFound('No Questionnaire Request with label \'%s\'' %
                        label)
Exemple #20
0
    def get(self, request, *args, **kwargs):
        project = get_object_with_check_and_log(request,
                                                Project,
                                                pk=self.kwargs['pk'])
        # TODO: LSE option
        # if not project.is_published:
        #     raise PermissionDenied('Project is not published.')
        self.check_object_permissions(request, project)
        user = request.user

        # support actions api call from actions/next_task.py
        if hasattr(self, 'prepared_tasks'):
            project.prepared_tasks = self.prepared_tasks
            external_prepared_tasks_used = True
        # get prepared tasks from request params (filters, selected items)
        else:
            project.prepared_tasks = get_prepared_queryset(
                self.request, project)
            external_prepared_tasks_used = False

        # detect solved and not solved tasks
        user_solved_tasks_array = user.annotations.filter(
            ground_truth=False).filter(Q(task__isnull=False)).values_list(
                'task__pk', flat=True)

        with conditional_atomic():
            not_solved_tasks = project.prepared_tasks.\
                exclude(pk__in=user_solved_tasks_array).filter(is_labeled=False)
            not_solved_tasks_count = not_solved_tasks.count()

            # return nothing if there are no tasks remain
            if not_solved_tasks_count == 0:
                raise NotFound(
                    f'There are no tasks remaining to be annotated by the user={user}'
                )
            logger.debug(
                f'{not_solved_tasks_count} tasks that still need to be annotated for user={user}'
            )

            # # ordered by data manager
            # if external_prepared_tasks_used:
            #     next_task = not_solved_tasks.first()
            #     if not next_task:
            #         raise NotFound('No more tasks found')
            #     return self._make_response(next_task, request)

            # If current user has already lock one task - return it (without setting the lock again)
            next_task = Task.get_locked_by(user, project)
            if next_task:
                return self._make_response(next_task,
                                           request,
                                           use_task_lock=False)

            if project.show_ground_truth_first:
                logger.debug(
                    f'User={request.user} tries ground truth from {not_solved_tasks_count} tasks'
                )
                next_task = self._try_ground_truth(not_solved_tasks, project)
                if next_task:
                    return self._make_response(next_task, request)

            if project.show_overlap_first:
                # don't output anything - just filter tasks with overlap
                logger.debug(
                    f'User={request.user} tries overlap first from {not_solved_tasks_count} tasks'
                )
                _, not_solved_tasks = self._try_tasks_with_overlap(
                    not_solved_tasks)

            # if there any tasks in progress (with maximum number of annotations), randomly sampling from them
            logger.debug(
                f'User={request.user} tries depth first from {not_solved_tasks_count} tasks'
            )
            next_task = self._try_breadth_first(not_solved_tasks)
            if next_task:
                return self._make_response(next_task, request)

            if project.sampling == project.UNCERTAINTY:
                logger.debug(
                    f'User={request.user} tries uncertainty sampling from {not_solved_tasks_count} tasks'
                )
                next_task = self._try_uncertainty_sampling(
                    not_solved_tasks, project, user_solved_tasks_array)

            elif project.sampling == project.UNIFORM:
                logger.debug(
                    f'User={request.user} tries random sampling from {not_solved_tasks_count} tasks'
                )
                next_task = self._get_random_unlocked(not_solved_tasks)

            elif project.sampling == project.SEQUENCE:
                logger.debug(
                    f'User={request.user} tries sequence sampling from {not_solved_tasks_count} tasks'
                )
                next_task = self._get_first_unlocked(
                    not_solved_tasks.all().order_by('id'))

            if next_task:
                return self._make_response(next_task, request)
            else:
                raise NotFound(
                    f'There exist some unsolved tasks for the user={user}, but they seem to be locked by another users'
                )
Exemple #21
0
def get_task(pk):
    try:
        return Tasks.objects.get(pk=pk)
    except Tasks.DoesNotExist:
        raise NotFound()
Exemple #22
0
    def _business_logic(request_data: dict) -> OrderedDict:
        # By this point, our award_id has been validated and cleaned up by
        # TinyShield.  We will either have an internal award id that is an
        # integer or a generated award id that is a string.
        award_id = request_data["award_id"]
        award_id_column = "award_id" if type(
            award_id) is int else "generated_unique_award_id"

        try:
            parent_award = ParentAward.objects.get(
                **{award_id_column: award_id})
            account_data = fetch_account_details_idv(award_id, award_id_column)
            return OrderedDict((
                ("award_id", parent_award.award_id),
                ("generated_unique_award_id",
                 parent_award.generated_unique_award_id),
                ("child_idv_count", parent_award.direct_idv_count),
                ("child_award_count", parent_award.direct_contract_count),
                ("child_award_total_obligation",
                 parent_award.direct_total_obligation),
                ("child_award_base_and_all_options_value",
                 parent_award.direct_base_and_all_options_value),
                ("child_award_base_exercised_options_val",
                 parent_award.direct_base_exercised_options_val),
                ("child_total_account_outlay",
                 account_data["child_total_account_outlay"]),
                ("child_total_account_obligation",
                 account_data["child_total_account_obligation"]),
                ("child_account_outlays_by_defc",
                 account_data["child_account_outlays_by_defc"]),
                ("child_account_obligations_by_defc",
                 account_data["child_account_obligations_by_defc"]),
                ("grandchild_award_count", parent_award.rollup_contract_count -
                 parent_award.direct_contract_count),
                (
                    "grandchild_award_total_obligation",
                    parent_award.rollup_total_obligation -
                    parent_award.direct_total_obligation,
                ),
                (
                    "grandchild_award_base_and_all_options_value",
                    parent_award.rollup_base_and_all_options_value -
                    parent_award.direct_base_and_all_options_value,
                ),
                (
                    "grandchild_award_base_exercised_options_val",
                    parent_award.rollup_base_exercised_options_val -
                    parent_award.direct_base_exercised_options_val,
                ),
                ("grandchild_total_account_outlay",
                 account_data["grandchild_total_account_outlay"]),
                ("grandchild_total_account_obligation",
                 account_data["grandchild_total_account_obligation"]),
                ("grandchild_account_outlays_by_defc",
                 account_data["grandchild_account_outlays_by_defc"]),
                ("grandchild_account_obligations_by_defc",
                 account_data["grandchild_account_obligations_by_defc"]),
            ))
        except ParentAward.DoesNotExist:
            logger.info("No IDV Award found where '%s' is '%s'" %
                        next(iter(request_data.items())))
            raise NotFound("No IDV award found with this id")
Exemple #23
0
 def last_scanned_card(self, request):
     event = AuthEvent.objects.filter(
         event_type=AuthEvent.CARD).order_by('-date').first()
     if event is None:
         raise NotFound(detail="No scanned cards", code=404)
     return Response({"card_id": event.value})
Exemple #24
0
 def retrieve(self, request, *args, **kwargs):
     try:
         return super(OrderView, self).retrieve(request, *args, **kwargs)
     except OrderModel.DoesNotExist:
         raise NotFound("No order has been found for the current user.")
Exemple #25
0
    def do_login(self, request, *args, **kwargs):

        user_account = request.data.get("user")
        user_password = request.data.get("user_password")
        way = request.data.get("way")

        try:
            if way == "phone":
                user = User.objects.get(user_phone=user_account)
            elif way == "name":
                user = User.objects.get(user_name=user_account)
            elif way == "email":
                user = User.objects.get(user_email=user_account)
            else:
                raise NotFound(detail="您所输入的用户不存在")
        except User.DoesNotExist:
            data = {
                "status": status.HTTP_404_NOT_FOUND,
                "msg": "您输入的用户不存在",
                "data": request.data
            }
            return Response(data)

        # try:
        #     if User.objects.get(user_name=user_account):
        #         user = User.objects.get(user_name=user_account)
        #     elif User.objects.get(user_phone=user_account):
        #         user = User.objects.get(user_phone=user_account)
        #     else:
        #         user = None
        # except User.DoesNotExist:
        #     raise NotFound(detail="用户不存在")

        if not user.verify_password(user_password):
            data = {
                "status": status.HTTP_406_NOT_ACCEPTABLE,
                "msg": "密码错误",
                "data": request.data
            }
            return Response(data)

        if user.user_lock:
            data = {
                "status": status.HTTP_403_FORBIDDEN,
                "msg": "用户已被禁用",
                "data": request.data
            }
            return Response(data)
        # print("2@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")

        token = generate_user_token()

        cache.set("token", token, timeout=USER_TIMEOUT)
        cache.set(token, user.id, timeout=USER_TIMEOUT)

        resp_user = {
            "id": user.id,
            "name": user.user_name,
            "phone": user.user_phone,
            "token": token
        }

        resp_data = {
            "status": status.HTTP_200_OK,
            "msg": "登录成功",
            "data": resp_user
        }

        return Response(resp_data)
 def delete(self, condominio_id):
     try:
         Condominio.objects.get(id=condominio_id).delete()
     except Condominio.DoesNotExist:
         raise NotFound(detail='Condomínio não encontrado')
 def get_object(self, id):
     try:
         return PrizeStructure.objects.get(pk=id)
     except PrizeStructure.DoesNotExist:
         raise NotFound()
 def find_by_id(self, condominio_id):
     try:
         return Condominio.objects.get(id=condominio_id)
     except Condominio.DoesNotExist:
         raise NotFound(detail='Condomínio não encontrado')
Exemple #29
0
 def get_object(self):
     try:
         return super().get_object()
     except Http404:
         raise NotFound(code=ResultCodes.ERR_UNKNOWN_ID,
                        detail='No experiment using that id was found')
Exemple #30
0
 def _find_clinical_annotation(self, label):
     try:
         return ClinicalAnnotation.objects.get(label=label)
     except ClinicalAnnotation.DoesNotExist:
         raise NotFound('No clinical annotation found with label \'%s\'' % label)