Example #1
0
class CommentsTests(TestCase):
    def setUp(self):
        self.user = User(
            email="*****@*****.**",
            first_name="John",
            last_name="Doe",
            personal_id="20171118-1234",
            address="Gatan 2",
            city="Luleå",
            zip_code="97434",
            phone_number="0731234567",
        )
        self.password = '******'
        self.user.set_password(self.password)
        self.user.save()

        self.product = Product.objects.create(name='i7',
                                              description="Bla bla bla",
                                              price=200,
                                              inventory=3)
        self.comment = Comment.objects.create(comment="Test kommentar.",
                                              user=self.user,
                                              product=self.product)

    def test_comment_is_visible_to_all_visitors(self):
        response = self.client.get(
            reverse('shop_detail', args=(self.product.pk, )))
        self.assertContains(response, "Test kommentar.")
Example #2
0
    def sign_up(self, instance):
        """
        :param instance:
        - field: email
          type: string
        - field: first_name
          type: string
        - field: last_name
          type: string
        - field: password
          type: string
        - field: repeat_passwor
          type: string
        :return user instance:
        - field: id
          type: int
        - field: email
          type: string
        - field: first_name
          type: string
        - field: last_name
          type: string
        - field: access_token
          type: string
        - field: refresh_token
          type: string
        """
        logging.info(instance)
        email = instance.email
        first_name = instance.first_name
        last_name = instance.last_name
        password = instance.password
        repeat_password = instance.repeat_password

        if password != repeat_password:
            raise endpoints.BadRequestException("Password do not match")

        unique_properties = ['email']
        user_data = User.create_user(email,
                                     unique_properties,
                                     email=email,
                                     first_name=first_name,
                                     password_raw=password,
                                     last_name=last_name,
                                     verified=True)
        if not user_data[0]:
            raise endpoints.BadRequestException(
                "User with this email already exists.")
        user = user_data[1]
        user_id = user.get_id()

        token, refresh_token = User.create_auth_token(user_id)

        return SignUpResponse(id=user.get_id(),
                              email=user.email,
                              first_name=user.first_name,
                              last_name=user.last_name,
                              access_token=token,
                              refresh_token=refresh_token)
Example #3
0
 def logout(self, instance):
     """
     :param instance:
     :return no-content:
     """
     logging.info(instance)
     User.delete_auth_token(self.user.get_id(), self.token)
     return message_types.VoidMessage()
Example #4
0
 def delete_profile(self, instance):
     """
     :param instance:
     :return no-content:
     """
     logging.info(instance)
     user_id = self.user.get_id()
     User.delete_auth_token(self.user.get_id(), self.token)
     User.delete_by_id(user_id)
     return message_types.VoidMessage()
Example #5
0
class Customer(TestCase):
    def setUp(self):
        self.user = User(
            email="*****@*****.**",
            first_name="John",
            last_name="Doe",
            personal_id="20171118-1234",
            address="Gatan 2",
            city="Luleå",
            zip_code="97434",
            phone_number="0731234567",
        )
        self.password = '******'
        self.user.set_password(self.password)
        self.user.save()

        self.order = Order.objects.create(
            order_status='0',
            user=self.user,
        )

    def test_cannot_login_to_admin_panel(self):
        data = {
            'username': self.user.email,
            'password': self.password,
        }
        form = AdminAuthenticationForm(None, data)
        self.assertEquals(form.is_valid(), False)

    def test_display_as_logged_out_on_template(self):
        response = self.client.get(reverse('profile'))
        self.assertEquals(response.status_code, 302)
        pass

    def test_display_as_logged_in_on_template(self):
        data = {
            'username': self.user.email,
            'password': self.password,
        }
        is_logged_in = self.client.login(**data)
        self.assertEquals(is_logged_in, True)
        response = self.client.get(reverse('profile'))
        self.assertEquals(response.status_code, 200)

    def test_can_see_orders(self):
        data = {
            'username': self.user.email,
            'password': self.password,
        }
        is_logged_in = self.client.login(**data)
        self.assertEquals(is_logged_in, True)

        response = self.client.get(reverse('profile_orders'))
        self.assertContains(response, "Verified")
Example #6
0
    def refresh(self, instance):
        """
        :param instance:
        - field: refresh_token
          type: string
        - field: password
          type: string
        :return user instance:
        - field: id
          type: int
        - field: email
          type: string
        - field: first_name
          type: string
        - field: last_name
          type: string
        - field: access_token
          type: string
        - field: refresh_token
          type: string
        """
        refresh_token = instance.refresh_token
        try:
            payload = jwt.decode(refresh_token,
                                 JWT_SECRET,
                                 issuer='refresh',
                                 algorithms=JWT_ALGORITHM)
        except jwt.ExpiredSignatureError:

            logging.info('Refresh token has been expired')
            raise endpoints.BadRequestException(
                'Your refresh token has been expired!')
        except jwt.InvalidIssuerError:
            logging.info('Refresh token has been expired')
            raise endpoints.BadRequestException(
                'Your have invalid token type!')
        user_id = int(payload['user_id'])
        user, timestamp = User.get_by_refresh_token(user_id, refresh_token)
        if user is None and timestamp is None:
            logging.info('Invalid refresh token!')
            raise endpoints.BadRequestException('Invalid refresh token!')
        token, refresh_token = User.create_auth_token(user_id)

        return SignInResponse(id=user.get_id(),
                              email=user.email,
                              first_name=user.first_name,
                              last_name=user.last_name,
                              access_token=token,
                              refresh_token=refresh_token)
Example #7
0
 def check_login(self, *args, **kwargs):
     auth_header = self.request_state.headers.get('authorization', '')
     if not len(auth_header):
         logging.info('Access token invalid')
         raise endpoints.UnauthorizedException(
             "Your have invalid token format!")
     start, token = auth_header.split(' ')
     if start == 'Bearer' and token:
         try:
             payload = jwt.decode(token,
                                  JWT_SECRET,
                                  issuer='auth',
                                  algorithms=JWT_ALGORITHM)
             user, tmst = User.get_by_auth_token(
                 int(payload.get('user_id')), token)
             if user is None:
                 logging.info('We can\' find associated users')
                 raise endpoints.UnauthorizedException(
                     "Your have invalid token!")
             else:
                 self.user = user
                 self.token = token
                 return handler(self, *args, **kwargs)
         except jwt.ExpiredSignatureError:
             logging.info('Refresh token has been expired')
             raise endpoints.UnauthorizedException(
                 "Your access token has been expired!")
         except jwt.InvalidIssuerError:
             logging.info('Access token issue error')
             raise endpoints.UnauthorizedException(
                 "Your have invalid token type!")
     else:
         logging.info('Access token has been invalid')
         raise endpoints.UnauthorizedException(
             "Your have invalid token format!")
Example #8
0
    def setUp(self):
        self.user = User(
            email="*****@*****.**",
            first_name="John",
            last_name="Doe",
            personal_id="20171118-1234",
            address="Gatan 2",
            city="Luleå",
            zip_code="97434",
            phone_number="0731234567",
        )
        self.password = '******'
        self.user.set_password(self.password)
        self.user.save()

        self.cart = Cart.objects.create(user=self.user)
Example #9
0
 def get_queryset(self):
     queryset = super(FrontpageView, self).get_queryset()
     self.form = SearchForm(self.request.GET)
     if self.form.is_valid():
         filters = User.get_queryset(self.form.cleaned_data)
         if len(filters):
             queryset = User.objects.filter(filters)
     return queryset
Example #10
0
class CartTests(TestCase):
    def setUp(self):
        self.user = User(
            email="*****@*****.**",
            first_name="John",
            last_name="Doe",
            personal_id="20171118-1234",
            address="Gatan 2",
            city="Luleå",
            zip_code="97434",
            phone_number="0731234567",
        )
        self.password = '******'
        self.user.set_password(self.password)
        self.user.save()

        self.cart = Cart.objects.create(user=self.user)

    def test_product_snapshot_defaults_to_zero(self):
        product = Product.objects.create(name='i7',
                                         description="Bla bla bla",
                                         price=200,
                                         inventory=3)
        ps = CartItem.objects.create(
            product=product,
            user_cart=self.cart,
        )
        self.assertEquals(ps.price_snapshot, 0)

    def test_cart_cascade_deletes(self):
        product = Product.objects.create(name='i7',
                                         description="Bla bla bla",
                                         price=200,
                                         inventory=3)
        ps = CartItem.objects.create(
            product=product,
            user_cart=Cart.objects.get(pk=self.cart.pk),
        )

        self.assertEquals(Cart.objects.filter(pk=self.cart.pk).count(), 1)
        self.assertEquals(CartItem.objects.filter(pk=ps.pk).count(), 1)

        Cart.objects.get(pk=self.cart.pk).delete()

        self.assertEquals(Cart.objects.filter(pk=self.cart.pk).count(), 0)
        self.assertEquals(CartItem.objects.filter(pk=ps.pk).count(), 0)
Example #11
0
 def get_queryset(self):
     queryset = super(FrontpageView, self).get_queryset()
     self.form = SearchForm(self.request.GET)
     if self.form.is_valid():
         filters = User.get_queryset(self.form.cleaned_data)
         if len(filters):
             queryset = User.objects.filter(filters)
     return queryset
Example #12
0
    def setUp(self):
        self.user = User(
            email="*****@*****.**",
            first_name="John",
            last_name="Doe",
            personal_id="20171118-1234",
            address="Gatan 2",
            city="Luleå",
            zip_code="97434",
            phone_number="0731234567",
        )
        self.password = '******'
        self.user.set_password(self.password)
        self.user.save()

        self.product = Product.objects.create(name='i7',
                                              description="Bla bla bla",
                                              price=200,
                                              inventory=3)
Example #13
0
    def sign_in(self, instance):
        """
        :param instance:
        - field: email
          type: string
        - field: password
          type: string
        :return user instance:
        - field: id
          type: int
        - field: email
          type: string
        - field: first_name
          type: string
        - field: last_name
          type: string
        - field: access_token
          type: string
        - field: refresh_token
          type: string
        """
        logging.info(instance)
        email = instance.email
        password = instance.password
        try:
            user = User.get_by_auth_password(email, password=password)
            token, refresh_token = User.create_auth_token(user.get_id())

        except (InvalidAuthIdError, InvalidPasswordError) as e:
            logging.info('Login failed for user %s because of %s', email,
                         type(e))

            raise endpoints.BadRequestException(
                'Login failed for user %s because user with this email does not exist'
                % email)

        return SignInResponse(id=user.get_id(),
                              email=user.email,
                              first_name=user.first_name,
                              last_name=user.last_name,
                              access_token=token,
                              refresh_token=refresh_token)
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('admin'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That is an invalid or expired token', 'warning')
        return redirect(url_for('reset_request'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash('your password has been updated. You are now able to login now',
              'success')
        return request(url_for('login'))
    return render_template('reset_token.html', form=form)
Example #15
0
 def update_profile(self, instance):
     """
     :param instance:
     - field: email
       type: string
     - field: first_name
       type: string
     - field: last_name
       type: string
     :return user instance:
     - field: id
       type: int
     - field: email
       type: string
     - field: first_name
       type: string
     - field: last_name
       type: string
     """
     logging.info(instance)
     if self.user.email != instance.email:
         ur = User.get_by_auth_id(instance.email)
         if ur is not None:
             raise endpoints.BadRequestException(
                 'User with this email already exists')
         self.user.email = instance.email
         self.user.add_auth_id(instance.email)
     for field in instance.all_fields():
         if field.name != 'email':
             value = getattr(instance, field.name)
             setattr(self.user, field.name, value)
     self.user.put()
     return ProfileResponse(
         id=self.user.get_id(),
         email=self.user.email,
         first_name=self.user.first_name,
         last_name=self.user.last_name,
     )
Example #16
0
class RatingTests(TestCase):
    def setUp(self):
        self.user = User(
            email="*****@*****.**",
            first_name="John",
            last_name="Doe",
            personal_id="20171118-1234",
            address="Gatan 2",
            city="Luleå",
            zip_code="97434",
            phone_number="0731234567",
        )
        self.password = '******'
        self.user.set_password(self.password)
        self.user.save()

        self.product = Product.objects.create(name='i7',
                                              description="Bla bla bla",
                                              price=200,
                                              inventory=3)

    def test_rating_buttons_are_hidden_when_logged_out(self):
        response = self.client.get(
            reverse('shop_detail', args=(self.product.pk, )))
        self.assertNotContains(response, "Give your rating")

    def test_rating_buttons_are_visible_when_logged_in(self):
        self.client.force_login(self.user)
        response = self.client.get(
            reverse('shop_detail', args=(self.product.pk, )))
        self.assertContains(response, "Give your rating")

    def test_ratings_are_visible_when_logged_out(self):
        Rating.objects.create(product=self.product, user=self.user, rating=1)
        response = self.client.get(
            reverse('shop_detail', args=(self.product.pk, )))
        self.assertContains(response, "Rating:")
        self.assertContains(
            response,
            '<div class="progress-bar bg-success" role="progressbar"')

    def test_ratings_are_visible_when_logged_in(self):
        Rating.objects.create(product=self.product, user=self.user, rating=1)
        self.client.force_login(self.user)
        response = self.client.get(
            reverse('shop_detail', args=(self.product.pk, )))
        self.assertContains(response, "Rating:")
        self.assertContains(
            response,
            '<div class="progress-bar bg-success" role="progressbar"')

    def test_user_can_add_good_rating(self):
        self.client.force_login(self.user)
        order = Order.objects.create(user=self.user)
        OrderProduct.objects.create(order=order,
                                    quantity=1,
                                    product=self.product,
                                    cost=5)
        _rating = 1
        response = self.client.post(reverse('product_rate',
                                            args=(
                                                self.product.pk,
                                                _rating,
                                            )),
                                    follow=True)
        ratingDb = Rating.objects.get(user=self.user,
                                      product=self.product,
                                      rating=_rating)
        self.assertContains(response, "Your rating has been registered")
        self.assertAlmostEqual(ratingDb.rating, _rating)

    def test_user_can_add_bad_rating(self):
        self.client.force_login(self.user)
        order = Order.objects.create(user=self.user)
        OrderProduct.objects.create(order=order,
                                    quantity=1,
                                    product=self.product,
                                    cost=5)
        _rating = 0
        response = self.client.post(reverse('product_rate',
                                            args=(
                                                self.product.pk,
                                                _rating,
                                            )),
                                    follow=True)
        ratingDb = Rating.objects.get(user=self.user,
                                      product=self.product,
                                      rating=_rating)
        self.assertContains(response, "Your rating has been registered")
        self.assertAlmostEqual(ratingDb.rating, _rating)

    def test_user_cannot_add_negative_rating(self):
        self.client.force_login(self.user)
        order = Order.objects.create(user=self.user)
        OrderProduct.objects.create(order=order,
                                    quantity=1,
                                    product=self.product,
                                    cost=5)
        _rating = -1
        got_exception = False
        try:
            self.client.post(reverse('product_rate',
                                     args=(
                                         self.product.pk,
                                         _rating,
                                     )),
                             follow=True)
        except NoReverseMatch:
            got_exception = True

        ratingDb = Rating.objects.count()
        self.assertEqual(ratingDb, 0)
        self.assertEqual(got_exception, True)

    def test_user_can_change_rating(self):
        self.client.force_login(self.user)
        order = Order.objects.create(user=self.user)
        OrderProduct.objects.create(order=order,
                                    quantity=1,
                                    product=self.product,
                                    cost=5)
        _rating = 1
        Rating.objects.create(product=self.product,
                              user=self.user,
                              rating=(not _rating))
        response = self.client.get(reverse('shop_detail',
                                           args=(self.product.pk, )),
                                   follow=True)
        self.assertContains(response,
                            '<a type="button" class="btn btn-danger"')

        response = self.client.post(reverse('product_rate',
                                            args=(
                                                self.product.pk,
                                                _rating,
                                            )),
                                    follow=True)
        ratingDb = Rating.objects.get(user=self.user,
                                      product=self.product,
                                      rating=_rating)
        self.assertContains(response, "Your rating has been registered")
        self.assertAlmostEqual(ratingDb.rating, _rating)

    def test_logged_out_user_cannot_add_rating(self):
        _rating = 1
        response = self.client.post(reverse('product_rate',
                                            args=(
                                                self.product.pk,
                                                _rating,
                                            )),
                                    follow=True)
        self.assertEqual(0, Rating.objects.count())
        self.assertContains(response, "<h1>Login</h1>")

    def test_user_can_rate_after_buying_product_more_than_once(self):
        self.client.force_login(self.user)

        order = Order.objects.create(user=self.user)
        OrderProduct.objects.create(order=order,
                                    quantity=1,
                                    product=self.product,
                                    cost=5)

        order = Order.objects.create(user=self.user)
        OrderProduct.objects.create(order=order,
                                    quantity=2,
                                    product=self.product,
                                    cost=4)

        _rating = 1

        response = self.client.post(reverse('product_rate',
                                            args=(
                                                self.product.pk,
                                                _rating,
                                            )),
                                    follow=True)
        ratingDb = Rating.objects.get(user=self.user,
                                      product=self.product,
                                      rating=_rating)
        self.assertContains(response, "Your rating has been registered")
        self.assertAlmostEqual(ratingDb.rating, _rating)