diff --git a/app.py b/app.py index 0eefa08..998d086 100644 --- a/app.py +++ b/app.py @@ -1,7 +1,32 @@ -from flask import Flask, render_template, request, jsonify -from services import Services -app = Flask("Project Candle") -services = Services() +from flask import Flask, render_template, request, jsonify, abort, redirect, url_for +from flask_login import LoginManager , login_required , UserMixin , login_user, current_user, logout_user +from forms import LoginForm +from services import Services, UserManager +from models import User +import sqlite3 +import re + +#Setup +app = Flask("Project Fish") +app.config.from_pyfile('config.py') +login_manager = LoginManager() +login_manager.login_view = "login" +login_manager.init_app(app) + +sqlpath="sqlite.db" +db = sqlite3.connect(sqlpath, check_same_thread=False) +services = Services(db) +usermanager = UserManager(db) + +def is_string_sanitized(data): + sanitized_string = re.sub('[^a-zA-Z0-9_@#$.\s]', '', data) + if len(data) != len(sanitized_string): + return False + return True + +@login_manager.user_loader +def load_user(user_id): + return usermanager.GetUserByID(user_id) @app.route('/') def index(): @@ -10,20 +35,42 @@ def index(): @app.route("/GetServices", methods=['GET', 'POST']) def GetServices(): nummer = (request.json)["nummer"] + if(not is_string_sanitized(nummer)): + return abort(401) if(nummer != None and nummer != ""): ser=services.GetServices(nummer) return jsonify(render_template("results.html", services=ser),) ser = services.GetAllServices() return render_template("results.html", services=ser) + + +@app.route('/admin') +@login_required +def admin(): + return render_template("admin.html") + +@app.route("/logout") +@login_required +def logout(): + logout_user() + return render_template("index.html") + +@app.route('/login' , methods=['GET' , 'POST']) +def login(): + if request.method == 'POST': + username = request.form['username'] + password = request.form['password'] + if(not (is_string_sanitized(username) and is_string_sanitized(username))): + return abort(401) + registeredUser = usermanager.Authenticate(username, password) + if registeredUser != None: + login_user(registeredUser) + return redirect(url_for('admin')) + else: + return abort(401) + else: + return render_template("login.html") + def RunWeb(): - app.run(debug=True) - -@app.route('/', methods=['POST']) -def my_form_post(): - text = request.form['text'] - processed_text = text.upper() - print(f'Inputted text is: {processed_text}') - return processed_text - - + app.run(debug=True) \ No newline at end of file diff --git a/config.py b/config.py new file mode 100644 index 0000000..db1d18c --- /dev/null +++ b/config.py @@ -0,0 +1 @@ +SECRET_KEY="5d836ca2ce0843658c5d56e12d94e512" \ No newline at end of file diff --git a/forms.py b/forms.py new file mode 100644 index 0000000..2a394f0 --- /dev/null +++ b/forms.py @@ -0,0 +1,7 @@ +from wtforms import StringField, PasswordField, SubmitField +from flask_wtf import FlaskForm + +class LoginForm(FlaskForm): + username = StringField('username') + password = PasswordField('password') + submit = SubmitField('Submit') diff --git a/models.py b/models.py new file mode 100644 index 0000000..26a1e2d --- /dev/null +++ b/models.py @@ -0,0 +1,21 @@ +from flask_login import UserMixin + +class User(UserMixin): + def __init__(self , username , password , id , active=True, salt=""): + self.id = id + self.username = username + self.password = password + self.active = active + self.salt = salt + + def get(self): + return self.id + + def get_id(self): + return self.id + + def is_active(self): + return self.active + + # def get_auth_token(self): + # return make_secure_token(self.username , key='secret_key') diff --git a/services.py b/services.py index fb52f09..8ae9bc1 100644 --- a/services.py +++ b/services.py @@ -1,14 +1,19 @@ import datetime -from sqlite3 import * import sqlite3 import locale import random -locale.setlocale(locale.LC_TIME, "nl_NL.utf-8") # swedish +import hashlib +import uuid + +from werkzeug.datastructures import Authorization +from models import User +locale.setlocale(locale.LC_TIME, "nl_NL.utf-8") + + class Services: - def __init__(self, sqlpath="sqlite.db") -> None: - self.sqlpath = sqlpath - self.db = sqlite3.connect(self.sqlpath, check_same_thread=False) + def __init__(self, db) -> None: + self.db = db self.cursor = self.db.cursor() self.PopulateDB() @@ -53,19 +58,75 @@ class Services: self.cursor.execute(query) self.db.commit() +class UserManager(): + def __init__(self, db) -> None: + self.db = db + self.cursor = self.db.cursor() + self.PopulateDB() + + def PopulateDB(self): + ''' + Create db for user managment. Password is stored as a hash + ''' + query = f"""CREATE TABLE IF NOT EXISTS users + ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name STRING, + password STRING, + salt STRING + ); + """ + self.cursor.execute(query) + + def AddUser(self, name, password): + salt = uuid.uuid4().hex + m = hashlib.sha512() + m.update((password + salt).encode("utf-8")) + password = m.digest().hex() + query = f""" + INSERT INTO users (name, password, salt) + VALUES('{name}', '{password}', '{salt}'); + """ + self.cursor.execute(query) + self.db.commit() + + def Authenticate(self, name, password): + us = self.cursor.execute(f"select * from users where name == '{name}';").fetchall() + if(us != None and len(us) > 0): + us = us[0] + m = hashlib.sha512() + m.update((password + us[3]).encode("utf-8")) + password = m.digest().hex() + if(password == us[2]): + return User(us[1], us[2], us[0], salt=us[3]) + return None + + def GetUserByID(self, id): + us = self.cursor.execute(f"select * from users where id == {id};").fetchall() + if(us != None): + us = us[0] + return User(us[1], us[2], us[0], salt=us[3]) + return None + if __name__ == "__main__": #fill db - ser = Services() - for i in range(100): - d = datetime.datetime.now() - d = d.replace(hour=random.randint(1, 23), day = random.randint(1, 28), month = random.randint(1, 12)) - d = d.strftime("%Y-%m-%d %H:%M:%S") - g = "" - for j in range(10): - g += str(random.randint(1, 30)) - g += ":" - ser.AddService(d, g) - r = ser.GetAllServices() - d = ser.GetServices(str(4)) - print(d) + db = sqlite3.connect("sqlite.db", check_same_thread=False) + ser = Services(db) + us = UserManager(db) + + # us.AddUser("Eljakim", "Kunnenwe?") + us.Authenticate("Eljakim", "Kunnenwe?") + us.Authenticate("Eljakim", "Kunnenwe2?") + # for i in range(100): + # d = datetime.datetime.now() + # d = d.replace(hour=random.randint(1, 23), day = random.randint(1, 28), month = random.randint(1, 12)) + # d = d.strftime("%Y-%m-%d %H:%M:%S") + # g = "" + # for j in range(10): + # g += str(random.randint(1, 30)) + # g += ":" + # ser.AddService(d, g) + # r = ser.GetAllServices() + # d = ser.GetServices(str(4)) + # print(d) \ No newline at end of file diff --git a/sqlite.db b/sqlite.db index 08eee2f..14c7bf6 100644 Binary files a/sqlite.db and b/sqlite.db differ diff --git a/static/style.css b/static/style.css index 5b98c8a..b0ee07b 100644 --- a/static/style.css +++ b/static/style.css @@ -131,4 +131,43 @@ margin-top: -100px; margin-left: -100px; font-family: "Verdana"; -} */ \ No newline at end of file +} */ + +.a_datum_block{ + width: 100%; +} + +.a_datum_input{ + padding: 1%; + position: relative; + margin:1%; +} +.a_datum_block{ + width: 100%; +} + +.a_van_input{ + padding: 1%; + margin:1%; +} + +.a_tot_input{ + padding: 1%; + margin:1%; +} + +.add_service_btn{ + position: relative; + background-color: lightblue; + padding: 2%; + margin: 1%; + width: 20%; + left: 20%; + text-align: center; + font-size: 26px; +} + +.add_service_btn:hover{ + background-color: blue; + cursor: pointer; +} \ No newline at end of file diff --git a/templates/admin.html b/templates/admin.html new file mode 100644 index 0000000..47750df --- /dev/null +++ b/templates/admin.html @@ -0,0 +1,30 @@ +{% extends 'base.html' %} + +
+ +
+

Administratie

+ + + + +{% block content %} +
+

Voeg dienst toe:

+
+ +
+
+ + t/m + +
+ +
Toevoegen
+
+ +
+
+{% endblock %} + + diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..75ac2fc --- /dev/null +++ b/templates/login.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block content %} +
+

+

+

+

+{% endblock %} \ No newline at end of file diff --git a/templates/static/style.css b/templates/static/style.css deleted file mode 100644 index e7f88b5..0000000 --- a/templates/static/style.css +++ /dev/null @@ -1,13 +0,0 @@ - -.center { - display: block; - margin-left: 40%; - margin-right: 60%; - width: 50%; - } - -.nummer_button{ - width:5%; - height: 3%; - background-color: red; -} \ No newline at end of file