Exemple #1
0
def post_ecocase(request):
    print("at ecocase views: post ecocase")
    if request.method == 'POST':
        post_data = json.loads(request.body)
        title = post_data['title']

        try:
            username = post_data['username']
        except KeyError:
            token = get_token_data(request)
            username = token['username']

        # get ecocase object
        user = User.objects.get(username=username)
        # comment
        ecocase = Ecocase(title=title, user=user)
        try:
            ecocase.save()
        except:
            return JsonResponse({
                'status': 'fail',
                'data': {
                    'message': 'Error while saving ecocase'
                }
            }, status=500)

        return JsonResponse({
            'status': 'success',
            'data': {
                'id': ecocase.id
            }
        })
    elif request.method == 'DELETE':
        id = request.GET.get('id', '')
        # username = request.GET.get('u', '')

        try:
            ecocase = Ecocase.objects.get(id=id)
        except Ecocase.DoesNotExist:
            return JsonResponse({
                'status': 'fail',
                'data': {
                    'message': 'This ecocase does not exist'
                }
            }, status=500)

        try:
            ecocase.delete()
        except:
            return JsonResponse({
                'status': 'fail',
                'data': {
                    'message': 'Error while deleting ecocase'
                }
            }, status=500)

        return JsonResponse({
            'status': 'success'
        })
Exemple #2
0
def get_user_data(request):
    token = get_token_data(request)
    username = token['username']

    try:
        u = User.objects.get(username=username).values('username', 'email')
    except User.DoesNotExist:
        return JsonResponse(
            {
                'status': 'fail',
                'data': {
                    'message': 'The username does not exist'
                }
            },
            status=500)

    return JsonResponse({'status': 'success', 'data': u})
Exemple #3
0
def update_password(request):
    token = get_token_data(request)
    username = token['username']

    post_data = json.loads(request.body)
    new_password = post_data['password']
    old_password = post_data['oldPassword']

    try:
        validate_password(new_password)
    except ValidationError as e:
        return JsonResponse({
            'status': 'fail',
            'data': {
                'message': str(e)
            }
        },
                            status=500)

    # check old password and get user object
    u = authenticate(username=username, password=old_password)
    if u is not None:
        u.set_password(new_password)
        try:
            u.save()
        except:
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message':
                        'There was an error while updating the password'
                    }
                },
                status=500)

        return JsonResponse({'status': 'success'})
    else:
        return JsonResponse({'status': 'fail'}, status=401)
Exemple #4
0
def delete_account(request):
    if request.method != 'DELETE':
        pass

    token = get_token_data(request)
    username = token['username']

    u = User.objects.get(username=username)
    try:
        u.delete()
    except:
        return JsonResponse(
            {
                'status': 'fail',
                'data': {
                    'message': 'There was an error while deleting user account'
                }
            },
            status=500)

    # need to delete jwt cookie on client side
    return JsonResponse({'status': 'success'})
Exemple #5
0
def update_data(request):
    # only the email can be updated here
    token = get_token_data(request)
    username = token['username']

    post_data = json.loads(request.body)
    new_email = post_data['email']

    try:
        validate_email(new_email)
    except ValidationError as e:
        return JsonResponse({
            'status': 'fail',
            'data': {
                'message': str(e)
            }
        },
                            status=500)

    # get user object
    u = User.objects.get(username=username)
    u.email = new_email
    try:
        u.save()
    except:
        return JsonResponse(
            {
                'status': 'fail',
                'data': {
                    'message': 'There was an error while updating user data'
                }
            },
            status=500)

    token = create_login_token({'username': u.username, 'email': u.email})
    res = JsonResponse({'status': 'success'})
    res.set_cookie('token', value=token['token'], expires=token['exp'])
    return res
Exemple #6
0
def post_ecocase(request):
    errors = []
    print('request method:', request.method)
    if request.method == 'POST':
        post_data = json.loads(request.body)
        title = post_data['title']

        try:
            username = post_data['username']
        except KeyError:
            token = get_token_data(request)
            username = token['username']

        # get ecocase object
        user = User.objects.get(username=username)
        # comment
        ecocase = Ecocase(title=title, user=user)
        try:
            ecocase.save()
        except:
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message': 'Error while saving ecocase'
                    }
                },
                status=500)

        return JsonResponse({'status': 'success', 'data': {'id': ecocase.id}})
    elif request.method == 'DELETE':
        id = request.GET.get('id', '')
        # username = request.GET.get('u', '')

        try:
            ecocase = Ecocase.objects.get(id=id)
        except Ecocase.DoesNotExist:
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message': 'This ecocase does not exist'
                    }
                },
                status=500)

        try:
            ecocase.delete()
            return JsonResponse({'status': 'success'})
        except:
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message': 'Error while deleting ecocase'
                    }
                },
                status=500)

    # UPDATE ecocase
    elif request.method == 'PUT':
        update_data = json.loads(request.body)
        update_ecocase = update_data['ecocase']
        upload_files = update_data['uploadFiles']
        removed_urls = update_data['removedUrls']
        objects_to_delete = [{
            'Key': aws_s3_bucket_key + url.split('/')[-1]
        } for url in removed_urls]

        print('objects_to_delete: ', objects_to_delete)
        print('removedUrls: ', removed_urls)

        # UPLOAD directly image to AWS S3
        # s3 = boto3.resource('s3')
        # for file in upload_files:
        #     try:
        #         req = s3.Bucket(AWS_STORAGE_BUCKET_NAME).put_object(
        #             Key='media/ecocases/images/' + file['filename'],
        #             Body=base64.b64decode(file['value']),
        #             ContentType='image/png',
        #             ACL='public-read'
        #         )
        #         print('req put object: ', req)
        #     except Exception as e:
        #         return errors.append(e)

        # DELETE images in aws s3
        if len(objects_to_delete) > 0:
            try:
                s3 = boto3.resource('s3')
                bucket = s3.Bucket(AWS_STORAGE_BUCKET_NAME)
                bucket.delete_objects(Delete={'Objects': objects_to_delete})
            except Exception as e:
                errors.append(str(e))

        try:
            ecocase = Ecocase.objects.get(id=update_ecocase['id'])
            ecocase.title = update_ecocase['title']
            ecocase.promise = update_ecocase['promise']
            ecocase.description = update_ecocase['description']

            for file in upload_files:
                new_image = EcocaseImage(prefix='prefix', ecocase=ecocase)
                new_image.image = ContentFile(base64.b64decode(file['value']),
                                              file['filename'])
                new_image.save()

            for url in removed_urls:
                try:
                    image = EcocaseImage.objects.get(
                        image=url[len(aws_s3_ecocase_image_url):])
                    image.delete()
                except Exception as e:
                    errors.append(str(e))

            ecocase.save()
        except Ecocase.DoesNotExist:
            errors.append('The ecocase does not exist')

        if len(errors) == 0:
            return JsonResponse({
                'status': 'success',
                'data': {
                    'message': 'The ecocase is updated successfully',
                    'ecocase': model_to_dict_ecocase(ecocase)
                }
            })
        else:
            print(errors)
            return JsonResponse({
                'status': 'fail',
                'errors': errors
            },
                                status=500)
Exemple #7
0
def ecocase_rate(request):

    # if POST, save or update rating
    if request.method == 'POST':
        body = json.loads(request.body)
        ecocase_id = body['id']
        rating = int(body['rating'])

        try:
            username = body['username']
        except KeyError:
            token = get_token_data(request)
            username = token['username']

        # get the ecocase object with id ecocase_id, or create it
        ecocase, created = Ecocase.objects.get_or_create(
            id=ecocase_id, defaults={'title': ''})
        # save or update rating
        try:
            r, created = EcocaseRating.objects.update_or_create(
                username=username, ecocase=m, defaults={'rating': rating})
        except Exception as e:
            print(e)
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message': 'Error while saving rating'
                    }
                },
                status=500)

        return JsonResponse({
            'status': 'success',
            'data': {
                'title': m.title,
                'rating': r.rating,
                'is_new': created
            }
        })
    elif request.method == 'DELETE':
        username = request.GET.get('u', '')
        ecocase_id = request.GET.get('m_id', '')

        # find ecocase object
        m = Ecocase.objects.filter(id=ecocase_id).first()
        r = EcocaseRating.objects.filter(ecocase=m, username=username)

        # delete rating
        try:
            r.delete()
        except:
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message': 'Error while deleting rating'
                    }
                },
                status=500)

        return JsonResponse({'status': 'success'})
Exemple #8
0
def comment(request):
    print("at comment views")
    if request.method == 'POST':
        post_data = json.loads(request.body)
        ecocase_id = post_data['ecocaseId']
        body = post_data['body']

        try:
            username = post_data['username']
        except KeyError:
            token = get_token_data(request)
            username = token['username']

        # get ecocase object
        ecocase, created = Ecocase.objects.get_or_create(
            id=ecocase_id, defaults={'title': ''})
        user = User.objects.get(username=username)
        # comment
        cmt = EcocaseComment(ecocase=ecocase, username=username, body=body)
        try:
            cmt.save()
        except:
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message': 'Error while saving comment'
                    }
                },
                status=500)

        return JsonResponse({'status': 'success', 'data': {'id': cmt.id}})
    elif request.method == 'DELETE':
        id = request.GET.get('id', '')
        username = request.GET.get('u', '')

        try:
            cmt = EcocaseComment.objects.get(id=id, username=username)
        except EcocaseComment.DoesNotExist:
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message': 'This comment does not exist'
                    }
                },
                status=500)

        try:
            cmt.delete()
        except:
            return JsonResponse(
                {
                    'status': 'fail',
                    'data': {
                        'message': 'Error while deleting comment'
                    }
                },
                status=500)

        return JsonResponse({'status': 'success'})