Пример #1
0
def upload_file_to_s3(apps, schema_editor):
    Resort = apps.get_model("resorts", "Resort")

    # Create s3 client with provided credential
    client = create_s3_client()

    # Media directory where all media files are located
    media_path = os.path.join(settings.MEDIA_ROOT, 'media')

    # Iterate through each of the media directory
    # First level describes resort_id
    for each_dir in os.listdir(media_path):
        if uuid(each_dir):
            media_incident_path = os.path.join(media_path, each_dir)
            # Interate through second level which describes incident_id
            for each_incident_dir in os.listdir(media_incident_path):
                if uuid(each_incident_dir):
                    for each_file in os.listdir(os.path.join(media_incident_path, each_incident_dir)):
                        try:
                            # Fetch the resort to check KMS settings
                            resort = Resort.objects.get(resort_id=each_dir)

                            # Use global KMS Key for Encryption
                            kms_key = settings.GLOBAL_KMS_KEY_ID

                            # If resort has its own CMK then use it instead of global one
                            if resort.kms_enabled and resort.kms_cmk != "" and (resort.kms_cmk is not None):
                                kms_key = resort.kms_cmk
                            if os.path.isfile(os.path.join(media_incident_path, each_incident_dir, each_file)):
                                with open(os.path.join(media_incident_path, each_incident_dir, each_file)) as file_to_upload:
                                    response = client.put_object(Body=file_to_upload, Bucket=settings.BUCKET_NAME, Key="%s/%s/%s" % (each_dir, each_incident_dir, each_file), ServerSideEncryption="aws:kms", SSEKMSKeyId=kms_key)
                        except:
                            pass
Пример #2
0
    def get(self, request, *args, **kwargs):
        incident_id = kwargs.get('uuid')
        response_data = {}
        status_data = []

        if not uuid(incident_id):
            return Response({_('detail'): _('not a valid UUID')}, status=400)

        try:
            incident = Incident.objects.get(incident_id=incident_id)
            if incident.incident_status.order == 9:
                raise ObjectDoesNotExist
        except ObjectDoesNotExist:
            return Response({_("detail"): _("Incident does not exists")}, status=400)

        status_history = StatusHistory.objects.filter(incident=incident).order_by('status_date')

        for status in status_history:
            status_data.append(StatusHistorySerializer(status, fields=('status_history_id', 'status', 'status_date',
                                                                       'user')).data)

        response_data['status_count'] = len(status_history)
        response_data['status'] = status_data

        return Response(response_data, status=200)
Пример #3
0
    def get(self, request):
        resort_id = request.GET.get('resort_id')
        if resort_id is None or resort_id == '':
            return Response({_('detail'): _('resort_id not provided')}, status=400)

        if not uuid(resort_id):
            return Response({_('detail'): _('not a valid UUID')}, status=400)

        resort = Resort.objects.filter(resort_id=resort_id).first()

        if resort is not None:
            incident_template = resort.incident_template
        else:
            return Response({_('detail'): _('Resort does not exists')}, status=400)

        if request.user.user_connected == 0:
            incident_template['DashboardItems'].pop('field_52d47aac9bd13', None)
        else:
            try:
                patroller_sorted_list = sorted(
                    incident_template['DashboardItems']['field_52d47aac9bd13']['RepeatingQuestions']['patroller'][
                        'Values'], key=lambda k: k[k.keys()[0]].lower())
                incident_template['DashboardItems']['field_52d47aac9bd13']['RepeatingQuestions']['patroller'][
                    'Values'] = patroller_sorted_list
            except:
                pass

        if resort is not None:
            return Response(incident_template, status=200)
        else:
            return Response({_('detail'): _('Resort does not exists')}, status=400)
Пример #4
0
    def post(self, request, *args, **kwargs):
        incident_id = kwargs.get('uuid')

        if not uuid(incident_id):
            return Response({_('detail'): _('not a valid UUID')}, status=400)

        try:
            incident = Incident.objects.get(incident_id=incident_id)
            if incident.incident_status.order == 9:
                raise Exception
        except ObjectDoesNotExist:
            return Response({_("detail"): _("Incident does not exists")}, status=400)

        if request.data.get('field_52ca448dg94ja4') is not None:
            timestamp = datetime.strptime(request.data.get('field_52ca448dg94ja4'), "%Y-%m-%d %H:%M:%S")
        else:
            timestamp = datetime.now()

        note = IncidentNotes(incident=incident, note=request.data.get('field_52ca448dg94ja3'), note_date=timestamp,
                             user=request.user)
        note.save()

        note_response = IncidentNotesSerializer(note, fields=('note_id', 'note_date', 'note'))

        return Response(note_response.data, status=200)
Пример #5
0
 def test_create(self, mock_upload):
     validate_data = {
         'path': 'valid_path',
         'image': MagicMock()
     }
     serializer = ImageUploadSerializer()
     result = serializer.create(validate_data)
     iid = result['iid']
     self.assertTrue(uuid(iid))
     self.assertTrue(mock_upload.called_once_with('valid_path/{0}'.format(iid), validate_data['image']))
Пример #6
0
def upload_file_to_s3(request):
    messages = []
    resorts = []
    not_found_id = []
    # Create s3 client with provided credential
    client = create_s3_client()

    # Media directory where all media files are located
    media_path = os.path.join(settings.MEDIA_ROOT, 'media')

    # Iterate through each of the media directory
    # First level describes resort_id
    for each_dir in os.listdir(media_path):
        if uuid(each_dir):
            try:
                # Fetch the resort to check KMS settings
                resort = Resort.objects.get(resort_id=each_dir)
                resorts.append(resort.resort_name)
            except ObjectDoesNotExist:
                not_found_id.append(each_dir)
                continue
            media_incident_path = os.path.join(media_path, each_dir)
            # Interate through second level which describes incident_id
            for each_incident_dir in os.listdir(media_incident_path):
                if uuid(each_incident_dir):
                    for each_file in os.listdir(os.path.join(media_incident_path, each_incident_dir)):
                        # Use global KMS Key for Encryption
                        kms_key = settings.GLOBAL_KMS_KEY_ID

                        # If resort has its own CMK then use it instead of global one
                        if resort.kms_enabled and resort.kms_cmk != "" and (resort.kms_cmk is not None):
                            kms_key = resort.kms_cmk
                        if os.path.isfile(os.path.join(media_incident_path, each_incident_dir, each_file)):
                            with open(os.path.join(media_incident_path, each_incident_dir, each_file)) as file_to_upload:
                                response = client.put_object(Body=file_to_upload.read(), Bucket=settings.BUCKET_NAME, Key="%s/%s/%s" % (each_dir, each_incident_dir, each_file), ServerSideEncryption="aws:kms", SSEKMSKeyId=kms_key)
                            messages.append(resort.resort_name + " File with Key " + "%s/%s/%s" % (each_dir, each_incident_dir, each_file) + " Uploaded Successfully")
    return Response({"messages": messages, "resorts found": resorts, "not found resort": not_found_id}, status=200)
Пример #7
0
    def post(self, request, *args, **kwargs):
        with transaction.atomic():
            incident_id = kwargs.get('uuid')

            if not uuid(incident_id):
                return Response({_('detail'): _('not a valid UUID')}, status=400)

            try:
                incident = Incident.objects.select_for_update().get(incident_id=incident_id)
                if incident.incident_status.order == 9:
                    raise ObjectDoesNotExist
            except ObjectDoesNotExist:
                return Response({_("detail"): _("Incident does not exists")}, status=400)

            user_role = get_roleid_user(incident.resort, request.user)
            status_id = int(request.data.get('status_type_id'))

            if user_role != 3 and incident.incident_status.order == 8:
                return Response({_("detail"): _("You do not have permission to open this incident")}, status=403)
            elif user_role == 1 and status_id == 9:
                return Response({_("detail"): _("You do not have permission to delete this incident")}, status=403)

            if status_id is not None:
                try:
                    status = IncidentStatus.objects.get(incident_status_id=status_id)
                except ObjectDoesNotExist:
                    return Response({_("detail"): _("incident status not found")}, status=400)

            updated_by = request.data.get('updated_by')

            if updated_by is not None:
                try:
                    updated_user = get_user_model().objects.get(user_id=updated_by)
                except ObjectDoesNotExist:
                    return Response({_("detail"): _("updated_by user not found")}, status=400)
            else:
                updated_user = request.user

            incident.incident_status = status
            incident.save()

            if request.data.get('status_date') is not None:
                timestamp = datetime.strptime(request.data.get('status_date'), "%Y-%m-%d %H:%M:%S")
            else:
                timestamp = timezone.now()

            status_history(incident, status, updated_user, timestamp)

            return Response({"incident_id": incident.incident_id}, status=200)
Пример #8
0
    def patch(self, request):
        resort_id = request.GET.get('resort_id')
        json = request.data

        if resort_id is None or resort_id == '':
            return Response({_('detail'): _('resort id not provided')})

        if not uuid(resort_id):
            return Response({_('detail'): _('not a valid UUID')})

        resort = Resort.objects.filter(resort_id=resort_id).first()

        if resort is not None:

            incident_template = dict(resort.incident_template.items() + json.items())
            resort.incident_template = incident_template
            resort.save()
        else:
            return Response({_('detail'): _('Resort does not exists')}, status=400)
Пример #9
0
    def get(self, request, *args, **kwargs):
        incident_id = kwargs.get('uuid')
        response_data = {}

        if not uuid(incident_id):
            return Response({_('detail'): _('not a valid UUID')}, status=400)

        try:
            incident = Incident.objects.get(incident_id=incident_id)
            if incident.incident_status.order == 9:
                raise Exception
        except ObjectDoesNotExist:
            return Response({_("detail"): _("Incident does not exists")}, status=400)

        notes = IncidentNotes.objects.filter(incident_id=incident).order_by('-note_date')

        notes = IncidentNotesSerializer(notes, fields=('note_id', 'note_date', 'note', 'user'), many=True)

        response_data['results'] = notes.data
        response_data['count'] = len(notes.data)
        response_data['incident_id'] = incident_id

        return Response(response_data, status=200)
Пример #10
0
    def list(self, request, *args, **kwargs):
        user = self.request.user
        resort_id = request.query_params.get('resort_id')
        assigned_to = request.query_params.get('assigned_to')
        order_by = request.query_params.get('order_by', 'incident_pk')
        order_by_direction = request.query_params.get('order_by_direction', 'desc')
        include_status = map(int, request.query_params.get('include_status', '1, 2, 3, 4, 5, 6, 7, 8').split(','))

        if order_by_direction == 'desc':
            order = '-' + order_by
        elif order_by_direction == 'asc':
            order = order_by

        if resort_id is None:
            if not user.is_admin:
                resort = get_resort_for_user(user)
            else:
                resort = None
        else:
            if not uuid(resort_id):
                return Response({_('detail'): _('not a valid UUID')}, status=400)
            try:
                resort = Resort.objects.get(resort_id=resort_id)
            except ObjectDoesNotExist:
                return Response({_("detail"): _("Resort does not exists")}, status=400)

        user_role = get_roleid_user(resort, user)

        dateFrom = request.query_params.get('date_from', None)
        if dateFrom is None:
            dateFrom = datetime.today()
            dateFrom = dateFrom.strftime("%Y-%m-%d 00:00:00")
        else:
            dateFrom = (datetime.strptime(dateFrom, "%Y-%m-%d %H:%M:%S"))

        dateTo = request.query_params.get('date_to', None)
        if dateTo is None:
            dateTo = datetime.today()
            dateTo = dateTo.strftime("%Y-%m-%d 23:59:59")
        else:
            dateTo = (datetime.strptime(dateTo, "%Y-%m-%d %H:%M:%S"))

        # if request.query_params.get('date_from') is not None:
        #     date_from = datetime.datetime.strptime(request.query_params.get('date_from'), "%Y-%m-%d %H:%M:%S")
        # else:
        #     date_from = datetime.datetime.combine(timezone.now().date(), datetime.time(12, 0, 0))
        #
        # if request.query_params.get('date_to') is not None:
        #     date_to = datetime.datetime.strptime(request.query_params.get('date_to'), "%Y-%m-%d %H:%M:%S")
        # else:
        #     date_to = datetime.datetime.combine(timezone.now().date() + datetime.timedelta(days=1), datetime.time(12, 0, 0))

        if request.query_params.get('assigned_to') is not None:
            try:
                assigned_to = get_user_model().objects.get(user_id=request.query_params.get('assigned_to'))
            except ObjectDoesNotExist:
                return Response({_("detail"): _("assigned_to user does not exists")}, status=400)

        # If user is admin then show all the incidents across all the resorts
        if user.is_admin:
            if resort is None:
                query = Incident.objects.filter(dt_created__gte=dateFrom, dt_created__lte=dateTo,
                                                incident_status__order__in=include_status).order_by(order)
            else:
                query = Incident.objects.filter(resort=resort, dt_created__gte=dateFrom, dt_created__lte=dateTo,
                                                incident_status__order__in=include_status).order_by(order)

        # If user is resort patroller (or) connected to resort as SOLO user then only return incidents assigned to him
        elif user_role == 1 or user.user_connected == 0:
            query = Incident.objects.filter(resort=resort, assigned_to=user, dt_created__gte=dateFrom,
                                            dt_created__lte=dateTo, incident_status__order__in=include_status).order_by(
                order)

        # For manager, dispatcher connected with resort as networked user show all the incidents if assigned_to is not provided
        else:
            if assigned_to is None:
                query = Incident.objects.filter(resort=resort, dt_created__gte=dateFrom, dt_created__lte=dateTo,
                                                assigned_to__user_connected=1,
                                                incident_status__order__in=include_status).order_by(order)
            else:
                query = Incident.objects.filter(resort=resort, assigned_to=assigned_to, dt_created__gte=dateFrom,
                                                dt_created__lte=dateTo,
                                                incident_status__order__in=include_status).order_by(order)

        queryset = self.filter_queryset(query)

        page = self.paginate_queryset(queryset)
        if page is not None:
            data_key = get_data_key(resort)
            serializer = IncidentListSerializer(page, fields=(
            'incident_pk', 'incident_id', 'dt_created', 'resort', 'incident_status', 'assigned_to'),
                                            many=True, context={'data_key': data_key})
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
Пример #11
0
    def post(self, request, *args, **kwargs):
        user = request.user
        resort = get_resort_for_user(user)

        # Check if the user requesting the impersonate is manager (or) not.
        if not user_has_permission(user, resort, 3):
            return Response(
                {
                    _('detail'):
                    _('you do not have permission to impersonate this user')
                },
                status=400)

        # check for validity of the UUID of the user
        if not uuid(kwargs['user_id']):
            return Response({_('detail'): _('not a valid UUID')}, status=400)

        device_id = request.query_params.get('device_id')
        if device_id is None:
            return Response({_('detail'): _('device_id not provided')},
                            status=400)

        try:
            impersonate_user = get_user_model().objects.get(
                user_id=kwargs['user_id'])
            impersonate_user_resort = get_resort_for_user(impersonate_user)

            if impersonate_user_resort != resort:
                return Response(
                    {_('detail'): _('user is not allowed to impersonate')},
                    status=400)
        except:
            return Response({_('detail'): _('user not found')}, status=400)

        try:
            device = Devices.objects.get(device_id=device_id)
        except:
            return Response(
                {
                    _('detail'):
                    _('device with provided device_id does not exists')
                },
                status=400)

        try:
            Heartbeat.objects.get(user=impersonate_user, device=device)
        except:
            heartbeat = Heartbeat(user=impersonate_user, device=device)
            heartbeat.save()

        response_data = {}
        resort_data = get_user_resort_combo(
            impersonate_user.user_pk,
            ('resort_id', 'resort_name', 'map_kml', 'map_type', 'report_form',
             'unit_format', 'timezone', 'map_lat', 'map_lng',
             'datetime_format', 'season_start_date', 'dispatch_field_choice'),
            ('user_id', 'name', 'email', 'phone'))
        response_data.update(resort_data)
        response_data.update({'devices': get_devices_user(impersonate_user)})
        response_data.update({'token': get_token(impersonate_user)})

        return Response(response_data, status=200)