Ejemplo n.º 1
0
def check_and_forward(request):

    resource = request.POST.get("resource", None)

    if resource is None:
        return JsonResponse(data=TrainingDiaryResponse.error_response_dict("No resource specifiec"))

    logger.debug(f"{request.user} requesting {resource}")

    view_class = ANYONE_RESOURCE_MAP.get(resource, None)
    if view_class is None and request.user.is_authenticated:
        view_class = ME_RESOURCE_MAP.get(resource, None)

    if view_class is None:
        return JsonResponse(data=TrainingDiaryResponse.error_response_dict(f"You need to be logged in to access this resource"))

    view_class_instance = view_class()
    missing_fields = []
    for field in view_class_instance.required_post_fields():
        if field not in request.POST:
            missing_fields.append(field)
    for field in view_class_instance.required_file_fields():
        if field not in request.FILES:
            missing_fields.append(field)

    if len(missing_fields) > 0:
        return JsonResponse(data=TrainingDiaryResponse.error_response_dict(f'Cannot process {resource} as was not passed all these fields: {", ".join(missing_fields)}'))

    response = view_class_instance.call_resource(request)

    return response
Ejemplo n.º 2
0
    def post(self, request, *args, **kwargs):
        r = super().post(request, args, kwargs)
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'])

        if user is None:
            return JsonResponse(data=TrainingDiaryResponse.error_response_dict('Invalid username and password. Please try again'))

        if r.status_code == 302:
            login(self.request, user)
            response = TrainingDiaryResponse()
            response.set_status(response.SUCCESS)
            response.add_data('user', str(user))
            response.add_data('logged_in', True)
            return JsonResponse(data=response.as_dict())
        else:
            return JsonResponse(data=TrainingDiaryResponse.error_response_dict('Unable to login. No idea why'))