Exemplo n.º 1
0
def add_popular_category(current_user):
    if isAdmin(current_user):

        if 'file' not in request.files:
            return "No file part", 205
        file = request.files["file"]
        popular_category_name = request.form['name']
        if file.filename == "":
            return "No images selected", 205
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            if os.path.exists("images/popular_categories/" +
                              str(file.filename)):
                os.remove("images/popular_categories/" + str(file.filename))
            file.save(
                os.path.join(app.config["POPULAR_CATEGORIES"], file.filename))

            db = mysql_db.get_db()
            cursor = db.cursor()

            cursor.execute(
                "INSERT INTO popular_categories (name, image) VALUES(%s, %s) ",
                (popular_category_name, file.filename))
            db.commit()
            # print("File uploaded: " + filename + " to test_images/profile_photos")
            return jsonify({"message": "Added"}), 200
    else:
        return jsonify({"message": "Not authorized"}), 401
Exemplo n.º 2
0
def edit_popular_category(current_user):
    if isAdmin(current_user):
        if 'file' not in request.files:
            return "No file part found", 205
        file = request.files['file']
        popular_category_name = request.form['name']
        id = request.form['id']
        if file.filename == "":
            return "No images selected", 205
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            if os.path.exists("images/popular_categories/" +
                              str(file.filename)):
                os.remove("images/popular_categories/" + str(file.filename))

            # Remove old image
            db = mysql_db.get_db()
            cursor = db.cursor()
            cursor.execute("SELECT image FROM popular_categories WHERE id=%s",
                           (id, ))
            old_name = cursor.fetchone()
            try:
                os.remove("images/popular_categories/" + str(old_name))
            except FileNotFoundError as fne:
                print(fne)
            cursor.execute(
                "UPDATE popular_categories SET name=%s, image=%s WHERE id=%s",
                (popular_category_name, str(file.filename), id))
            file.save(
                os.path.join(app.config["POPULAR_CATEGORIES"], file.filename))
            db.commit()
            return jsonify({"message": "Edited"}), 200

    else:
        return jsonify({"message": "Not authorized"}), 401
Exemplo n.º 3
0
def confirm_reset_password_token(token):
    try:
        email = confirm_token(token)
    except:
        return jsonify({"message": "Expired or invalid link"}), 401

    if email:
        db = mysql_db.get_db()
        cursor = db.cursor()
        cursor.execute("SELECT * FROM users WHERE email=%s", (email, ))
        user = cursor.fetchone()
        temp_pass = str(uuid4())[:8]
        user['password'] = generate_password_hash(temp_pass, method='sha256')
        user['password_reset'] = True
        cursor.execute(
            "UPDATE users SET password_reset=%(password_reset)s, password=%(password)s WHERE email=%(email)s",
            user)
        db.commit()
        return render_template('reset_password.html',
                               url=url_for('index'),
                               success=True,
                               password=temp_pass)

    else:
        return render_template('reset_password.html',
                               url=url_for('index'),
                               success=False)
Exemplo n.º 4
0
def confirm_email(token):
    try:
        email = confirm_token(token)
    except:
        return jsonify({"message": "Invalid token"})

    if email:
        db = mysql_db.get_db()
        cursor = db.cursor()
        cursor.execute("SELECT * FROM users WHERE email=%s", (email, ))
        user = cursor.fetchone()
        if user['confirmed']:
            return render_template('email_confirmed.html',
                                   url=url_for('index'),
                                   success=False), 201
        user['confirmed'] = True
        user['confirmed_on'] = datetime.datetime.now()
        cursor.execute(
            "UPDATE users SET confirmed=%(confirmed)s, confirmed_on=%(confirmed_on)s WHERE email=%(email)s",
            user)
        db.commit()
        return render_template('email_confirmed.html',
                               url=url_for('index'),
                               success=True), 201
    else:
        return render_template('email_confirmed.html',
                               url=url_for('index'),
                               failed=True), 404
Exemplo n.º 5
0
def login():
    auth = request.get_json()
    cursor = mysql_db.get_db().cursor()
    cursor.execute("SELECT * FROM users WHERE username=%(username)s", auth)
    customer = cursor.fetchone()

    if not customer:
        return jsonify({"message": "Invalid credentials"}), 401

    if check_password_hash(customer.get('password'), auth['password']):
        token = jwt.encode(
            {
                'id': customer.get('id'),
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(hours=12)
            }, app.config['SECRET_KEY'], 'HS256')
        response = make_response("Verified", 200)
        # Check if cookie with token exists
        get_cookie = request.cookies.get('_tkws')

        if not get_cookie:
            response.set_cookie('_tkws',
                                encrypt_jwt(token),
                                max_age=60 * 60 * 13), 200
        return response

    return make_response("Could not verify", 401,
                         {"WWW-Authenticate": "Basic realm='Login required!'"})
Exemplo n.º 6
0
def customer_registration():
    data = request.get_json()
    hashed_password = generate_password_hash(data['password'], method='sha256')
    db = mysql_db.get_db()
    cursor = db.cursor()
    data['password'] = hashed_password
    #
    data['date_of_birth'] = datetime.datetime.strptime(
        data['date_of_birth'][:-5],
        "%Y-%m-%dT%H:%M:%S") + datetime.timedelta(hours=1)
    data['registration_date'] = datetime.datetime.now()
    data['admin'] = False
    data['image'] = "no_picture.png"
    token = generate_confirmation_token(data['email'])
    confirm_url = url_for("customer.confirm_email",
                          token=token,
                          _external=True)
    html = render_template('email_confirmation.html',
                           confirm_url=confirm_url,
                           name=data['first_name'])
    subject = "WebShop - Email confirmation"
    send_email(data['email'], subject, html)

    cursor.execute(
        "INSERT INTO users (email, username, password, first_name, last_name, gender, date_of_birth, registration_date, admin, image) VALUES(%(email)s, %(username)s, %(password)s, %(first_name)s, %(last_name)s, %(gender)s, %(date_of_birth)s, %(registration_date)s, %(admin)s, %(image)s)",
        data)
    db.commit()
    return jsonify({
        "message":
        "A confirmation email has been sent to your email address"
    }), 201
Exemplo n.º 7
0
def edit_user_data(current_user):
    data = request.get_json()

    current_user['address_1'] = data['address_1']
    current_user['address_2'] = data['address_2']
    current_user['city'] = data['city']
    current_user['country'] = data['country']
    current_user['postal_code'] = data['postal_code']
    current_user['phone_number'] = data['phone_number']

    db = mysql_db.get_db()
    cursor = db.cursor()

    if data['email'] != current_user['email']:
        current_user['email'] = data['email']
        current_user['confirmed'] = False
        cursor.execute(
            "UPDATE users SET confirmed=%(confirmed)s, email=%(email)s,  address_1=%(address_1)s, address_2=%(address_2)s, city=%(city)s, country=%(country)s, postal_code=%(postal_code)s, phone_number=%(phone_number)s WHERE id=%(id)s",
            current_user)
        # Token for email confirmation
        token = generate_confirmation_token(data['email'])
        confirm_url = url_for("customer.confirm_email",
                              token=token,
                              _external=True)
        html = render_template('email_confirmation.html',
                               confirm_url=confirm_url,
                               name=data['first_name'])
        subject = "WebShop - Email address changed"
        send_email(data['email'], subject, html)
    else:
        cursor.execute(
            "UPDATE users SET address_1=%(address_1)s, address_2=%(address_2)s, city=%(city)s, country=%(country)s, postal_code=%(postal_code)s, phone_number=%(phone_number)s WHERE id=%(id)s",
            current_user)
    db.commit()
    return jsonify({"message": "Updated"}), 200
Exemplo n.º 8
0
def get_all_products():
    cursor = mysql_db.get_db().cursor()
    cursor.execute("SELECT * FROM products")
    products = cursor.fetchall()
    for i in products:
        i["created_at"] = i["created_at"].isoformat()
    return jsonify(products)
Exemplo n.º 9
0
def update_cart_item_quantity(current_user, id):
    db = mysql_db.get_db()
    cursor = db.cursor()
    cursor.execute("UPDATE cart_items SET quantity=%s WHERE id=%s",
                   (int(request.data), id))
    db.commit()
    return "", 200
Exemplo n.º 10
0
    def decorated(*args, **kwargs):
        token = None
        
        try:
            if request.cookies.get('_tkws'):
                token = request.cookies.get('_tkws')
                token = token.encode()
                try:
                    token = decrypt_jwt(token)
                except cryptography.fernet.InvalidToken:
                    return "Invalid Token", 205
        except KeyError:
            return "Could not authenticate", 205

            
        if not token:
            return jsonify({"message":'Missing token'}), 205
        try:
            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
            cursor = mysql_db.get_db().cursor()
            cursor.execute("SELECT * FROM users WHERE id=%s", (data['id'], ))
            current_user = cursor.fetchone()
            
        except jwt.ExpiredSignatureError:
            return jsonify({"message':'Expired or it's invalid token"}), 401
        return f(current_user, *args, **kwargs)
Exemplo n.º 11
0
def get_all_admins(current_user):
    if isAdmin(current_user
               ):  # returns True if user has attribute of admin(bool)==True
        db = mysql_db.get_db().cursor()
        db.execute("SELECT * FROM admins")
        admins = db.fetchall()
        return jsonify(admins), 200
    else:
        return jsonify({'message': 'Not verified'}), 401
Exemplo n.º 12
0
def get_admin_orders_by_status(current_user, status):
    if isAdmin(current_user):
        cursor = mysql_db.get_db().cursor()
        cursor.execute(
            "SELECT o.id, o.customer_id, o.order_status_code, o.order_date, SUM(oi.order_item_quantity) order_item_quantity, SUM(oi.order_item_price) total, u.username  FROM orders o INNER JOIN order_items oi ON o.id = oi.order_id INNER JOIN users u ON o.customer_id=u.id WHERE o.order_status_code=%s GROUP BY o.id",
            (status, ))
        orders = cursor.fetchall()
        return jsonify(orders)
    else:
        return jsonify({"message": "Not authorized"}), 401
Exemplo n.º 13
0
def stripe_pay():
    customer = stripe.Customer.create(email=request.form['stripeEmail'],
                                      source=request.form['stripeToken'])
    db = mysql_db.get_db()
    cursor = db.cursor()
    cursor.execute("SELECT * FROM users WHERE email=%s",
                   (request.form['stripeEmail']))
    customer_db = cursor.fetchone()
    if not customer_db:
        return "No user with email provided found", 205

    cursor.execute(
        "SELECT * FROM cart_items c LEFT JOIN products p ON c.product_id=p.id LEFT JOIN shopping_cart s ON c.shopping_cart_id=s.id WHERE s.customer_id=%s",
        (customer_db['id'], ))
    cart_items = cursor.fetchall()

    # Get amount to be charged
    total_price = 0
    for i in cart_items:
        total_price += (i["price"] * i["quantity"])

    charge = stripe.Charge.create(customer=customer.id,
                                  amount=int(total_price * 100),
                                  currency='usd',
                                  description=customer_db["username"] +
                                  " cart items")

    cursor.execute("SELECT id FROM shopping_cart WHERE customer_id=%s",
                   (customer_db['id']))
    shopping_cart_id = cursor.fetchone()
    cursor.execute("DELETE FROM cart_items WHERE shopping_cart_id=%s",
                   (int(shopping_cart_id['id'])))
    cursor.execute(
        "INSERT INTO orders (customer_id, order_status_code) VALUES (%s, %s)",
        (customer_db['id'], 1))
    db.commit()

    cursor.execute(
        "SELECT * FROM orders WHERE customer_id=%s ORDER BY orders.order_date DESC",
        (customer_db['id']))
    order = cursor.fetchone()
    cursor.execute(
        "INSERT INTO invoices (order_id, invoice_desc) VALUES (%s, %s)",
        (order['id'],
         str(customer_db['first_name'] + " " + customer_db['last_name'])))
    for i in cart_items:
        cursor.execute(
            "INSERT INTO order_items (product_id, order_id, order_item_quantity, order_item_price) VALUES (%s, %s, %s, %s)",
            (i['product_id'], order['id'], i['quantity'], i['price']))

    # TODO - Place order

    db.commit()

    return redirect(url_for('index'))
Exemplo n.º 14
0
def edit_category(current_user, id):
    if isAdmin(current_user):
        data = dict(request.json)
        db = mysql_db.get_db()
        cursor = db.cursor()
        cursor.execute("UPDATE categories SET category_name=%s WHERE id=%s",
                       (data['category_name'], id))
        db.commit()
        return jsonify({"messsage": "Category name updated"}), 200
    else:
        return jsonify({"message": "Not authorized"}), 401
Exemplo n.º 15
0
def add_category(current_user):
    if isAdmin(current_user):
        data = dict(request.json)
        db = mysql_db.get_db()
        cursor = db.cursor()
        cursor.execute("INSERT INTO categories VALUES (0, %s)",
                       data['category_name'])
        db.commit()
        return jsonify({"message": "Category added"}), 200
    else:
        return jsonify({"message": "Not authorized"}), 401
Exemplo n.º 16
0
def add_subcategory(current_user):
    if isAdmin(current_user):
        data = dict(request.json)
        db = mysql_db.get_db()
        cursor = db.cursor()
        cursor.execute(
            "INSERT INTO sub_categories (category_id, sub_category_name) VALUES (%(category_id)s, %(sub_category_name)s)",
            data)
        db.commit()
        return jsonify({"message": "Category added"}), 200
    else:
        return jsonify({"message": "Not authorized"}), 401
Exemplo n.º 17
0
def search(params):
   cursor = mysql_db.get_db().cursor()
   query = "SELECT * FROM products WHERE name LIKE '%" + params + "%'"
   cursor.execute(query)
   search_result = cursor.fetchall()
   # count = len(search_result)
   # if len(params) <= 3: # If search params is les than 3 characters, return quarter of search results number
      
   #    return jsonify(search_result[:round(count/4)])
   if not search_result:
      return "", 205
   return jsonify(search_result)
Exemplo n.º 18
0
def delete_popular_category(current_user, id):
    if isAdmin(current_user):
        db = mysql_db.get_db()
        cursor = db.cursor()
        cursor.execute("SELECT * FROM popular_categories WHERE id=%s", (id, ))
        cat = cursor.fetchone()
        try:
            os.remove("images/popular_categories/" + str(cat['image']))
        except FileNotFoundError as fne:
            print(fne)
        cursor.execute("DELETE FROM popular_categories WHERE id=%s", (id, ))
        db.commit()
        return jsonify({"message": "Deleted"})
Exemplo n.º 19
0
def get_cart_items(current_user):
    if current_user:
        cursor = mysql_db.get_db().cursor()
        cursor.execute(
            "SELECT * FROM cart_items c LEFT JOIN products p ON c.product_id=p.id LEFT JOIN shopping_cart s ON c.shopping_cart_id=s.id WHERE s.customer_id=%s",
            (current_user['id'], ))
        cart_items = cursor.fetchall()

        for i in cart_items:
            i["product_id"] = i["p.id"]
            del i["customer_id"], i["shopping_cart_id"], i["s.id"], i["p.id"]
        return jsonify(cart_items)
    else:
        return "Not authenticated", 401
Exemplo n.º 20
0
def get_orders(current_user):
    db = mysql_db.get_db()
    cursor = db.cursor()
    cursor.execute(
        "SELECT o.id, o.order_date, o.order_status_code, p.name, oi.order_item_quantity, oi.order_item_price FROM order_items oi LEFT JOIN orders o ON oi.order_id=o.id LEFT JOIN products p ON oi.product_id=p.id WHERE o.customer_id=%s ORDER BY o.order_date DESC",
        (current_user['id']))
    orders = cursor.fetchall()
    sorted_orders = sorted(orders, key=operator.itemgetter('id'))

    list_orders = []
    for key, group in itertools.groupby(sorted_orders, key=lambda x: x['id']):
        list_orders.append(list(group))

    return jsonify(list_orders)
Exemplo n.º 21
0
def change_password(current_user):
    data = dict(request.json)
    db = mysql_db.get_db()
    cursor = db.cursor()
    cursor.execute("SELECT * FROM users WHERE id=%s", (current_user['id'], ))
    user = cursor.fetchone()
    user["password"] = generate_password_hash(data["newPass"], method='sha256')

    user["password_reset"] = False
    cursor.execute(
        "UPDATE users SET password=%(password)s, password_reset=%(password_reset)s WHERE email=%(email)s",
        user)
    db.commit()
    return jsonify({"message": "Password successfully changed"}), 200
Exemplo n.º 22
0
def add_item_to_cart(current_user, id):
    db = mysql_db.get_db()
    cursor = db.cursor()
    cursor.execute(
        "SELECT customer_id, id FROM shopping_cart WHERE customer_id=%s",
        (current_user['id'], ))
    hasCart = cursor.fetchone()
    cursor.execute("SELECT id FROM products WHERE id=%s", (id, ))
    product = cursor.fetchone()
    try:
        quantity = int(request.data)
    except TypeError:
        return "", 205
    if hasCart:
        data = {
            "product_id": product['id'],
            "shopping_cart_id": hasCart["id"],
            "created_at": datetime.datetime.now(),
            "quantity": quantity
        }
        cursor.execute(
            "INSERT INTO cart_items (product_id, shopping_cart_id, created_at, quantity) VALUES (%(product_id)s, %(shopping_cart_id)s, %(created_at)s, %(quantity)s)",
            data)
        db.commit()

        return jsonify({"message": "Added to cart"}), 200
    else:
        cursor.execute(
            "INSERT INTO shopping_cart (customer_id, created_at) VALUES (%s, %s)",
            (current_user['id'], datetime.datetime.now()))
        db.commit()
        cursor.execute(
            "SELECT customer_id, id FROM shopping_cart WHERE customer_id=%s",
            (current_user['id'], ))
        hasCart = cursor.fetchone()
        data = {
            "product_id": product['id'],
            "shopping_cart_id": hasCart["id"],
            "created_at": datetime.datetime.now(),
            "quantity": quantity
        }

        cursor.execute(
            "INSERT INTO cart_items (product_id, shopping_cart_id, created_at, quantity) VALUES (%(product_id)s, %(shopping_cart_id)s, %(created_at)s, %(quantity)s)",
            data)
        db.commit()
        return jsonify({"message": "Added to cart"}), 200
Exemplo n.º 23
0
def delete_profile_picture(current_user):
    if os.path.exists("images/profile_images/" + str(current_user['image'])):
        try:
            if not str(current_user['image']) == "no_image.png":
                os.remove("images/profile_images/" +
                          str(current_user['image']))
        except PermissionError:
            return "Error", 404
        current_user['image'] = ""
        db = mysql_db.get_db()
        cursor = db.cursor()
        cursor.execute("UPDATE users SET image=%(image)s WHERE id=%(id)s",
                       current_user)
        db.commit()
        return "", 200
    else:
        return "", 400
Exemplo n.º 24
0
def reset_password():
    data = dict(request.json)
    cursor = mysql_db.get_db().cursor()
    cursor.execute("SELECT * FROM users WHERE email=%s", (data['email'], ))
    user = cursor.fetchone()
    if user:
        token = generate_confirmation_token(user['email'])
        reset_url = url_for("customer.confirm_reset_password_token",
                            token=token,
                            _external=True)
        html = render_template("reset_password_email.html",
                               reset_url=reset_url)
        subject = "WebShop - Account Recovery"
        send_email(user['email'], subject, html)
        return jsonify({
            "message":
            "An email with reset token has been sent to email address"
        }), 200
    if not user:
        return jsonify({"message": "No user found with email provided"}), 200
Exemplo n.º 25
0
def upload_profile_picture(current_user):
    if 'file' not in request.files:
        return "No file part", 205
    file = request.files["file"]
    if file.filename == "":
        return "No images selected", 205
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        if os.path.exists("images/profile_images/" + str(current_user['image'])
                          ) and current_user['image'] != "":
            os.remove("images/profile_images/" + str(current_user['image']))
        file.save(os.path.join(app.config["PROFILE_IMAGES"], file.filename))

        db = mysql_db.get_db()
        cursor = db.cursor()
        current_user['image'] = file.filename
        cursor.execute("UPDATE users SET image=%(image)s WHERE id=%(id)s",
                       current_user)
        db.commit()
        # print("File uploaded: " + filename + " to test_images/profile_photos")
        return filename, 200
Exemplo n.º 26
0
def get_one_category(id):
    cursor = mysql_db.get_db().cursor()
    cursor.execute("SELECT * FROM categories WHERE id=%s", (id, ))
    category = cursor.fetchone()
    return jsonify(category)
Exemplo n.º 27
0
def get_categories():
    cursor = mysql_db.get_db().cursor()
    cursor.execute("SELECT * FROM categories")
    categories = cursor.fetchall()
    return jsonify(categories)
Exemplo n.º 28
0
def get_daily_deals_products():
   cursor = mysql_db.get_db().cursor()
   cursor.execute("SELECT p.id, p.category_id, p.sub_category_id, p.name, p.price, p.color, p.size, p.desc, p.image, p.created_at FROM daily_deals d LEFT JOIN products p ON p.id = d.product_id")
   daily_deals = cursor.fetchall()
   return jsonify(daily_deals)
Exemplo n.º 29
0
def get_similar_products(id):
   cursor = mysql_db.get_db().cursor()
   cursor.execute("SELECT * FROM products WHERE sub_category_id=%s", (id, ))
   products = cursor.fetchmany(4)
   return jsonify(products)
Exemplo n.º 30
0
def get_one_product(id):
    cursor = mysql_db.get_db().cursor()
    cursor.execute("SELECT * FROM products WHERE id=%s", (id, ))
    product = cursor.fetchone()
    product["created_at"] = product["created_at"].isoformat()
    return jsonify(product)