コード例 #1
0
    def update(self, request, pk=None, *args, **kwargs):
        response = None
        success = False

        branch_count = Branch.objects.filter(
            name__iexact=request.data['name']).count()
        if branch_count == 0:
            if pk:
                try:
                    branch = Branch.objects.get(pk=pk)
                    if hasattr(request.data, '_mutable'):
                        request.data._mutable = True

                    request.data['account'] = request.user.account.pk
                    request.data['branch_alias'] = request.data['name']

                    if request.user.user_type == User.ADMIN:
                        return super().update(request, pk, *args, **kwargs)
                except:
                    response = JsonResponse(
                        {'message': 'Branch does not exist',
                         'success': success})
                    response.status = status.HTTP_400_BAD_REQUEST
        else:
            response = JsonResponse(
                {'message': 'Branch name already exits!',
                 'success': success})

            response.status = status.HTTP_400_BAD_REQUEST

        return response
コード例 #2
0
ファイル: branch_schedule.py プロジェクト: rowegie/basev2
    def retrieve(self, request, pk=None):
        success = False
        response = None
        if pk:
            if request.user.user_type == User.ADMIN:
                try:
                    schedule_filter = Q(pk=pk) & Q(status='OPEN') & Q(
                        deleted__isnull=True)
                    queryset = BranchSchedule.objects.get(schedule_filter)
                    serializer = BranchScheduleSerializer(queryset).data
                    branches = json.dumps(serializer)
                    success = True
                    response = JsonResponse({
                        'data': json.loads(branches),
                        'success': success
                    })
                    response.status = status.HTTP_200_OK
                except Exception as e:
                    pp.pprint(e)
        else:
            response = JsonResponse({
                'message': 'Invalid Request',
                'success': success
            })
            response.status = status.HTTP_400_BAD_REQUEST

        return response
コード例 #3
0
    def create(self, request, *args, **kwargs):
        success = False
        response = None

        name_count = Branch.objects.filter(
            name__iexact=request.data['name']).count()

        if name_count == 0:
            if hasattr(request.data, '_mutable'):
                request.data._mutable = True

            request.data['account'] = request.user.account.pk
            request.data['branch_alias'] = request.data['name']

            if request.user.user_type == User.ADMIN:
                serializer = BranchSerializer(data=request.data)
                serializer.is_valid(raise_exception=True)
                self.perform_create(serializer)
                success = True
                response = JsonResponse(
                    {'data': serializer.data,
                     'success': success})
                response.status = status.HTTP_201_CREATED
        else:
            response = JsonResponse(
                {'message': 'Branch name already exits!',
                 'success': success})
            response.status = status.HTTP_400_BAD_REQUEST

        return response
コード例 #4
0
    def retrieve(self, request, pk=None):
        success = False
        response = None
        if pk:
            if request.user.user_type == User.ADMIN:
                try:
                    branch_filter = Q(pk=pk) & Q(deleted__isnull=True) & Q(
                        account=self.request.user.account)
                    queryset = Branch.objects.get(branch_filter)
                    serializer = BranchSerializer(queryset).data
                    branches = json.dumps(serializer)
                    success = True
                    response = JsonResponse(
                        {'data': json.loads(branches), 'success': success})
                    response.status = status.HTTP_200_OK
                except:
                    response = (
                        {'detail': 'Branch does not exist',
                         'success': success})
                    response.status = status.HTTP_400_BAD_REQUEST
        else:
            response = ({'detail': 'Invalid Request',
                         'success': success})
            response.status = status.HTTP_400_BAD_REQUEST

        return response
コード例 #5
0
    def update(self, request, pk=None):
        response = None
        success = False
        msg = ''

        if request.user.is_authenticated():
            try:
                user = User.objects.get(pk=pk)
                user.email = request.data['email']
                user.phone_number = request.data['phone_number']
                user.user_type = request.data['user_type']
                if ('password' in request.data):
                    user.set_password(request.data['password'])
                user.save()
                msg = 'User successfully updated!'

                response = JsonResponse({
                    'success': success,
                    'detail': msg,
                    'data': UserSerializer(user).data
                })
                response.status = status.HTTP_200_OK

            except User.DoesNotExist:
                msg = 'User does not exist!'
                response = JsonResponse({'success': success, 'detail': msg})
                response.status = status.HTTP_400_BAD_REQUEST
        else:
            msg = 'Not Authorized!'
            response = JsonResponse({'success': success, 'detail': msg}),
            response.status = status.HTTP_401_UNAUTHORIZED

        return response
コード例 #6
0
    def create(self, request):
        success = False
        response = None

        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                form.cleaned_data['email'],
                password=form.cleaned_data['password'],
                phone_number=form.cleaned_data['phone_number'],
                user_type=request.data['user_type'])
            # user.phone_number =
            # email side
            password = form.cleaned_data['password']
            user.set_password(password)
            success = True
            user.save()
            response = JsonResponse({
                'success': success,
                'detail': 'User successfully created'
            })
            response.status = status.HTTP_201_CREATED
        else:
            response = JsonResponse({
                'success': success,
                'detail': form.errors
            })
            response.status = status.HTTP_400_BAD_REQUEST

        return response
コード例 #7
0
ファイル: branch_schedule.py プロジェクト: rowegie/basev2
    def destroy(self, request, pk=None):
        success = False
        response = None

        try:
            branch = Branch.objects.get(pk=request.GET['branch'])
        except Branch.DoesNotExist:
            response = JsonResponse({
                'success': success,
                'detail': 'Invalid Branch'
            })
            response.status = status.HTTP_400_BAD_REQUEST

        if branch:
            try:
                branch_schedule = BranchSchedule.objects.get(pk=pk,
                                                             branch=branch)
                branch_schedule.delete()
                success = True
                response = JsonResponse({
                    'success':
                    True,
                    'message':
                    'Schedule successfully deleted'
                })
                response.status = status.HTTP_200_OK
            except BranchSchedule.DoesNotExist:
                response = JsonResponse({
                    'detail': 'Schedule does not exist',
                    'success': success
                })
                response.status = status.HTTP_400_BAD_REQUEST

        return response
コード例 #8
0
    def destroy(self, request, pk=None):
        response = None
        success = False
        if request.user.is_authenticated():
            try:
                user = User.objects.get(pk=pk)
                user.delete()
                success = True
                response = JsonResponse({
                    'success': success,
                    'message': 'User successfully deleted'
                })
                response.status = status.HTTP_200_OK

            except User.DoesNotExist:
                response = JsonResponse({
                    'success': success,
                    'detail': 'User does not exist'
                })
                response.status = status.HTTP_400_BAD_REQUEST
        else:
            response = JsonResponse({'detail': 'UInvalid Request'})
            response.status = status.HTTP_401_UNAUTHORIZED

        return response
コード例 #9
0
ファイル: user.py プロジェクト: xKxAxKx/twitter_clone
 def put(self, request, *args, **kwargs):
     serializer = self.serializer_class(self.get_object(),
                                        data=request.data,
                                        partial=True)
     if serializer.is_valid():
         instance = serializer.save()
         payload = jwt_payload_handler(instance)
         token = jwt.encode(payload, settings.SECRET_KEY) \
                    .decode('unicode_escape')
         response = JsonResponse({'token': token})
         response.status = 200
         return response
     else:
         response = JsonResponse({'errors': serializer.errors})
         response.status = 500
         return response
コード例 #10
0
 def put(self, request):
     form = JobCompletedForm(request.POST)
     if not form.is_valid():
         resp = JsonResponse(form.errors.as_json())
         resp.status = 400
         return resp
     form.save()
     return JsonResponse()
コード例 #11
0
    def list(self, request):
        success = False
        response = None
        try:
            if request.user.user_type == User.ADMIN:
                branch_filter = Q(deleted__isnull=True) & Q(
                    account=self.request.user.account)
                queryset = Branch.objects.filter(branch_filter).all()
                serializer = BranchSerializer(queryset, many=True)
                branches = json.dumps(serializer.data)
                success = True
                response = JsonResponse(
                    {'data': json.loads(branches), 'success': success})
                response.status = status.HTTP_200_OK
        except:
            response = JsonResponse(
                {'success': success, 'detail': 'Invalid Request'})
            response.status = status.HTTP_401_UNAUTHORIZED

        return response
コード例 #12
0
ファイル: branch_schedule.py プロジェクト: rowegie/basev2
 def list(self, request, *args, **kwargs):
     response = None
     queryset = self.get_queryset()
     serializer = BranchScheduleSerializer(queryset, many=True).data
     branch_schedules = json.dumps(serializer)
     response = JsonResponse({
         'data': json.loads(branch_schedules),
         'success': True
     })
     response.status = status.HTTP_200_OK
     return response
コード例 #13
0
def handle403(request):
    if "application/json" in request.META["CONTENT_TYPE"] or \
       "application/x-www-form-urlencoded" in request.META["CONTENT_TYPE"] or\
       "multipart/form-data" in request.META["CONTENT_TYPE"]:
        resp_body = {"mid": request.path_info, "msg": "Authentication Failed"}
        resp = JsonResponse(resp_body, status=403)
    else:
        url_param = urllib.urlencode(
            {"redirect_after_login": request.META["REQUEST_URI"]})
        resp = HttpResponseRedirect("/auth/login-page/?%s" % url_param)
        resp.status = 403
    return resp
コード例 #14
0
ファイル: branch_schedule.py プロジェクト: rowegie/basev2
    def update(self, request, pk=None, *args, **kwargs):
        response = None
        success = False

        if pk:
            try:
                branch = Branch.objects.get(pk=request.data['branch'])
                branch_schedule = BranchSchedule.objects.get(pk=pk,
                                                             branch=branch)
                serializer = BranchScheduleSerializer(branch_schedule,
                                                      data=request.data)
                if serializer.is_valid():
                    serializer.save()
                    queryset = BranchScheduleSerializer(branch_schedule).data
                    branch_schedules = json.dumps(queryset)
                    response = JsonResponse({
                        'data':
                        json.loads(branch_schedules),
                        'success':
                        success
                    })
                    response.status = status.HTTP_200_OK

            except BranchSchedule.DoesNotExist:
                response = JsonResponse({
                    'detail': 'Schedule does not exist',
                    'success': success
                })
                response.status = status.HTTP_400_BAD_REQUEST
        else:
            response = JsonResponse({
                'detail': 'Invalid Request',
                'success': success
            })

            response.status = status.HTTP_400_BAD_REQUEST

        return response
コード例 #15
0
    def list(self, request):
        response = None
        success = False

        if request.user.is_authenticated():
            user_filter = Q(is_admin=False) & Q(deleted__isnull=True)
            queryset = User.objects.all().filter(user_filter)
            serializer = UserSerializer(queryset, many=True)
            success = True
            response = JsonResponse(
                {
                    'data': serializer.data,
                    'success': success
                }, safe=False)
            response.status = status.HTTP_200_OK
        else:
            response = JsonResponse({
                'message': 'Invalid Request',
                'success': False
            })
            response.status = status.HTTP_401_UNAUTHORIZED

        return response
コード例 #16
0
    def retrieve(self, request, pk=None):
        success = False

        if request.user.is_authenticated():
            try:
                user = User.objects.filter(is_admin=False).get(pk=pk)
                user = UserSerializer(user).data
                success = True
                response = JsonResponse({'success': success, 'data': user})
                response.status = status.HTTP_200_OK
            except User.DoesNotExist:
                response = JsonResponse({
                    'success': success,
                    'detail': 'User does not exist'
                })
                response.status = status.HTTP_400_BAD_REQUEST
        else:
            response = JsonResponse({
                'success': success,
                'detail': 'Not Authorized'
            })
            response.status = status.HTTP_401_UNAUTHORIZED

        return response
コード例 #17
0
    def destroy(self, request, pk=None):
        success = False
        response = None
        if pk:
            if request.user.user_type == User.ADMIN:
                branch = Branch.objects.get(pk=pk)
                branch.delete()
                success = True
                response = JsonResponse(
                    {'success': success,
                     'message': 'Branch successfully deleted'})
                response.status = status.HTTP_200_OK
            else:
                response = JsonResponse(
                    {'success': success,
                     'message': 'Not allowed to delete branch'})
                response.status = status.HTTP_401_UNAUTHORIZED
        else:
            response = JsonResponse(
                {'success': success,
                 'message': 'Invalid request'})
            response.status = status.HTTP_400_BAD_REQUEST

        return response
コード例 #18
0
ファイル: branch_schedule.py プロジェクト: rowegie/basev2
    def get_queryset(self):

        success = False
        date_from = None
        date_to = None
        branch_schedules = None
        response = None

        branch_schedules_filter = BranchSchedule.objects

        if self.request.method == 'GET':
            branches = None
            if 'from' in self.request.GET and 'to' in self.request.GET:
                start = self.request.GET['from']
                end = self.request.GET['to']
                date_from = datetime.strptime(start,
                                              '%Y-%m-%d').replace(hour=0,
                                                                  minute=0,
                                                                  second=0)
                date_to = datetime.strptime(end, '%Y-%m-%d')
                date_to = date_to.replace(hour=23,
                                          minute=59,
                                          second=59,
                                          microsecond=999)

            if 'branch' in self.request.GET:
                try:
                    branches = Branch.objects.get(
                        pk=self.request.GET['branch'])
                except Branch.DoesNotExist:
                    response = JsonResponse({
                        'detail': 'Invalid Branch',
                        'success': success
                    })
                    response.status = status.HTTP_400_BAD_REQUEST
                    return response

            if branches:
                branch_schedules = branch_schedules_filter.filter(
                    Q(branch=branches)).all()
            else:
                branch_schedules = branch_schedules_filter.all()

            if date_from and date_to:
                branch_schedules = branch_schedules_filter.filter(
                    date__range=[date_from, date_to])

            return branch_schedules.all().order_by('date')
コード例 #19
0
    def put(self, request, *args, **kwargs):
        serializer = self.serializer_class(self.get_object(),
                                           data=request.data,
                                           partial=True)

        if serializer.is_valid():
            instance = serializer.save()
            # Generate a new token
            payload = jwt_payload_handler(instance)
            token = jwt.encode(payload, site_config.SECRET_KEY)
            response = JsonResponse({'token': token.decode('unicode_escape')})
            response.status = 200
            return response
        else:
            response = Response(serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
            return response
コード例 #20
0
ファイル: branch_schedule.py プロジェクト: rowegie/basev2
    def create(self, request):
        success = False
        response = None
        # b'{"day":"tue","date":"2017-07-11","status":"OPEN","start":"17:00:00","end":"20:30:00","branch":40}'
        req_field = ['day', 'status', 'start', 'end', 'date', 'branch']
        if (all(field in request.data for field in req_field)):
            date = datetime.strptime(request.data['date'],
                                     '%Y-%m-%d').replace(hour=0,
                                                         minute=0,
                                                         second=0)
            start_time = datetime.strptime(request.data['start'],
                                           '%H:%M:%S').time()
            end_time = datetime.strptime(request.data['end'],
                                         '%H:%M:%S').time()

            # pp.pprint(str(date))
            # branch = Branch.objects.get(pk=request.data['branch'])
            # data = BranchSerializer(branch).data
            date = date.astimezone(pytz.utc)
            try:
                branch = Branch.objects.get(pk=request.data['branch'])
                branch_filter = Q(branch=branch) & Q(date=date) & Q(
                    deleted__isnull=True)
                branch_query = BranchSchedule.objects.filter(
                    branch_filter).count()

                if branch_query == 0:
                    branch_schedule = BranchSchedule()
                    branch_schedule.date = date
                    branch_schedule.day = request.data['day']
                    branch_schedule.start = start_time
                    branch_schedule.end = end_time
                    branch_schedule.status = request.data['status']
                    # branch_schedule.account = request.account
                    branch_schedule.branch = branch
                    success = True
                    branch_schedule.save()
                    serializer = BranchScheduleSerializer(branch_schedule).data
                    branch_schedules = json.dumps(serializer)
                    response = JsonResponse({
                        'data':
                        json.loads(branch_schedules),
                        'success':
                        success
                    })
                    response.status = status.HTTP_201_CREATED
                else:
                    response = JsonResponse({
                        'success': success,
                        'detail': 'Schedule already exists'
                    })
                    response.status = status.HTTP_400_BAD_REQUEST

            except Branch.DoesNotExist:
                response = JsonResponse({
                    'detail': 'Invalid Branch',
                    'success': success
                })
                response.status = status.HTTP_400_BAD_REQUEST
        else:
            response = JsonResponse({
                'message': 'Invalid Request',
                'success': success
            })
            response.status = status.HTTP_400_BAD_REQUEST

        return response