def respond_with_user(self, request, user_id): return JsonResponse( self._get_objs( annotate( self.get_queryset(request).filter(pk=user_id), request), request=request, )[0])
def login(self, request): data = jsonloads(request.body) username = data.get('username', '').lower() password = data.get('password', '') if request.method != 'POST': raise BinderMethodNotAllowed() user = auth.authenticate(username=username, password=password) if user is None: raise BinderNotAuthenticated() auth.login(request, user) return JsonResponse(UserView()._get_obj(user.id, request=request))
def get_aggregate(self, request): start_date = parse_date(request.GET.get('start_date')) end_date = parse_date(request.GET.get('end_date')) # Django doesn't have a decent query builder, # so we first get the aggregate for each category qs = self.get_queryset(request).order_by('id').filter(user=request.user) \ .annotate(sum_amount=Subquery( Transaction.objects.order_by().filter( category=OuterRef('pk'), date__range=(start_date, end_date) ).values('category_id') .annotate(sum_amount=Sum('amount')).values('sum_amount'), output_field=IntegerField() ) ).values('id', 'name', 'color', 'sum_amount') res = list(qs.all()) # And then we get the aggregate for transactions without category sum_category_null = TransactionView().get_queryset(request).order_by( ).filter( user=request.user, category__isnull=True, date__range=(start_date, end_date)).values('category_id').annotate( sum_amount=Sum('amount')).values('sum_amount').all() sum_amount = 0 if len(sum_category_null): sum_amount = sum_category_null[0]['sum_amount'] res.append({ 'id': None, 'name': None, 'color': None, 'sum_amount': sum_amount, }) data = [] for record in res: row = {} for k, v in record.items(): row[k] = v data.append(row) return JsonResponse({ 'data': data, 'meta': { 'total_records': qs.count() + 1 } })
def reset(self, request): body = jsonloads(request.body) # form = ResetForm(body) # if not form.is_valid(): # raise BinderValidationError(form.errors) for s in self._get_images(body, request): file = self._get_file(s) original_file = self._get_backup_file(s) src_im = Image.open(original_file) src_im.save(file.file.name, overwrite=True) file.file.close() original_file.file.close() return JsonResponse([])
def rotate(self, request): body = jsonloads(request.body) form = RotateForm(body) if not form.is_valid(): raise BinderValidationError(form.errors) angle = body['angle'] for s in self._get_images(body, request): file = self._get_file(s) src_im = Image.open(file) rotated_img = src_im.rotate(angle, expand=1) rotated_img.save(file.file.name, overwrite=True) file.close() return JsonResponse([])
def dispatch_file_field(self, request, pk=None, file_field=None): if isinstance(pk, self.model): obj = pk else: try: obj = self.get_queryset(request).get(pk=int(pk)) except self.model.DoesNotExist: raise BinderNotFound() res = super().dispatch_file_field(request, obj, file_field) if request.method == 'POST': data = jsonloads(res.content) field = next(iter(data['data'])) data['data'][field] += self._get_params(obj, field) return JsonResponse(data) return res
def crop(self, request): body = jsonloads(request.body) form = CropForm(body) if not form.is_valid(): raise BinderValidationError(form.errors) x_1 = body['x_1'] x_2 = body['x_2'] y_1 = body['y_1'] y_2 = body['y_2'] for s in self._get_images(body, request): file = self._get_file(s) src_im = Image.open(file) rotated_img = src_im.crop((x_1, y_1, x_2, y_2)) rotated_img.save(file.file.name, overwrite=True) file.close() return JsonResponse([])
def login(self, request): perm = 'auth.login_user' # {permissions/views.py copy-paste} if getattr(request, '_permission', None) is None: self._parse_permissions(request) if perm not in request._permission: raise BinderForbidden(perm, request.user) try: body = jsonloads(request.body) username = body.get('username', '') password = body.get('password', '') except Exception: username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(username=username.lower(), password=password) if user is None: raise BinderNotAuthenticated() request.user = user data = self._store(Token(), {'user': user.pk}, request) meta = data.setdefault('_meta', {}) withs = self._get_withs([data['id']], request=request, withs=None) meta['with'], meta['with_mapping'], meta['with_related_name_mapping'], field_results = withs for datum in data: for (w, (view, ids_dict, is_singular)) in field_results.items(): if is_singular: try: datum[w] = list(ids_dict[datum['id']])[0] except IndexError: datum[w] = None else: datum[w] = list(ids_dict[datum['id']]) return JsonResponse(data)
def custom(request): return JsonResponse({'custom': True})
import json import unittest from unittest.mock import patch from django.contrib.auth.models import User, Group from django.contrib.auth.tokens import default_token_generator from django.test import TestCase, Client, override_settings from binder.json import JsonResponse @patch( 'binder.plugins.views.UserViewMixIn._reset_pass_for_user', side_effect=lambda *args: JsonResponse({}), ) class UserPasswordResetTestCase(TestCase): def setUp(self): self.user = User.objects.create_user(username='******', password='******') self.user.save() self.token = default_token_generator.make_token(self.user) def test_reset_call(self, reset_mock): client = Client() res = client.put('/user/{}/reset_password/'.format(self.user.pk), json.dumps({ 'reset_code': self.token, 'password': '******', })) self.assertEqual(200, res.status_code)
def send_activation_email(self, request): """ Endpoint that can be used to send an activation mail for an user. Calls the _send_activation_email callback if the user is succesfully activated Request: POST { "email": "email" } Response: { "code": code } Possible codes: sent Mail is send sucessfully already active User is already active, no mail was send blacklisted User was not activated """ if request.method != 'PUT': raise BinderMethodNotAllowed() # For lack of a better check self._require_model_perm('reset_password', request) decoded = request.body.decode() try: body = json.loads(decoded) except ValueError: raise BinderRequestError( _('Invalid request body: not a JSON document.')) logger.info('activation email attempt for {}'.format( body.get('email', ''))) if body.get('email') is None: raise BinderValidationError({'email': ['missing']}) try: user = self.model._default_manager.get(email=body.get('email')) except self.model.DoesNotExist: raise BinderNotFound() if user.is_active: if user.last_login is None: # TODO: Figure out a way to make this customisable without # allowing injection of arbitrary URLs (phishing!) self._send_activation_email(request, user) response = JsonResponse({'code': 'sent'}) response.status_code = 201 else: response = JsonResponse({'code': 'already active'}) else: response = JsonResponse({'code': 'blacklisted'}) response.status_code = 400 return response