Exemplo n.º 1
0
    def delete(self, request, post_id):
        """ Deletes a single restaurant post """
        user = request.user
        check_user_status(user)

        post_deleted = RestaurantPost.remove_post(post_id)
        return JsonResponse({"Deleted post": model_to_json(post_deleted)})
Exemplo n.º 2
0
    def get(self, request):
        """ Retrieves a restaurant owner profile """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant_owner = RestaurantOwner.get_by_user_id(user_id=user_id)
        return JsonResponse(model_to_json(restaurant_owner))
Exemplo n.º 3
0
    def get(self, request):
        """ Get all restaurants favourited by a user """
        user = request.user
        check_user_status(user)

        user_id = user.id
        response = UserFavRestrs.getUserFavourites(user_id)
        return JsonResponse(response, safe=False)
Exemplo n.º 4
0
    def get(self, request):
        """ Get all posts for a restaurant (for ROs) """
        user = request.user
        check_user_status(user)

        user_id = user.id
        posts = RestaurantPost.get_by_user_id(user_id)
        return JsonResponse(posts)
Exemplo n.º 5
0
 def get(self, request):
     """ Retrieves the 5 (or less) nearest restaurants from an sduser """
     user = request.user
     check_user_status(user)
     user_id = user.id
     role = user.role
     nearest = get_nearby_restaurants(user_id, role)
     return JsonResponse(nearest, safe=False)
Exemplo n.º 6
0
    def delete(self, request, dish_id):
        """ Deletes dish from database """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant = PendingRestaurant.get_by_owner(user_id)
        deleted_dish = PendingFood.remove_dish(dish_id, restaurant._id)
        return JsonResponse(model_to_json(deleted_dish))
Exemplo n.º 7
0
    def put(self, request):
        body = request.data
        user = request.user
        check_user_status(user)

        for field in body:
            setattr(user, field, body[field])
        user.save()
        return JsonResponse(model_to_dict(user))
Exemplo n.º 8
0
    def put(self, request):
        """ Modifies a SubscriberProfile record in the database """
        body = request.data
        user = request.user
        check_user_status(user)

        body['user_id'] = user.id
        SubscriberProfile.field_validate(body)
        profile = SubscriberProfile.edit(body)
        return JsonResponse(model_to_json(profile))
Exemplo n.º 9
0
    def get(self, request):
        """ Retrieve restaurant from pending collection by the owner's user_id """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant = PendingRestaurant.get_by_owner(user_id)

        restaurant = model_to_json(restaurant)
        return JsonResponse(restaurant)
Exemplo n.º 10
0
    def delete(self, request, rest_id):
        """ Remove a new user-restaurant-favourite relation """
        user = request.user
        check_user_status(user)

        user_id = user.id
        body = {'user_id': user_id, 'restaurant_id': rest_id}
        UserFavRestrs.field_validate(body)
        response = UserFavRestrs.remove_fav(user_id, rest_id)
        return JsonResponse(response, safe=False)
Exemplo n.º 11
0
    def post(self, request):
        """ Insert new restaurant as a draft into database """
        user = request.user
        check_user_status(user)

        validate(instance=request.data,
                 schema=schemas.restaurant_insert_draft_schema)
        body = request.data
        PendingRestaurant.field_validate_draft(body)
        restaurant = PendingRestaurant.insert(body)
        return JsonResponse(model_to_json(restaurant))
Exemplo n.º 12
0
    def put(self, request):
        """ Updates a restaurant owner profile """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data, schema=schemas.restaurant_owner_edit_schema)
        body = request.data
        RestaurantOwner.field_validate(body)
        profile = RestaurantOwner.edit_profile(user_id, body)
        return JsonResponse(model_to_json(profile))
Exemplo n.º 13
0
    def get(self, request):
        """ Retrieves a SubscriberProfile record from the database """
        user = request.user
        check_user_status(user)

        profile = SubscriberProfile.objects.get(user_id=user.id)
        if not profile:
            raise ObjectDoesNotExist(
                'No subscriber profile found with owner user id of this: ' +
                str(user_id))
        return JsonResponse(model_to_dict(profile))
Exemplo n.º 14
0
    def get(self, request):
        """ Retrieve all dishes from restaurant owned by user """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant = PendingRestaurant.get_by_owner(user_id)
        rest_id = restaurant._id
        dishes = PendingFood.get_by_restaurant(rest_id)
        response = {'Dishes': models_to_json(dishes)}
        return JsonResponse(response)
Exemplo n.º 15
0
    def put(self, request):
        """ For updating existing image caption for a restaurant """
        user = request.user
        check_user_status(user)

        user_id = user.id
        body = request.data
        validate(instance=body, schema=schemas.image_captions_schema)
        restaurant = PendingRestaurant.get_by_owner(user_id)

        restaurant = PendingRestaurant.update_image_captions(restaurant, body)
        return JsonResponse(model_to_json(restaurant))
Exemplo n.º 16
0
    def put(self, request):
        """ Edit a restaurant profile and save it as a draft in the database """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data,
                 schema=schemas.restaurant_edit_draft_schema)
        body = request.data
        PendingRestaurant.field_validate_draft(body)
        restaurant = PendingRestaurant.edit_draft(user_id, body)
        return JsonResponse(model_to_json(restaurant))
Exemplo n.º 17
0
    def post(self, request):
        """ Add a new user-restaurant-favourite relation """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data, schema=schemas.user_fav_schema)
        body = request.data
        body['user_id'] = user_id
        rest_id = body['restaurant']
        UserFavRestrs.field_validate(body)
        response = UserFavRestrs.insert(user_id, rest_id)
        return JsonResponse(response, safe=False)
Exemplo n.º 18
0
    def post(self, request):
        """ Insert a new post for a restaurant """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data, schema=schemas.post_schema)
        body = request.data
        body['owner_user_id'] = user_id
        RestaurantPost.field_validate(body)

        post = RestaurantPost.insert(body, request)
        return JsonResponse(model_to_json(post))
Exemplo n.º 19
0
    def post(self, request):
        """ Inserts a new SubscriberProfile record into the database """
        body = request.data
        user = request.user
        check_user_status(user)

        body['user_id'] = user.id
        SubscriberProfile.field_validate(body)
        if SubscriberProfile.objects.filter(user_id=body['user_id']).exists():
            raise IntegrityError(
                'Cannot insert subscriber profile, an object with this user id already exists'
            )
        profile = SubscriberProfile.signup(body)
        return JsonResponse(model_to_json(profile))
Exemplo n.º 20
0
    def put(self, request):
        """ For inserting or updating restaurant media """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant = PendingRestaurant.get_by_owner(user_id)

        form = RestaurantMediaForm(request.data, request.FILES)
        if not form.is_valid():
            raise ValidationError(message=form.errors, code="invalid_input")

        restaurant = PendingRestaurant.upload_media(
            restaurant, request.data, request.FILES)
        return JsonResponse(model_to_json(restaurant))
Exemplo n.º 21
0
    def post(self, request):
        """ Insert dish into database """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data, schema=schemas.food_insert_edit_schema)
        body = request.data
        PendingFood.field_validate(body)

        restaurant = PendingRestaurant.get_by_owner(user_id)

        rest_id = restaurant._id
        food = PendingFood.add_dish(body, rest_id)
        return JsonResponse(model_to_json(food))
Exemplo n.º 22
0
    def put(self, request, dish_id):
        """ Updates dish data """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data,
                 schema=schemas.food_insert_edit_schema)
        body = request.data
        PendingFood.field_validate(body)

        restaurant = PendingRestaurant.get_by_owner(user_id)

        dish = PendingFood.edit_dish(dish_id, body, restaurant._id)
        return JsonResponse(model_to_json(dish))
Exemplo n.º 23
0
    def delete(self, request):
        """ For removing image(s) from the restaurant_image_url field
        and Google Cloud bucket """
        user = request.user
        check_user_status(user)

        user_id = user.id
        restaurant = PendingRestaurant.get_by_owner(user_id)

        form = RestaurantImageDeleteForm(request.data, request.FILES)
        if not form.is_valid():
            raise ValidationError(message=form.errors, code="invalid_input")

        restaurant = PendingRestaurant.delete_media(restaurant, request.data)
        return JsonResponse(model_to_json(restaurant))
Exemplo n.º 24
0
    def post(self, request):
        """ Inserts a new restaurant profile record into the database and
        attaches user_id to the corresponding restaurant
        """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data, schema=schemas.restaurant_owner_signup_schema)
        body = request.data
        RestaurantOwner.field_validate(body)

        body['user_id'] = user_id
        profile = RestaurantOwner.signup(body)
        return JsonResponse(model_to_json(profile))
Exemplo n.º 25
0
    def put(self, request, dish_id):
        """ For inserting or updating restaurant media """
        user = request.user
        check_user_status(user)

        user_id = user.id
        dish = PendingFood.objects.filter(_id=dish_id).first()
        if not dish:
            raise IntegrityError("Could not find the dish with id: " + dish_id)

        form = FoodMediaForm(request.data, request.FILES)
        if not form.is_valid():
            raise ValidationError(message=form.errors, code="invalid_input")

        dish = PendingFood.upload_media(dish, request.data, request.FILES)
        return JsonResponse(model_to_json(dish))
Exemplo n.º 26
0
    def put(self, request):
        """ Insert or update a restaurant record for admin approval """
        user = request.user
        check_user_status(user)

        user_id = user.id
        validate(instance=request.data,
                 schema=schemas.restaurant_insert_for_approval_schema)
        body = request.data
        PendingRestaurant.field_validate(body)

        rest_filter = PendingRestaurant.objects.filter(owner_user_id=user_id)
        if not rest_filter.exists():
            body['status'] = Status.Pending.value
            restaurant = PendingRestaurant.insert(body)
        else:
            restaurant = PendingRestaurant.edit_approval(user_id, body)
        return JsonResponse(model_to_json(restaurant))
Exemplo n.º 27
0
    def get(self, request, id):
        """ Retrieve an article given id (restricted by user's visibility) """
        user = request.user

        if user.is_anonymous:
            article = Article.objects.filter(
                visibility="ALL", published=True, id=id).values()
        else:
            check_user_status(user)
            article = Article.objects.filter(
                visibility__in=[user.role, "ALL"], published=True, id=id).values()
        # evaluate it instead of calling exists() because we need the cached result in response
        if article:
            response = {'article': article[0]}
        else:
            raise NotFound('Cannot find article with id: ' + str(id))
        # model to dict (and therefore model to json) does not work for date fields
        # so we get the queryset by calling values() and let DRF handles the serialization (Response)
        return Response(response)
Exemplo n.º 28
0
    def post(self, request):
        refresh_token = request.COOKIES.get('refresh_token')
        user_id = request.data.get('id')
        current_user = request.user
        check_user_status(current_user)
        if current_user.id is not user_id:
            return JsonResponse(
                {
                    'message': 'deactivation failed: user mismatch!',
                    'code': 'deactivation_fail'
                },
                status=400)

        try:
            user = User.objects.get(id=user_id)
            if refresh_token == user.refresh_token:
                user.is_active = False
                user.save()
                send_email_deactivate(user=user, request=request)
                return JsonResponse(model_to_dict(user))
            else:
                return JsonResponse(
                    {
                        'message': 'deactivation failed: token mismatch',
                        'code': 'deactivation_fail'
                    },
                    status=400)
        except User.DoesNotExist:
            return JsonResponse(
                {
                    'message': 'deactivation failed: User not found',
                    'code': 'deactivation_fail'
                },
                status=400)
        except (BadHeaderError, SMTPException):
            return JsonResponse(
                {
                    'message':
                    ' There is an error sending the notification email. However, this user account has been successfully deactivated. No further action is required.',
                    'code': 'fail_to_send_email'
                },
                status=503)
Exemplo n.º 29
0
    def post(self, request):
        passwords = request.data
        old_password = passwords.get('old_password')
        new_password1 = passwords.get('new_password1')
        new_password2 = passwords.get('new_password2')

        user = request.user
        check_user_status(user)

        # if not user.check_password(old_password):

        # Django way of validation
        form = SDPasswordChangeForm(user=user, data=passwords)

        if form.is_valid():
            form.save()
            # user.set_password(form.cleaned_data['new_password2'])
            # user.save()

            # need to renew the JWT
            return construct_token_response_for_user(user)
        else:
            return JsonResponse(form.errors.get_json_data(escape_html=True),
                                status=400)
Exemplo n.º 30
0
    def post(self, request):
        """
        FLOW 1 (for new signup)
        creates a disabled SDUser and associate it with the google account,
        if for any reason the google account has unverified email,
        it will send a verification email to that address

        returns messages indicating the above for frontend to handle

        FLOW 2 (for verified user)
        updates the SDUser associated with the google account
        and authenticate this user

        returns access token in response body with refresh token set in the httpOnly cookie
        """

        payload = {'access_token': request.data.get("authToken")}
        # verify the token and use it to get user info
        r = requests.get('https://www.googleapis.com/oauth2/v2/userinfo',
                         params=payload)
        data = json.loads(r.text)
        # print(data)

        if 'error' in data:
            content = {
                'message':
                'wrong google token / this google token is already expired.'
            }
            return Response(content)

        auth_id = data['id']
        # this should be the same as the one obtained from google idToken
        email = data['email']
        role = request.data.get('role')

        try:
            googleJWT = id_token.verify_oauth2_token(
                request.data.get('idToken'), google_requests.Request(),
                settings.GOOGLE_OAUTH2_CLIENT_ID)
            #print('user info from google idToken:')
            # print(googleJWT)
            # this is definitive as it is not modifiable
            email = googleJWT['email']
            # get user by auth Id (3rd party id) Or email
            user = User.objects.get(
                Q(auth_id=auth_id) | Q(email__iexact=email))
            '''
            if user.email is not email:
                user.email = email
                user.save()
            '''
            check_user_status(user)
        # if verify_oauth2_token failed
        except ValueError:
            return JsonResponse({'message': 'idToken is invalid'}, status=400)
        # if user not in db, create one with random password
        except User.DoesNotExist:
            if role is None or role == "":
                return JsonResponse(
                    {
                        'message':
                        'no user is associated with this google account, please register an account first'
                    },
                    status=400)
            user = create_default_user_for_3rd_party(email, auth_id, role)

            # if email is not verified with 3rd party we create a disabled user and send an email for verification
            if not googleJWT['email_verified']:
                user.is_active = False
                user.save()
                create_disable_user_and_send_verification_email(
                    user, password, request)
                check_user_status(user)

        response = construct_token_response_for_user(user)

        return response