diff --git a/db/user.db b/db/user.db
index 7f46464..172959d 100644
Binary files a/db/user.db and b/db/user.db differ
diff --git a/concept/user.py b/obj/user.py
similarity index 63%
rename from concept/user.py
rename to obj/user.py
index 85676b6..aa6a3d4 100644
--- a/concept/user.py
+++ b/obj/user.py
@@ -8,7 +8,6 @@ class User:
self._email = email
self._password = password
self._db_path = os.path.join("db", "user.db")
- #self._init_db()
# Getter
def get_id(self):
@@ -36,36 +35,6 @@ class User:
self._password = password
self._update_db()
- def _init_db(self):
- """Create the database and table if it doesn't exist"""
- with sqlite3.connect(self._db_path) as conn:
- c = conn.cursor()
- c.execute('''
- CREATE TABLE IF NOT EXISTS users (
- id INTEGER PRIMARY KEY,
- name TEXT NOT NULL,
- email TEXT NOT NULL,
- password TEXT NOT NULL
- )
- ''')
- conn.commit()
- #self._save_to_db()
-
- def _save_to_db(self):
- """Insert or update the user in the DB"""
- with sqlite3.connect(self._db_path) as conn:
- c = conn.cursor()
- c.execute("SELECT id FROM users WHERE id = ?", (self._user_id,))
- if c.fetchone():
- # update
- c.execute('UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?',
- (self._name, self._email, self._password, self._user_id))
- else:
- # insert
- c.execute('INSERT INTO users (id, name, email, password) VALUES (?, ?, ?, ?)',
- (self._user_id, self._name, self._email, self._password))
- conn.commit()
-
def _update_db(self):
"""Update the user's data in the DB"""
with sqlite3.connect(self._db_path) as conn:
@@ -91,15 +60,28 @@ class User:
@staticmethod
- def authenticate_user(email, password):
+ def authenticate_user(username, password):
"""Prüft, ob ein Benutzer mit E-Mail + Passwort existiert"""
db_path = os.path.join("db", "user.db")
with sqlite3.connect(db_path) as conn:
c = conn.cursor()
- c.execute("SELECT id, name, email FROM users WHERE email = ? AND password = ?", (email, password))
+ c.execute("SELECT id, name, email FROM users WHERE name = ? AND password = ?", (username, password))
result = c.fetchone()
if result:
user_id, name, email = result
return User(user_id, name, email, password)
return None
+
+ @staticmethod
+ def validate_user(username, userid):
+ """Prüft, ob ein Benutzer mit E-Mail + Passwort existiert"""
+ db_path = os.path.join("db", "user.db")
+ with sqlite3.connect(db_path) as conn:
+ c = conn.cursor()
+ c.execute("SELECT id, name, email FROM users WHERE name = ? AND id = ?", (username, userid))
+ result = c.fetchone()
+ if result:
+ user_id, name, email= result
+ return True
+ return None
diff --git a/routes/unsecure_routes.py b/routes/unsecure_routes.py
index 35adf55..bc9b99b 100644
--- a/routes/unsecure_routes.py
+++ b/routes/unsecure_routes.py
@@ -5,6 +5,8 @@ from modules.persistence import esp_conn_infos
from datetime import datetime
from modules.socketio import resend_static_data
from modules.db import get_coffee_count, get_coffees
+from obj import user
+import random
@unsecure.route('/')
@@ -15,17 +17,47 @@ def index():
if not username or not userid:
return redirect('/unsecure/login')
+ valid_user = user.User.validate_user(username=username, userid=userid)
+ print(valid_user)
+ if not valid_user:
+ return redirect('/unsecure/login')
+
+
water = load_dict("water")
beans = load_dict("beans")
machine = load_dict("machine")
coffee_count = get_coffee_count()
# print(f"[DEBUG] Water: {water}, Beans: {beans}, Machine: {machine}")
- return render_template('index.html', title='gimmiCoffee', water=water, beans=beans, machine=machine, esp_conn_infos=esp_conn_infos, coffee_count=coffee_count)
+ return render_template('index.html', title='gimmiCoffee', water=water, beans=beans, machine=machine, esp_conn_infos=esp_conn_infos, coffee_count=coffee_count, username = username)
-# @unsecure.route('/update')
-# def update():
-# resend_static_data()
-# return jsonify({"status": "ok", "task": "update-executed"})
+@unsecure.route('/verify', methods=['POST'])
+def verify():
+ username = request.args.get('username')
+ password = request.args.get('pass')
+
+ if not username or not password:
+ return jsonify({'route': '/unsecure/login'}), 400
+
+ is_existent = user.User.authenticate_user(username, password)
+ if is_existent:
+ # Erfolgreich eingeloggt → weiterleiten
+ return jsonify({'route': f"/unsecure/?username={is_existent.get_name()}&userid={is_existent.get_id()}"})
+ else:
+ # Fehler → zurück zur Login-Seite
+ return jsonify({'route': '/unsecure/login', 'error': 'Invalid credentials'}), 401
+
+@unsecure.route('/register', methods=['POST'])
+def register():
+ username = request.args.get('username')
+ password = request.args.get('pass')
+ userid = random.randint(10000, 99999)
+ print(username, password, userid)
+ if not username or not password:
+ return jsonify({'err': 'invalidData'}), 400
+
+ new_user = user.User(user_id=userid, name=username, email = "", password=password)
+ new_user.save_to_db()
+ return redirect('/unsecure/login')
@unsecure.route('/login')
def login():
diff --git a/static/login.js b/static/login.js
index e812f24..cac0e0e 100644
--- a/static/login.js
+++ b/static/login.js
@@ -6,10 +6,29 @@ document.getElementById('login-btn').addEventListener('click', function () {
alert("Bitte Benutzername und Passwort eingeben.");
return;
}
+ fetch(`/unsecure/verify?username=${username}&pass=${password}`, { method: 'POST' })
+ .then(res => res.json())
+ .then(data => {
+ //console.log(data)
+ window.location.href = data.route
- // Beispiel: Zufällige User-ID generieren (normalerweise kommt das vom Server)
- const userid = Math.floor(Math.random() * 100000);
+ });
+});
+document.getElementById('create-btn').addEventListener('click', function () {
+ const username = document.getElementById('usrnm').value.trim();
+ const password = document.getElementById('pw').value;
+ if (!username || !password) {
+ alert("Bitte Benutzername und Passwort eingeben.");
+ return;
+ }
- // Weiterleitung zur Startseite mit Parametern
- window.location.href = `/unsecure/?username=${encodeURIComponent(username)}&userid=${userid}`;
-});
\ No newline at end of file
+ const result = confirm(`Möchtest du einen Nutzer mit ${username} erstellen?`);
+ if (!result) {
+ return;
+ }
+ fetch(`/unsecure/register?username=${username}&pass=${password}`, { method: 'POST' })
+ .then(res => res.json)
+ .then(data => {
+ console.log(data)
+ })
+})
\ No newline at end of file
diff --git a/static/script.js b/static/script.js
index a8c2afc..d215af2 100644
--- a/static/script.js
+++ b/static/script.js
@@ -138,3 +138,6 @@ function beansRefill(){
function showCoffeeHistory(){
window.location.href = "/unsecure/coffees-made";
}
+function logout(){
+ window.location.href = "/unsecure/login"
+}
diff --git a/templates/index.html b/templates/index.html
index 24ac754..9c56e41 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -13,8 +13,8 @@