예제 #1
0
def login():
    """Log in a registered user by adding the user id to the session."""
    if request.method == "POST":
        email = request.form["email"]
        password = request.form["password"]
        error = None
        user = Customer.objects(email=email).first()

        if user is None:
            error = "Incorrect Email."
        elif not check_password_hash(user["password"], password):
            error = "Incorrect password."

        if error is None:
            # store the user id in a new session and return to the index
            if session.get('order_id'):
                order = Order.objects(id=session.get('order_id')).first()
                order.delete()
            session.clear()
            session["user_id"] = str(user["id"])
            return redirect(url_for("bookstore.index"))

        flash(error)

    return render_template("auth/login.html")
예제 #2
0
def create_order(user_id, copies, book_id):
    book = Book.objects(id=book_id).first()
    customer = Customer.objects(id=user_id).first()
    books = []
    total = 0.0
    while copies > 0:
        books.append(book)
        total = round(total + Book.objects.with_id(book_id).price, 2)
        copies -= 1
    """checking to see if there's a order id already stored in session"""
    if session.get("order_id"):
        order = Order.objects(id=session.get("order_id")).first()
        order.total_price = round(order.total_price + total, 2)
        for book in books:
            order.books.append(book)
        order.save()
    else:
        order = Order(customer_name="{} {}".format(customer.first_name,
                                                   customer.last_name),
                      books=books,
                      shipping_address=customer.address,
                      total_price=total,
                      order_status="processing",
                      order_date=datetime.datetime.now).save()
        session["order_id"] = str(order.id)

    return order
예제 #3
0
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.user``."""
    user_id = session.get("user_id")

    if user_id is None:
        g.user = None
    else:
        g.user = Customer.objects(id=user_id).first()
예제 #4
0
def register():
    """Register a new user.
    Validates that the username is not already taken. Hashes the
    password for security.
    """
    if request.method == "POST":
        email = request.form["email"]
        password = request.form["password"]
        first_name = request.form["first_name"]
        last_name = request.form["last_name"]
        address = request.form["address"]
        phone = request.form["phone"]
        error = None

        if not email:
            error = "E-mail is required."
        elif not password:
            error = "Password is required."
        elif len(password) < 6:
            error = "Password needs to be more than 6 characters"
        elif not first_name:
            error = "first_name is required."
        elif not last_name:
            error = "last_name is required."
        elif not address:
            error = "address is required."
        elif (Customer.objects(email=email).first() is not None):
            error = "E-mail {0} is already registered.".format(email)

        try:
            if error is None:
                # the name is available, store it in the database and go to
                # the login page
                Customer(first_name=first_name,
                         last_name=last_name,
                         address=address,
                         email=email,
                         password=generate_password_hash(password),
                         phone=phone,
                         customer_since=datetime.datetime.utcnow(),
                         orders=[]).save()

            return redirect(url_for("auth.login"))

        except mongoengine.errors.ValidationError as ex:
            error = ex.errors

        flash(error)

    return render_template("auth/register.html")
예제 #5
0
def purchase_books():
    customer = Customer.objects(id=session.get("user_id")).first()
    if session['order_id']:
        order = Order.objects(id=session.get("order_id")).first()
        if len(order.books) < 1:
            flash("Please add some book to cart first")
            return redirect(url_for('bookstore.index'))
    else:
        flash("Please add some book to cart first")
        return redirect(url_for('bookstore.index'))
    customer.orders.append(order)
    customer.save()
    flash("Order complete. The order ID is {}".format(order.id))
    session['order_id'] = None
    return redirect(url_for('bookstore.index'))
예제 #6
0
def test_valid_data_entry(app):
    book_input = Book(title="Test book title",
                      isbn="Test12345",
                      author="Test author",
                      price="123",
                      published=datetime.datetime.utcnow(),
                      publisher="Test company")
    book_input.save()

    # verify book is successfully saved and able to be retrieved and their values match
    book_saved = Book.objects(title=book_input.title).first()
    assert book_saved.title == book_input.title
    assert book_saved.isbn == book_input.isbn
    assert book_saved.author == book_input.author
    assert book_saved.price == book_input.price
    assert book_saved.published.strftime(
        "%m/%d/%Y, %H:%M:%S") == book_input.published.strftime(
            "%m/%d/%Y, %H:%M:%S")
    assert book_saved.publisher == book_input.publisher

    # verify book can be retrieved by isbn
    book_saved = Book.objects(isbn=book_input.isbn).first()
    assert book_saved.title == book_input.title
    assert book_saved.isbn == book_input.isbn
    assert book_saved.author == book_input.author
    assert book_saved.price == book_input.price
    assert book_saved.published.strftime(
        "%m/%d/%Y, %H:%M:%S") == book_input.published.strftime(
            "%m/%d/%Y, %H:%M:%S")
    assert book_saved.publisher == book_input.publisher

    # verify the book can be ordered by a customer
    sample_customer = Customer.objects.first()

    order = Order(customer_name="{} {}".format(sample_customer.first_name,
                                               sample_customer.last_name),
                  books=[book_saved.id],
                  shipping_address=sample_customer.address,
                  total_price=book_saved.price,
                  order_status="processing",
                  order_date=datetime.datetime.utcnow()).save()
    sample_customer.orders.append(order.id)
    sample_customer.save()

    # Look for customer by order. Customer ID should match
    order_customer = Customer.objects(orders=order.id).first()
    assert order_customer.id == sample_customer.id
예제 #7
0
def create_order(copies, isbn):
    book = Book.objects(isbn=isbn).get()
    customer = Customer.objects(first_name="Kennth").get()
예제 #8
0
def cur_user_info(id):
    customer = Customer.objects(id=id).first()
    return render_template('bookstore/order.html', orders=customer.orders)