Exemplo n.º 1
0
 def my_retrieve(self, request, station_id, pk):
     self.serializer_context = {}
     form = Form.current_form(self.get_form_type_name(), station_id)
     if form is None:
         return Response(status=status.HTTP_404_NOT_FOUND)
     try:
         the_form = FormData.find_object_by_id(pk, form)
         if the_form is None:
             return Response(status=status.HTTP_404_NOT_FOUND)
     except ObjectDoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
     
     
     if hasattr(the_form, 'station'):
         station = the_form.station
     else:
         station = BorderStation.objects.get(id=pk)
         
     read_access = UserLocationPermission.has_session_permission(request, self.get_perm_group_name(), 'VIEW', station.operating_country.id, station.id)
     edit_access = UserLocationPermission.has_session_permission(request, self.get_perm_group_name(), 'EDIT', station.operating_country.id, station.id)
     private_access = UserLocationPermission.has_session_permission(request, self.get_perm_group_name(), 'VIEW PI', station.operating_country.id, station.id)
     
     if not read_access:
         return Response(status=status.HTTP_401_UNAUTHORIZED)
             
     if not edit_access and not private_access:
         self.serializer_context['mask_private'] = True
         
     form_data = FormData(the_form, form)
     serializer = FormDataSerializer(form_data, context=self.serializer_context)
     
     resp_data = serializer.data
    
     return Response(resp_data)
Exemplo n.º 2
0
 def update_permissions(self, request, pk):
     data = JSONParser().parse(request)
     if 'permission_id' in data:
         permission_id = int(data['permission_id'])
     elif 'permission_group' in data:
         permission_group = data['permission_group']
         permission_id = None
     else:
         permission_group = None
         permission_id = None
     
     user_permissions = UserLocationPermission.objects.filter(account__id = request.user.id)
         
     permission_list = data['permissions']
     new_permissions = []
     for perm_data in permission_list:
         serializer = UserLocationPermissionSerializer(data=perm_data)
         if serializer.is_valid():
             perm_obj = serializer.create_local()
             new_permissions.append(perm_obj)
     
     issues = UserLocationPermission.check_valid_permission_set(pk, new_permissions, permission_id, permission_group)
     if len(issues) > 0:
         code = status.HTTP_500_INTERNAL_SERVER_ERROR
     else:
         code = UserLocationPermission.update_permission_set (pk, new_permissions, permission_id, permission_group, user_permissions)
         if code == status.HTTP_200_OK:
             self.update_account_permission(pk)
         
     return Response({"data": data}, code)
Exemplo n.º 3
0
 def has_permission(self, account_id, action, country_id):
     perm_list = UserLocationPermission.objects.filter(
         account__id=account_id,
         permission__permission_group='AUDIT',
         permission__action=action)
     return UserLocationPermission.has_permission_in_list(
         perm_list, 'AUDIT', action, country_id, None)
Exemplo n.º 4
0
    def get_queryset(self):
        countries = Country.objects.all()
        include_countries = []
        country = self.request.GET.get('country')
        perm_list = UserLocationPermission.objects.filter(
            account__id=self.request.user.id,
            permission__permission_group='AUDIT',
            permission__action='VIEW')
        for country_entry in countries:
            if country is not None and int(country) != country_entry.id:
                continue
            if UserLocationPermission.has_permission_in_list(
                    perm_list, 'AUDIT', 'VIEW', country_entry.id, None):
                include_countries.append(country_entry)

        queryset = Audit.objects.filter(country__in=include_countries)

        form_type = self.request.GET.get('form_type')
        if country is not None:
            queryset = queryset.filter(country__id=country)
        if form_type is not None:
            forms = Form.objects.filter(form_type__id=form_type)
            form_names = []
            for form in forms:
                form_names.append(form.form_name)
            queryset = queryset.filter(form_name__in=form_names)
        return queryset
Exemplo n.º 5
0
    def add_permission(user, permission_configuration):
        for config in permission_configuration:
            perm = Permission.objects.get(permission_group=config['group'],
                                          action=config['action'])

            ulp = UserLocationPermission()
            ulp.account = user
            ulp.permission = perm
            ulp.country = config['country']
            ulp.station = config['station']
            ulp.save()
Exemplo n.º 6
0
 def create(permission_configuration):
     user = GenericUser.create()
     for config in permission_configuration:
         perm = Permission.objects.get(permission_group=config['group'], action=config['action'])
         
         ulp = UserLocationPermission()
         ulp.account = user
         ulp.permission = perm
         ulp.country = config['country']
         ulp.station = config['station']
         ulp.save()
     
     return user
Exemplo n.º 7
0
    def update_permissions(self, request, pk):
        data = JSONParser().parse(request)
        if 'permission_id' in data:
            permission_id = int(data['permission_id'])
        elif 'permission_group' in data:
            permission_group = data['permission_group']
            permission_id = None
        else:
            permission_group = None
            permission_id = None

        user_permissions = UserLocationPermission.objects.filter(
            account__id=request.user.id,
            permission__permission_group='ACCOUNTS',
            permission__action='MANAGE')

        permission_list = data['permissions']
        new_permissions = []
        for perm_data in permission_list:
            serializer = UserLocationPermissionSerializer(data=perm_data)
            if serializer.is_valid():
                perm_obj = serializer.create_local()
                new_permissions.append(perm_obj)

        issues = UserLocationPermission.check_valid_permission_set(
            pk, new_permissions, permission_id, permission_group)
        if len(issues) > 0:
            return_data = {'error_text': issues[0]}
            code = status.HTTP_500_INTERNAL_SERVER_ERROR
        else:
            result = UserLocationPermission.update_permission_set(
                pk, new_permissions, permission_id, permission_group,
                user_permissions)
            code = result['code']
            if code == status.HTTP_200_OK:
                self.update_account_permission(pk)
                return_data = data
            else:
                return_data = {'error_text': result['error']}

        return Response(return_data, code)
Exemplo n.º 8
0
    def create_local(self):
        perm = UserLocationPermission()
        perm.account = self.validated_data.get('account')
        perm.country = self.validated_data.get('country')
        perm.station = self.validated_data.get('station')
        perm.permission = self.validated_data.get('permission')

        return perm
Exemplo n.º 9
0
 def destroy(self, request, station_id, pk):
     form = Form.current_form(self.get_form_type_name(), station_id)
     try:
         the_form = FormData.find_object_by_id(pk, form)
     except ObjectDoesNotExist:
         return Response({'errors' : [self.get_form_type_name() + " not found"], 'warnings':[]}, status=status.HTTP_404_NOT_FOUND)
     
     if not UserLocationPermission.has_session_permission(request, self.get_perm_group_name(), 'DELETE',
             the_form.station.operating_country.id, the_form.station.id):
         return Response(status=status.HTTP_401_UNAUTHORIZED)
     form_data = FormData(the_form, form)
     form_data.delete()
     form_done.send_robust(sender=self.__class__, form_data=form_data, remove=True)
     return Response(status=status.HTTP_200_OK)
Exemplo n.º 10
0
 def setUp(self):
     IntercepteeFactory.create_batch(20)
     self.user = SuperUserFactory.create()
     self.client.force_authenticate(user=self.user)
     ulp = UserLocationPermission()
     ulp.account = self.user
     ulp.permission = Permission.objects.get(permission_group='IRF',
                                             action='VIEW')
     ulp.save()
Exemplo n.º 11
0
 def retrieve_blank_form(self, request, station_id):
     self.serializer_context = {}
     form = Form.current_form(self.get_form_type_name(), station_id)
     if form is None:
         return Response(status=status.HTTP_404_NOT_FOUND)
     form_class = FormData.get_form_class(form)
     the_form = form_class()
     if station_id is not None:
         station = BorderStation.objects.get(id=station_id)
         the_form.station = station
         add_access = UserLocationPermission.has_session_permission(request, self.get_perm_group_name(), 'ADD', 
                 the_form.station.operating_country.id, the_form.station.id)
         if not add_access:
             return Response(status=status.HTTP_401_UNAUTHORIZED)
         if station.auto_number is not None and station.auto_number == form.form_type.name:
             the_number = AutoNumber.get_next_number(station, form)
             setattr(the_form, form_class.key_field_name(), the_number)
     
     form_data = FormData(the_form, form)
     serializer = FormDataSerializer(form_data, context=self.serializer_context)
     return Response(serializer.data)
Exemplo n.º 12
0
    def custom_has_object_permission(self, request, view, method,
                                     permissions_required, obj):
        if request.method == method or method == "ANY":
            # Need to have a way to access the country id and border station id from the object
            # Assume each model will implement property get methods for country_id and border_station_id
            get_country_id = getattr(obj, 'get_country_id', None)
            if get_country_id is not None and callable(get_country_id):
                country_id = obj.get_country_id()
            else:
                country_id = None
            get_station_id = getattr(obj, 'get_border_station_id', None)
            if get_station_id is not None and callable(get_station_id):
                station_id = obj.get_border_station_id()
            else:
                station_id = None

            for permission in permissions_required:
                if not UserLocationPermission.has_session_permission(
                        request, permission['permission_group'],
                        permission['action'], country_id, station_id):
                    self.message = self.message.format(permission)
                    return False

        return True
Exemplo n.º 13
0
 def create(self, request):
     form_type = FormType.objects.get(name=self.get_form_type_name())
     request_json = self.extract_data(request, self.get_element_paths())
     self.serializer_context = {'form_type':form_type, 'request.user':request.user}
     self.pre_process(request, None)
     transaction.set_autocommit(False)
     try:
         serializer = FormDataSerializer(data=request_json, context=self.serializer_context)
         if serializer.is_valid():
             if not UserLocationPermission.has_session_permission(request, self.get_perm_group_name(), 'ADD',
                     serializer.get_country_id(), serializer.get_station_id()):
                 transaction.rollback()
                 transaction.set_autocommit(True)
                 return Response(status=status.HTTP_401_UNAUTHORIZED)
             try:
                 form_data = serializer.save()
                 if self.check_form_number(form_data):
                     self.logbook_submit(form_data)
                     serializer2 = FormDataSerializer(form_data, context=self.serializer_context)
                     form_done.send_robust(sender=self.__class__, form_data=form_data)
                     ret = serializer2.data
                     rtn_status = status.HTTP_200_OK
                     transaction.commit()
                     transaction.set_autocommit(True)
                     self.post_process(request, form_data)
                 else:
                     transaction.rollback()
                     transaction.set_autocommit(True)
                     ret = {
                         'errors':['Form number exceeds highest number allocated for station'],
                         'warnings':[]
                         }
                     rtn_status=status.HTTP_400_BAD_REQUEST
             except IntegrityError as exc:
                 transaction.rollback()
                 transaction.set_autocommit(True)
                 if 'unique constraint' in exc.args[0]:
                     ret = {
                         'errors': [ exc.args[0] ],
                         'warnings':[]
                     }
                     rtn_status=status.HTTP_400_BAD_REQUEST
                 else:
                     ret = {
                         'errors': 'Internal Error:' + traceback.format_exc(),
                         'warnings':[]
                     }
                     rtn_status=status.HTTP_400_BAD_REQUEST
         else:
             transaction.rollback()
             transaction.set_autocommit(True)
             ret = {
                 'errors': serializer.the_errors,
                 'warnings':serializer.the_warnings
                 }
             rtn_status=status.HTTP_400_BAD_REQUEST
     except Exception:
         transaction.rollback()
         transaction.set_autocommit(True)
         ret = {
                 'errors': 'Internal Error:' + traceback.format_exc(),
                 'warnings':[]
             }
         rtn_status = status.HTTP_500_INTERNAL_SERVER_ERROR
     
     return Response (ret, status=rtn_status)
Exemplo n.º 14
0
 def get_can_delete(self, obj):
     perm_list = self.context.get('perm_list')
     return UserLocationPermission.has_permission_in_list(
         perm_list, self.perm_group_name, 'DELETE',
         obj.station.operating_country.id, obj.station.id)
Exemplo n.º 15
0
 def get_can_edit(self, obj):
     perm_list = self.context.get('perm_list')
     ret = UserLocationPermission.has_permission_in_list(
         perm_list, self.perm_group_name, 'EDIT',
         obj.station.operating_country.id, obj.station.id)
     return ret
    def setUp(self):
        user = SuperUserFactory.create()
        self.client = APIClient()
        self.client.force_authenticate(user=user)

        self.globalCount += 1
        self.nepal = self.get_or_create_country('Nepal')
        self.south_africa = self.get_or_create_country('South Africa')
        self.thailand = self.get_or_create_country('Thailand')

        self.nepal_bs1 = self.get_or_create_station("nepal1", "NP1",
                                                    self.nepal)
        self.nepal_bs2 = self.get_or_create_station("nepal2", "NP2",
                                                    self.nepal)
        self.nepal_bs3 = self.get_or_create_station("nepal3", "NP3",
                                                    self.nepal)
        self.south_africa_bs = self.nepal_bs3 = self.get_or_create_station(
            "sa", "SA1", self.south_africa)
        self.thailand_bs = self.nepal_bs3 = self.get_or_create_station(
            "thai", "TL1", self.thailand)

        self.account = SuperUserFactory.create()

        self.permissions = []

        tmp = UserLocationPermission()
        tmp.account = self.account
        tmp.country = None
        tmp.station = None
        tmp.permission = Permission.objects.get(permission_group='IRF',
                                                action='VIEW')
        tmp.save()
        self.permissions.append(tmp)

        tmp = UserLocationPermission()
        tmp.account = self.account
        tmp.country = None
        tmp.station = self.nepal_bs2
        tmp.permission = Permission.objects.get(permission_group='IRF',
                                                action='ADD')
        tmp.save()
        self.permissions.append(tmp)

        tmp = UserLocationPermission()
        tmp.account = self.account
        tmp.country = None
        tmp.station = self.thailand_bs
        tmp.permission = Permission.objects.get(permission_group='IRF',
                                                action='ADD')
        tmp.save()
        self.permissions.append(tmp)

        tmp = UserLocationPermission()
        tmp.account = self.account
        tmp.country = None
        tmp.station = self.nepal_bs2
        tmp.permission = Permission.objects.get(permission_group='IRF',
                                                action='EDIT')
        tmp.save()
        self.permissions.append(tmp)

        tmp = UserLocationPermission()
        tmp.account = self.account
        tmp.country = None
        tmp.station = self.thailand_bs
        tmp.permission = Permission.objects.get(permission_group='IRF',
                                                action='EDIT')
        tmp.save()
        self.permissions.append(tmp)

        tmp = UserLocationPermission()
        tmp.account = self.account
        tmp.country = self.nepal
        tmp.station = None
        tmp.permission = Permission.objects.get(permission_group='VIF',
                                                action='VIEW')
        tmp.save()
        self.permissions.append(tmp)

        tmp = UserLocationPermission()
        tmp.account = self.account
        tmp.country = self.nepal
        tmp.station = None
        tmp.permission = Permission.objects.get(permission_group='VIF',
                                                action='ADD')
        tmp.save()
        self.permissions.append(tmp)

        tmp = UserLocationPermission()
        tmp.account = self.account
        tmp.country = self.nepal
        tmp.station = None
        tmp.permission = Permission.objects.get(permission_group='VIF',
                                                action='EDIT')
        tmp.save()
        self.permissions.append(tmp)
Exemplo n.º 17
0
    def update(self, request, station_id, pk):
        form = Form.current_form(self.get_form_type_name(), station_id)
        the_form = FormData.find_object_by_id(pk, form)
        if the_form is None:
            return Response({'errors' : [self.get_form_type_name() + " not found"], 'warnings':[]}, status=status.HTTP_404_NOT_FOUND)
        form_data = FormData(the_form, form)
        self.pre_process(request, form_data)
        request_json = self.extract_data(request, self.get_element_paths())

        self.serializer_context = {'form_type':form.form_type, 'request.user':request.user}
        transaction.set_autocommit(False)
        try:
            serializer = FormDataSerializer(form_data, data=request_json, context=self.serializer_context)
            if serializer.is_valid():
                if not UserLocationPermission.has_session_permission(request, self.get_perm_group_name(), 'EDIT',
                        serializer.get_country_id(), serializer.get_station_id()):
                    return Response(status=status.HTTP_401_UNAUTHORIZED)
                form_data = serializer.save()
                if self.check_form_number(form_data):
                    self.logbook_submit(form_data)
                    serializer2 = FormDataSerializer(form_data, context=self.serializer_context)
                    form_done.send_robust(sender=self.__class__, form_data=form_data)
                    rtn_status = status.HTTP_200_OK
                    ret = serializer2.data
                    transaction.commit()
                    transaction.set_autocommit(True)
                    self.post_process(request, form_data)
                else:
                    transaction.rollback()
                    transaction.set_autocommit(True)
                    ret = {
                        'errors':['Form number exceeds highest number allocated for station'],
                        'warnings':[]
                        }
                    rtn_status=status.HTTP_400_BAD_REQUEST
            else:
                transaction.rollback()
                transaction.set_autocommit(True)
                if serializer.the_errors is not None and len(serializer.the_errors) > 0:
                    rtn_errors = serializer.the_errors
                else:
                    rtn_errors = []
                    
                if serializer.the_warnings is not None and len(serializer.the_warnings) > 0:
                    rtn_warnings = serializer.the_warnings
                else:
                    rtn_warnings = []
                
                if len(rtn_errors) < 1 and len(rtn_warnings) < 1:
                    rtn_errors = serializer._errors
                ret = {
                    'errors': rtn_errors,
                    'warnings':rtn_warnings
                    }
                rtn_status = status.HTTP_400_BAD_REQUEST
        except Exception:
            transaction.rollback()
            transaction.set_autocommit(True)
            ret = {
                'errors': 'Internal Error:' + traceback.format_exc(),
                'warnings':[]
                }
            rtn_status = status.HTTP_500_INTERNAL_SERVER_ERROR
            
        return Response (ret, status=rtn_status)
Exemplo n.º 18
0
 def get_queryset(self):
     if self.action != 'list':
         return None
     in_country = self.request.GET.get('country_ids')
     status = self.request.GET.get('status', 'approved')
     search = self.request.GET.get('search')
     
     status_list = []
     in_progress=False
     for stat in status.split(','):
         # Earlier feature to only allow author to view in-progress forms
         # has been disabled
         #if stat == 'in-progress':
         #    in_progress = True
         #else:
         #    status_list.append(stat)
         status_list.append(stat)
             
     countries = Country.objects.all()
     all_country_list = []
     for country in countries:
         all_country_list.append(country.id)
     
     country_list = []
     if in_country is not None and in_country != '':
         # client provided a list of countries to consider
         for cntry in in_country.split(','):
             country_list.append(int(cntry))
     else:
         # client did not provide a list - so consider all countries
        country_list = all_country_list
     
     account_id = self.request.user.id
     
     station_list = []
     form_storage_list = []
     tmp_station_list = BorderStation.objects.filter(operating_country__in=country_list)
     perm_list = UserLocationPermission.objects.filter(account__id=account_id, permission__permission_group=self.get_perm_group_name()).exclude(permission__action='ADD')
     self.serializer_context = {'perm_list':perm_list}
     for station in tmp_station_list:
         if (UserLocationPermission.has_permission_in_list(perm_list, self.get_perm_group_name(), None, station.operating_country.id, station.id)):
             station_list.append(station)
             form = Form.current_form(self.get_form_type_name(), station.id)
             if form is not None and form.storage not in form_storage_list:
                 form_storage_list.append(form.storage)
     
     q_filter = self.build_query_filter(status_list, station_list, in_progress, account_id)
     queryset = None
     for form_storage in form_storage_list:
         mod = __import__(form_storage.module_name, fromlist=[form_storage.form_model_name])
         form_model = getattr(mod, form_storage.form_model_name)
         
         tmp_queryset = form_model.objects.filter(q_filter).only(*self.get_list_field_names())      
         if search is not None:
             tmp_queryset = self.filter_key(tmp_queryset, search)
         
         if queryset is None:
             queryset = tmp_queryset
         else:
             queryset = queryset.union(tmp_queryset)
         
     if queryset is None:
         queryset = self.get_empty_queryset()
             
     return queryset