Skip to content
Permalink
Browse files
Implemented a decorator function for protecting URL path routes and w…
…rote some other if-statement for validating users when making different HTTP requests with the help of cookie sessions.
  • Loading branch information
Prinex committed Nov 29, 2022
1 parent 2fe8400 commit 5ea77aaf9066f858c20d987ecd3bf9db8fd75478
Showing 1 changed file with 44 additions and 35 deletions.
@@ -1,18 +1,35 @@
import functools
from urllib import request
from .meta import *

import datetime
#--*
import bcrypt
#--*

#--*
# decorator function for protecting different routes
def login_required(view):
# accept and wrap a given view
@functools.wraps(view)
# can have 0 or >=1 arguments
def wrapped_view(*args, **kwargs):
# check if user has logged in the current session
if "user" not in flask.session:
flask.flash("You need to be logged in for this feature.")
return flask.redirect(flask.url_for("login"))
# return to the view function if yes
return view(*args, **kwargs)
# call the wrapped function
return wrapped_view
#--*

@app.route("/")
def index():
"""
Main Page.
"""

#Get data from the DB using meta function

rows = query_db("SELECT * FROM product")
app.logger.info(rows)

@@ -29,11 +46,9 @@ def products():
if theItem:

#We Do A Query for It
#itemQry = query_db(f"SELECT * FROM product WHERE id = ?",[theItem], one=True)

#--
theQry = "SELECT * FROM product WHERE id = ?"
args = (theItem)
args = (theItem,)
itemQry = query_db(theQry, args, True)

theQry1 = "SELECT * FROM review INNER JOIN user ON review.userID = user.id WHERE review.productID = ?;"
@@ -166,6 +181,7 @@ def create():
return flask.redirect(flask.url_for("login"))

@app.route("/user/<userId>/settings")
@login_required
def settings(userId):
"""
Update a users settings,
@@ -175,9 +191,13 @@ def settings(userId):
theQry = "Select * FROM User WHERE id = ?"
args = (userId,)
thisUser = query_db(theQry, args, one=True)
#--

if not thisUser:
# the user shouldn't be able to access other accounts' settings
if thisUser['id'] != flask.session['user']:
flask.flash("Access denied: Unauthorized access to another account")
return flask.redirect(flask.url_for("settings", userId=flask.session['user']))
#--
elif not thisUser:
flask.flash("No Such User")
return flask.redirect(flask.url_for("index"))

@@ -220,12 +240,11 @@ def updateUser(userId):
#--
theQry = "Select * FROM User WHERE id = ?"
args = (userId,)
thisUser = query_db(theQry, one=True)
thisUser = query_db(theQry, args, one=True)
#--

if not thisUser:
flask.flash("No Such User")
return flask.redirect(flask_url_for("index"))
return flask.redirect(flask.flask_url_for("index"))

#otherwise we want to do the checks
if flask.request.method == "POST":
@@ -249,10 +268,7 @@ def updateUser(userId):
app.logger.info("Mismatch")
flask.flash("Current Password is incorrect")
return flask.redirect(flask.url_for("settings",
userId = thisUser['id']))



userId = thisUser['id']))
flask.flash("Update Error")

return flask.redirect(flask.url_for("settings", userId=userId))
@@ -264,9 +280,17 @@ def updateUser(userId):
# ------------------------------------------

@app.route("/review/<userId>/<itemId>", methods=["GET", "POST"])
@login_required
def reviewItem(userId, itemId):
"""Add a Review"""

#--
theQry = "Select * FROM User WHERE id = ?"
args = (userId,)
thisUser = query_db(theQry, args, one=True)
if thisUser['id'] != flask.session['user']:
flask.flash("Access denied: Unauthorized access to another account")
return flask.redirect(flask.url_for("settings", userId=flask.session['user']))
#--
#Handle input
if flask.request.method == "POST":
reviewStars = flask.request.form.get("rating")
@@ -284,12 +308,7 @@ def reviewItem(userId, itemId):
app.logger.info("Update Existing")

#--
theSQL = """
UPDATE review
SET stars = ?
review = ?
WHERE
id = ?"""
theSQL = "UPDATE review SET stars = ?, review = ? WHERE id = ?"
args = (reviewStars, reviewComment, reviewId)
app.logger.debug("%s", theSQL)
write_db(theSQL, args)
@@ -315,7 +334,7 @@ def reviewItem(userId, itemId):
#--
theQry = "SELECT * FROM product WHERE id = ?;"
args = (itemId,)
item = query_db(theQry, one=True)
item = query_db(theQry, args, one=True)

theQry = "SELECT * FROM review WHERE userID = ? AND productID = ?;"
args = (userId, itemId)
@@ -337,14 +356,8 @@ def reviewItem(userId, itemId):


@app.route("/basket", methods=["GET","POST"])
@login_required
def basket():

#Check for user
if not flask.session["user"]:
flask.flash("You need to be logged in")
return flask.redirect(flask.url_for("index"))


theBasket = []
#Otherwise we need to work out the Basket
#Get it from the session
@@ -371,17 +384,13 @@ def basket():
total=totalPrice)

@app.route("/basket/payment", methods=["GET", "POST"])
@login_required
def pay():
"""
Fake paymeent.
YOU DO NOT NEED TO IMPLEMENT PAYMENT
"""

if not flask.session["user"]:
flask.flash("You need to be logged in")
return flask.redirect(flask.url_for("index"))

#Get the total cost
cost = flask.request.form.get("total")

@@ -405,7 +414,7 @@ def pay():
theQry = "INSERT INTO PURCHASE (userID, productID, date) VALUES (?, ?, ?)"
args = (theUser['id'], key, theDate)
app.logger.debug(theQry)
write_db(theQry, args, theDate)
write_db(theQry, args)
#--

#Clear the Session

0 comments on commit 5ea77aa

Please sign in to comment.