225 lines
8.1 KiB
Python
225 lines
8.1 KiB
Python
from flask import Flask, render_template, make_response, request, redirect, url_for, session, abort
|
|
from pprint import pprint
|
|
import mysql.connector
|
|
import configparser
|
|
import os.path
|
|
|
|
config = configparser.ConfigParser()
|
|
MOBILES = ["android", "iphone", "blackberry"]
|
|
|
|
try:
|
|
config.read(".config")
|
|
except Exception as E:
|
|
print(E)
|
|
|
|
def dbConnect():
|
|
mydb = mysql.connector.connect(
|
|
host=config["mysql"]["Host"],
|
|
user=config["mysql"]["Username"],
|
|
passwd=config["mysql"]["Password"],
|
|
database=config["mysql"]["Database"]
|
|
)
|
|
return mydb
|
|
|
|
|
|
def doesTableExist():
|
|
mydb = dbConnect()
|
|
mycursor = mydb.cursor()
|
|
mycursor.execute('''SHOW TABLES''')
|
|
tables = mycursor.fetchall()
|
|
if len(tables) == 0:
|
|
mycursor.execute('''CREATE TABLE USERS (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255), password VARCHAR(255), admin BOOLEAN)''')
|
|
mycursor.execute('''CREATE TABLE LISTS (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))''')
|
|
mycursor.execute('''CREATE TABLE SHOPLIST (id INT AUTO_INCREMENT PRIMARY KEY, item VARCHAR(255), gotten BOOLEAN, user_id INT, list_id INT, FOREIGN KEY (`list_id`) REFERENCES `LISTS`(`id`), FOREIGN KEY (`user_id`) REFERENCES `USERS`(`id`)
|
|
ON DELETE CASCADE)''')
|
|
mycursor.execute('''CREATE TABLE USER_META (user_id INT, list_id INT, FOREIGN KEY (`list_id`) REFERENCES `LISTS`(`id`), FOREIGN KEY (`user_id`) REFERENCES `USERS`(`id`)
|
|
ON DELETE CASCADE)''')
|
|
mydb.close()
|
|
|
|
def runQuery(query, data=None):
|
|
mydb = dbConnect()
|
|
c = mydb.cursor()
|
|
if data is not None:
|
|
c.execute(query, data)
|
|
else:
|
|
c.execute(query)
|
|
if query.lower().startswith("select"):
|
|
ret = c.fetchall()
|
|
else:
|
|
ret = []
|
|
mydb.commit()
|
|
mydb.close()
|
|
return ret
|
|
|
|
def readFromDB():
|
|
# By default load all shopping lists the user is a part of (Most users will only have one so this this fine)
|
|
query = '''select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username, SHOPLIST.list_id from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id'''
|
|
return runQuery(query)
|
|
|
|
def insertToDB(data):
|
|
query = "INSERT INTO SHOPLIST (item, gotten, user_id) VALUES (%s, 0, %s)"
|
|
data = (data['item'], data['name'])
|
|
# print(query)
|
|
runQuery(query, data)
|
|
|
|
|
|
def deleteRow(rowID):
|
|
query = "DELETE FROM SHOPLIST WHERE id = %s"
|
|
data = (rowID, )
|
|
runQuery(query, data)
|
|
|
|
def getItem(rowID):
|
|
query = "UPDATE SHOPLIST set gotten = 1 where id = %s"
|
|
data = (rowID, )
|
|
runQuery(query, data)
|
|
|
|
def unGetItem(rowID):
|
|
query = "UPDATE SHOPLIST set gotten = 0 where id = %s"
|
|
data = (rowID, )
|
|
runQuery(query, data)
|
|
|
|
def get_users(username=None):
|
|
if username == None:
|
|
#return all users
|
|
query = "select username, admin, id from USERS"
|
|
return runQuery(query)
|
|
query = "select username, admin from USERS where username like %s"
|
|
data = (username, )
|
|
return runQuery(query, data)
|
|
|
|
def add_user(userData):
|
|
username = userData["username"]
|
|
password = userData["password"]
|
|
query = "insert into USERS (username, password, admin) values (%s, md5(%s), False)"
|
|
data = (username, password)
|
|
runQuery(query, data)
|
|
|
|
def update_pass(user_id, newpass):
|
|
query = "update USERS set password=md5(%s) where id=%s"
|
|
data = (newpass, user_id)
|
|
runQuery(query, data)
|
|
|
|
def get_items(user_id, list_id=None):
|
|
if list_id != None:
|
|
query = "select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id where USER_META.user_id = %s and SHOPLIST.list_id = %s"
|
|
data = (user_id, list_id)
|
|
return runQuery(query, data)
|
|
query = "select SHOPLIST.id, SHOPLIST.item, SHOPLIST.gotten, USERS.username from SHOPLIST inner join USERS on SHOPLIST.user_id = USERS.id inner join USER_META on SHOPLIST.list_id = USER_META.list_id where USER_META.user_id = %s"
|
|
data = (user_id,)
|
|
return runQuery(query, data)
|
|
|
|
def get_list_ids(user_id):
|
|
query = "select USER_META.list_id, LISTS.name from USER_META inner join LISTS on LISTS.id = USER_META.list_id where USER_META.user_id = %s"
|
|
data = (user_id,)
|
|
ret = runQuery(query, data)
|
|
return ret
|
|
|
|
app = Flask(__name__)
|
|
app.config["DEBUG"] = True
|
|
app.secret_key = b'*$#@U9423jr92jioJKL_)_;dasfj()12'
|
|
|
|
@app.route('/')
|
|
def index():
|
|
print(f"ID in session is: {session['active_id']}")
|
|
if session.get('id') is None:
|
|
data = {"title":"Login"}
|
|
return render_template("auth.html", data=data)
|
|
|
|
if session["active_id"] == "0":
|
|
print("Heres")
|
|
res = get_items(session["id"])
|
|
else:
|
|
res = get_items(session["id"], session["active_id"])
|
|
data = {"title": "Shopping List", "results": res, "session": session, "list_ids": session["list_ids"]}
|
|
#Store active list in the session
|
|
# try:
|
|
# if request.args["list"]:
|
|
# print(request.args["list"])
|
|
# res = get_items(session["id"], request.args["list"])
|
|
# else:
|
|
# res = get_items(session["id"])
|
|
# data = {"title": "Shopping List", "results": res, "username": session["username"], "list_ids": session["list_ids"]}
|
|
# except KeyError:
|
|
# #Get initial data, contains all lists the user is apart of unless list is defined
|
|
# res = get_items(session["id"])
|
|
# data = {"title": "Shopping List", "results": res, "username": session["username"], "list_ids": session["list_ids"]}
|
|
for device in MOBILES:
|
|
if device in request.user_agent.platform:
|
|
return render_template('mobile.html', data=data)
|
|
print(session["list_ids"])
|
|
return render_template('index.html', data=data)
|
|
|
|
@app.route('/post', methods=['POST'])
|
|
def handle_data():
|
|
print(request.form)
|
|
if "addValue" in request.form:
|
|
for x in request.form:
|
|
if request.form[x] == '':
|
|
return redirect(url_for('index'))
|
|
insertToDB({"item": request.form["item"], "name": session["id"]})
|
|
if "rem" in request.form:
|
|
deleteRow(request.form["rem"])
|
|
|
|
if "got" in request.form:
|
|
getItem(request.form["got"])
|
|
|
|
if "ungot" in request.form:
|
|
unGetItem(request.form["ungot"])
|
|
|
|
if "loginform" in request.form:
|
|
query = "select id, username, admin from USERS where username = %s and password = md5(%s)"
|
|
data = (request.form["username"].lower(), request.form["password"])
|
|
res = runQuery(query, data)
|
|
if len(res) != 0:
|
|
list_ids = get_list_ids(res[0][0])
|
|
session["id"] = res[0][0]
|
|
session["username"] = res[0][1]
|
|
session["isAdmin"] = res[0][2]
|
|
session["list_ids"] = list_ids
|
|
session["active_id"] = "0"
|
|
|
|
if "newuser" in request.form:
|
|
#first check if the user exists
|
|
usrCheck = get_users(request.form["username"])
|
|
print(usrCheck)
|
|
if len(usrCheck) != 0:
|
|
return "Username Exists"
|
|
userData = {"username": request.form["username"], "password": request.form["password"]}
|
|
add_user(userData)
|
|
return redirect(url_for("admin"))
|
|
|
|
if "newpass" in request.form:
|
|
user_id = request.form['updatepass']
|
|
newpass = request.form['newpass']
|
|
update_pass(user_id, newpass)
|
|
return redirect(url_for("admin"))
|
|
|
|
if "logout" in request.form:
|
|
session.clear()
|
|
|
|
if "changeList" in request.form:
|
|
pprint(request.form["changeList"])
|
|
if "list" in request.form:
|
|
print(f"Change session to {request.form['list']}")
|
|
session["active_id"] = request.form['list']
|
|
|
|
return redirect(url_for('index'))
|
|
|
|
@app.route("/admin")
|
|
def admin():
|
|
if session.get('id') is None:
|
|
data = {"title":"Login"}
|
|
return render_template("auth.html", data=data)
|
|
elif session.get('isAdmin') == 0:
|
|
return redirect(url_for("index"))
|
|
|
|
#get a list of users
|
|
userList = get_users()
|
|
data = {"users": userList}
|
|
|
|
return render_template("admin.html", data=data)
|
|
|
|
if __name__ == '__main__':
|
|
doesTableExist()
|
|
app.run(host="0.0.0.0")
|