def get(self, user_id): try: identity = str(current_user.id) has_account = True except: identity = 'none' has_account = False if identity != user_id: # logging log_type = "Unauthorized Access" if has_account: log_details = f"A user with the username {current_user.get_username()} tried to add a new product." else: log_details = "An unknown user tried to change status of a product." Logging(log_type, log_details) response = jsonify(data="You do not have authorized access to perform this action.") response.status_code = 401 return response else: conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) conn.row_factory = sqlite3.Row c = conn.cursor() c.execute("SELECT * FROM vouchers WHERE user_id = ?", (user_id,)) conn.commit() vouchers = [dict(row) for row in c.fetchall()] conn.close() return jsonify(data=vouchers)
def put(self): try: admin = current_user.get_admin() has_account = True except: admin = 'n' has_account = False if admin == "y": request_json_data = request.get_json(force=True) product_name = request_json_data['product_name'] product_status = request_json_data['product_status'].lower() conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() # validate product name, check if it is in database c.execute("SELECT * FROM products WHERE name = ?", (product_name, )) if not c.fetchone(): response = jsonify( f"Invalid product name, product name {product_name} not found." ) response.status_code = 400 return response # validate product status if product_status not in ["inactive", "active"]: response = jsonify("Invalid product status") response.status_code = 400 return response c.execute("UPDATE products SET status = ? WHERE name = ?", (product_status, product_name)) conn.commit() return jsonify(data="Success") else: # logging log_type = "Unauthorized Access" if has_account: log_details = f"A user with the username {current_user.get_username()} tried to change status of a product." else: log_details = "An unknown user tried to change status of a product." Logging(log_type, log_details) response = jsonify( data="You do not have authorized access to perform this action." ) response.status_code = 401 return response
def put(self): try: identity = current_user.get_username() admin = current_user.get_admin() has_account = True except: identity = None admin = 'n' has_account = False if admin == "y": conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() request_json_data = request.get_json(force=True) voucher_name = request_json_data['voucher_name'] voucher_status = request_json_data['voucher_status'].lower() # validate voucher_name c.execute("SELECT * FROM vouchers WHERE title=?", (voucher_name, )) if not c.fetchone(): response = jsonify(data="No such Voucher Title.") response.status_code = 400 return response # validate voucher_status if voucher_status not in ["active", "inactive"]: response = jsonify(data="Invalid voucher status.") response.status_code = 400 return response # prevent sql injection c.execute("UPDATE vouchers SET status = ? WHERE title = ?", ( voucher_status, voucher_name, )) conn.commit() return jsonify(data="Success. Voucher Status Updated.") else: # logging log_type = "Unauthorized Access" if has_account: log_details = f"A user with the username {identity} tried to change status of voucher." else: log_details = "An unknown user tried to change status of a voucher." Logging(log_type, log_details) response = jsonify(data="Unauthorized access") response.status_code = 401 return response
def signin(): # Checks if user is logged in try: current_user.get_username() return redirect(url_for('main.home')) except: user = None signin = SignIn(request.form) if request.method == "POST" and signin.validate(): pw_hash = hashlib.sha512(signin.password.data.encode()).hexdigest() conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM users WHERE username=?", (signin.username.data, )) user = c.fetchone() # Patched code: Gives ambiguous error message if user is None: flash("Incorrect username or password") else: if user[3] == pw_hash: # Generate OTP digits = "0123456789" otp = "" for i in range(8): otp += digits[math.floor(random.random() * 10)] s = Serializer('3d6f45a5fc12445dbac2f59c3b6c7cb1', 120) # Store username and OTP in token for authentication token = s.dumps([user[1], otp]).decode('UTF-8') # Send Email to user mail.send_message( 'Indirect Home Gym Sign In', sender='*****@*****.**', recipients=[user[2]], body= "Hi {},\n\nYour 8 digit OTP is {}. It will expire in 2 minutes.\n\n If you did not request for this OTP, please reset your password as soon as possible.\n\nCheers!\nIndirect Home Gym Team" .format(user[1], otp)) return redirect(url_for('user.signInOTP', token=token)) else: username = signin.username.data details = f"Failed login attempt with the username of {username}." Loggingtype = "Login" Logging(Loggingtype, details) user = None flash("Incorrect username or password") conn.close() return render_template("user/SignIn.html", form=signin, user=user)
def put(self, user_id): try: identity = str(current_user.id) has_account = True except: identity = None has_account = False if user_id == identity: import datetime request_json_data = request.get_json(force=True) code = request_json_data["code"] used_date = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S") conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT * FROM vouchers WHERE code = ? AND status = 'unused'", (code,)) if c.fetchone(): c.execute("UPDATE vouchers SET status = 'used', used_date = ? WHERE code = ?", (used_date, code,)) conn.commit() conn.close() return jsonify(data=f"Voucher with the code {code} from username {user_id} has been used.") else: c.execute("SELECT * FROM vouchers WHERE code=? AND user_id=0", (code,)) if c.fetchone(): conn.commit() conn.close() return jsonify(data="This is a general voucher") else: conn.commit() conn.close() return jsonify(data=f"Voucher with the code {code} from username {user_id} has already been used.") else: # logging log_type = "Unauthorized Access" if has_account: log_details = f"A user with the username {current_user.get_username()} tried to change status of a product." else: log_details = "An unknown user tried to change status of a product." Logging(log_type, log_details) response = jsonify(data="You do not have authorized access to perform this action.") response.status_code = 401 return response
def post(self, user_id): try: admin = current_user.get_admin() has_account = True except: admin = 'n' has_account = False if admin == 'y': conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() request_json_data = request.get_json(force=True) voucher_title = request_json_data["title"] # Validate if voucher code is in database while True: voucher_code = get_random_alphanumeric_string(8) c.execute("SELECT * FROM vouchers WHERE code=?", (voucher_code,)) if not c.fetchone(): break voucher_image = "" voucher_description = request_json_data["description"] voucher_amount = request_json_data["amount"] voucher_status = "unused" used_date = "" c.execute("INSERT INTO vouchers VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (voucher_title, voucher_code, voucher_description, voucher_image, voucher_amount, voucher_status, used_date, user_id)) conn.commit() conn.close() return jsonify(data="Voucher created with user id of {}".format(user_id)) else: # logging log_type = "Unauthorized Access" if has_account: log_details = f"A user with the username {current_user.get_username()} tried to add a new product." else: log_details = "An unknown user tried to change status of a product." Logging(log_type, log_details) response = jsonify(data="You do not have authorized access to perform this action.") response.status_code = 401 return response
def post(self): try: admin = current_user.get_admin() has_account = True except: admin = 'n' has_account = False if admin == "y": product_name = request.form.get('productNameInput') product_img = request.files.get('productImage') product_description = request.form.get('productDescription') product_selling_price = request.form.get( 'productSellingPriceInput') product_cost_price = request.form.get('productCostPriceInput') product_category = request.form.get('productCategory') product_stock = request.form.get('productStock') # validate input to not be none if None in { product_name, product_img, product_description, product_selling_price, product_cost_price, product_category }: response = jsonify(data="Missing fields.") response.status_code = 400 return response # validate selling price and cost price try: product_selling_price = float(product_selling_price) product_cost_price = float(product_cost_price) if product_selling_price < 0 or product_cost_price < 0: response = jsonify( data= "Either selling price or cost price is less than 0.") response.status_code = 400 return response if product_selling_price < product_cost_price: response = jsonify( data="Selling price is less than cost price.") response.status_code = 400 return response except: response = jsonify( data= "Either selling price or cost price is not an integer or float." ) response.status_code = 400 return response # validate stock if not product_stock.isdigit(): response = jsonify( data="Stock amount is not an positive integer.") response.status_code = 400 return response elif product_stock == "0": response = jsonify(data="Stock amount cannot be 0.") response.status_code = 400 return response else: product_stock = int(product_stock) filename = product_img.filename # validate filename if filename[-3:] not in ["png", "jpg", "peg"]: response = jsonify(data="Invalid file type.") response.status_code = 400 return response filepath = 'products/' + filename product_img.save( os.path.join(file_directory, 'flaskr/static/img/products', filename)) conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute( "SELECT product_id from products where product_id = (select max(product_id) from products)" ) product_id = c.fetchone()[0] + 1 c.execute( "INSERT INTO products VALUES (?, ?, ?, ?, ?, ?, ?,'active', ?)", (product_id, product_name, filepath, product_description, product_selling_price, product_cost_price, product_category, product_stock)) conn.commit() if request.user_agent.string[:14] != "PostmanRuntime": return redirect(url_for('admin.show_product')) return jsonify(data="Success") else: # logging log_type = "Unauthorized Access" if has_account: log_details = f"A user with the username {current_user.get_username()} tried to add a new product." else: log_details = "An unknown user tried to change status of a product." Logging(log_type, log_details) response = jsonify( data="You do not have authorized access to perform this action." ) response.status_code = 401 return response
def post(self): try: identity = current_user.get_username() admin = current_user.get_admin() has_account = True except: identity = None admin = 'n' has_account = False if admin == "y": voucher_title = request.form.get('voucherNameInput') voucher_code = request.form.get('voucherCode') voucher_img = request.files.get('voucherImage') voucher_description = request.form.get('voucherDescription') voucher_amount = request.form.get('voucherAmountInput') conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() # validate if voucher title is in database c.execute("SELECT * FROM vouchers WHERE title=?", (voucher_title, )) if c.fetchone(): response = jsonify(data="Voucher Title is used.") response.status_code = 400 return response # validate if voucher code is in database c.execute("SELECT * FROM vouchers WHERE code=?", (voucher_code, )) if c.fetchone(): response = jsonify(data="Voucher Code is used.") response.status_code = 400 return response # validate if voucher image is in form try: filename = voucher_img.filename filepath = 'vouchers/' + filename voucher_img.save( os.path.join(file_directory, 'flaskr/static/img', filepath)) except PermissionError: response = jsonify(data="No Voucher Image in form.") response.status_code = 400 return response # prevent sql injection c.execute( "INSERT INTO vouchers VALUES (?, ?, ?, ?, ?, 'active', '', 0)", (voucher_title, voucher_code, voucher_description, filepath, voucher_amount)) conn.commit() if request.user_agent.string[:14] != "PostmanRuntime": return redirect(url_for('admin.show_voucher')) return jsonify(data="Success. Voucher Created.") else: # logging log_type = "Unauthorized Access" if has_account: log_details = f"A user with the username {identity} tried to add a new voucher." else: log_details = f"Am unknown user tried to add a new voucher." Logging(log_type, log_details) response = jsonify( data="You do not have authorized access to perform this action." ) response.status_code = 401 return response
def checkout(): try: username = current_user.get_username() user = current_user user_id = session["_user_id"] except: user = None user_id = None error = "" # Check if cart is in session or empty if 'cart' in session: cart = session['cart'] if not cart: return redirect(url_for('main.home')) else: return redirect(url_for('main.home')) # if user is not signin, will redirect to ask to signin if not user: return redirect(url_for('user.signin')) else: # getting card from existing user conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute( "SELECT credit_card_number from paymentdetails where user_id=?", (user_id, )) result = c.fetchone() if result: e1 = pyffx.Integer( b'12376987ca98sbdacsbjkdwd898216jasdnsd98213912', length=16) credit_card_number = str(e1.decrypt(result[0])) sliced_credit_card_number = "XXXX-" * 3 + credit_card_number[-4:] else: return redirect(url_for('user.Profile')) # payment if request.method == "POST" and user is not None: month = request.form.get('Expiry_DateM') year = request.form.get('Expiry_DateY') cvv = request.form.get('CVV') # validate credit card details conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute( "SELECT expiry, cvv, credit_card_number from paymentdetails where user_id=?", (user_id, )) result = c.fetchone() valid_year, valid_month, valid_day = result[0].split('-') e2 = pyffx.Integer(b'12376987ca98sbdacsbjkdwd898216jasdnsd98213912', length=len(str(result[1]))) valid_cvv = e2.decrypt(result[1]) if int(year) == int(valid_year[2:]) and int(month) == int( valid_month) and str(cvv) == str(valid_cvv): # successful payment c.execute("select max(order_id) from orders") try: order_id = c.fetchone()[0] + 1 except TypeError: order_id = 1 user_id = session["_user_id"] voucher_code = session["voucher"] date_of_purchase = datetime.now() total_cost = session["amount"] c.execute("INSERT into orders values (?, ?, ?, ?, ?)", (order_id, user_id, voucher_code, date_of_purchase, total_cost)) for item in session['cart']: c.execute("INSERT into order_details values (?,?)", (order_id, item[0])) conn.commit() conn.close() # uses the voucher (should only use it after payment is successful) if '_user_id' in session and 'voucher' in session and session[ 'voucher'] != '': cookie = request.headers['cookie'] csrf_token = request.form.get('csrf_token') headers = {'cookie': cookie, 'X-CSRF-Token': csrf_token} url = "http://localhost:5000/api/userVoucher/" + session[ "_user_id"] response = requests.put(url, json={"code": session["voucher"]}, headers=headers) data = response.json()["data"] if data == "This is a general voucher": data = "" else: data = "" # deletes voucher and cart session del session['cart'] if 'voucher' in session: del session['voucher'] return render_template("shopping/Thankyou.html", data=data, user=user) else: # unsuccessful payment details = f"Failed transaction with the username of {username}." Loggingtype = "Transaction" Logging(Loggingtype, details) error = "Invalid Payment Details" # checkout details cart = session['cart'] voucher = session['voucher'] conn = sqlite3.connect(os.path.join(file_directory, "storage.db")) c = conn.cursor() c.execute("SELECT amount from vouchers where code = ?", (voucher, )) try: voucher_cost = c.fetchone()[0] except TypeError: voucher_cost = 0 subtotal = session['subtotal'] amount = session['amount'] order_details = { 'cart': cart, 'voucher': voucher, 'voucher_cost': voucher_cost, 'subtotal': subtotal, 'total': amount } return render_template("shopping/Checkout.html", user=user, credit_card_number=sliced_credit_card_number, error_message=error, order_details=order_details)
def handle_404(error): path_info = request.url details = f"Attempted to access invalid webpage via {path_info}" Loggingtype = "URL Logging" Logging(Loggingtype, details) return render_template('main/Error404.html'), 404