OOP concept

This commit is contained in:
derlole
2025-05-15 08:08:47 +00:00
parent 885becf0e8
commit e268f0befb
8 changed files with 204 additions and 13 deletions

View File

@@ -2,12 +2,13 @@ import sqlite3
import os import os
class User: class User:
def __init__(self, user_id, name, email): def __init__(self, user_id, name, email, password):
self._user_id = user_id self._user_id = user_id
self._name = name self._name = name
self._email = email self._email = email
self._db_path = os.path.join("..", "db", "user.db") self._password = password
self._init_db() self._db_path = os.path.join("db", "user.db")
#self._init_db()
# Getter # Getter
def get_id(self): def get_id(self):
@@ -19,6 +20,9 @@ class User:
def get_email(self): def get_email(self):
return self._email return self._email
def get_password(self):
return self._password
# Setter # Setter
def set_name(self, name): def set_name(self, name):
self._name = name self._name = name
@@ -28,6 +32,10 @@ class User:
self._email = email self._email = email
self._update_db() self._update_db()
def set_password(self, password):
self._password = password
self._update_db()
def _init_db(self): def _init_db(self):
"""Create the database and table if it doesn't exist""" """Create the database and table if it doesn't exist"""
with sqlite3.connect(self._db_path) as conn: with sqlite3.connect(self._db_path) as conn:
@@ -36,11 +44,12 @@ class User:
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
name TEXT NOT NULL, name TEXT NOT NULL,
email TEXT NOT NULL email TEXT NOT NULL,
password TEXT NOT NULL
) )
''') ''')
conn.commit() conn.commit()
self._save_to_db() #self._save_to_db()
def _save_to_db(self): def _save_to_db(self):
"""Insert or update the user in the DB""" """Insert or update the user in the DB"""
@@ -49,18 +58,48 @@ class User:
c.execute("SELECT id FROM users WHERE id = ?", (self._user_id,)) c.execute("SELECT id FROM users WHERE id = ?", (self._user_id,))
if c.fetchone(): if c.fetchone():
# update # update
c.execute('UPDATE users SET name = ?, email = ? WHERE id = ?', c.execute('UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?',
(self._name, self._email, self._user_id)) (self._name, self._email, self._password, self._user_id))
else: else:
# insert # insert
c.execute('INSERT INTO users (id, name, email) VALUES (?, ?, ?)', c.execute('INSERT INTO users (id, name, email, password) VALUES (?, ?, ?, ?)',
(self._user_id, self._name, self._email)) (self._user_id, self._name, self._email, self._password))
conn.commit() conn.commit()
def _update_db(self): def _update_db(self):
"""Update the user's data in the DB""" """Update the user's data in the DB"""
with sqlite3.connect(self._db_path) as conn: with sqlite3.connect(self._db_path) as conn:
c = conn.cursor() c = conn.cursor()
c.execute('UPDATE users SET name = ?, email = ? WHERE id = ?', c.execute('UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?',
(self._name, self._email, self._user_id)) (self._name, self._email, self._password, self._user_id))
conn.commit() conn.commit()
def save_to_db(self):
"""Speichert den aktuellen Benutzer in die Datenbank (Insert oder Update)"""
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():
# Benutzer existiert bereits → aktualisieren
c.execute('UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?',
(self._name, self._email, self._password, self._user_id))
else:
# Neuer Benutzer → einfügen
c.execute('INSERT INTO users (id, name, email, password) VALUES (?, ?, ?, ?)',
(self._user_id, self._name, self._email, self._password))
conn.commit()
@staticmethod
def authenticate_user(email, 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))
result = c.fetchone()
if result:
user_id, name, email = result
return User(user_id, name, email, password)
return None

Binary file not shown.

View File

@@ -0,0 +1,25 @@
import sqlite3
import os
def create_user_db():
db_path = os.path.join("db", "user.db")
# Stelle sicher, dass der Ordner existiert
os.makedirs(os.path.dirname(db_path), exist_ok=True)
# Datenbank und Tabelle erstellen
with sqlite3.connect(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()
print(f"Datenbank erstellt unter: {db_path}")
if __name__ == "__main__":
create_user_db()

BIN
db/user.db Normal file

Binary file not shown.

View File

@@ -1,4 +1,4 @@
from flask import Blueprint, render_template, request, jsonify from flask import Blueprint, render_template, request, jsonify, redirect
unsecure = Blueprint('unsecure', __name__, url_prefix='/unsecure') unsecure = Blueprint('unsecure', __name__, url_prefix='/unsecure')
from modules.persistence import load_dict, save_dict from modules.persistence import load_dict, save_dict
from modules.persistence import esp_conn_infos from modules.persistence import esp_conn_infos
@@ -9,6 +9,12 @@ from modules.db import get_coffee_count, get_coffees
@unsecure.route('/') @unsecure.route('/')
def index(): def index():
username = request.args.get('username')
userid = request.args.get('userid')
if not username or not userid:
return redirect('/unsecure/login')
water = load_dict("water") water = load_dict("water")
beans = load_dict("beans") beans = load_dict("beans")
machine = load_dict("machine") machine = load_dict("machine")
@@ -21,6 +27,10 @@ def index():
# resend_static_data() # resend_static_data()
# return jsonify({"status": "ok", "task": "update-executed"}) # return jsonify({"status": "ok", "task": "update-executed"})
@unsecure.route('/login')
def login():
return render_template('login.html')
@unsecure.route('/refill-water', methods=['POST']) @unsecure.route('/refill-water', methods=['POST'])
def update_water(): def update_water():
water = load_dict("water") water = load_dict("water")

77
static/login.css Normal file
View File

@@ -0,0 +1,77 @@
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
height: 100vh;
background: linear-gradient(135deg, #ece9e6, #ffffff);
display: flex;
justify-content: center;
align-items: center;
}
.title {
font-size: 2.5rem;
margin-bottom: 1.5rem;
font-weight: 600;
color: #333;
text-align: center;
}
div.form-container {
background: #fff;
padding: 2rem 3rem;
border-radius: 12px;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
max-width: 350px;
}
input {
width: 100%;
padding: 0.75rem 1rem;
margin-bottom: 1rem;
border: 1px solid #ccc;
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.3s ease;
}
input:focus {
border-color: #6a5acd;
outline: none;
}
button {
margin-bottom: 1rem;
width: 100%;
padding: 0.75rem;
font-size: 1rem;
font-weight: bold;
background-color: #6a5acd;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #5941c6;
}
@media (max-width: 480px) {
div.form-container {
padding: 1.5rem 2rem;
}
.title {
font-size: 2rem;
}
}

15
static/login.js Normal file
View File

@@ -0,0 +1,15 @@
document.getElementById('login-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;
}
// Beispiel: Zufällige User-ID generieren (normalerweise kommt das vom Server)
const userid = Math.floor(Math.random() * 100000);
// Weiterleitung zur Startseite mit Parametern
window.location.href = `/unsecure/?username=${encodeURIComponent(username)}&userid=${userid}`;
});

25
templates/login.html Normal file
View File

@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="{{ url_for('static', filename='login.css') }}">
<link rel="icon" href="{{ url_for('static', filename='gimmiCoffee_Logo.png') }}" type="image/png">
</head>
<style>
</style>
<body>
<div class="form-container">
<div class="title">gimmiCoffee</div>
<input type="text" placeholder="Username" id="usrnm">
<input type="password" placeholder="Passwort" id="pw">
<button id="login-btn">Login</button>
<button>Erstelle Nutzer</button>
</div>
<script src="{{ url_for('static', filename='login.js') }}"></script>
</body>
</html>