implement user and login
This commit is contained in:
BIN
db/user.db
BIN
db/user.db
Binary file not shown.
@@ -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
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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}`;
|
||||
});
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -138,3 +138,6 @@ function beansRefill(){
|
||||
function showCoffeeHistory(){
|
||||
window.location.href = "/unsecure/coffees-made";
|
||||
}
|
||||
function logout(){
|
||||
window.location.href = "/unsecure/login"
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
<header>
|
||||
<div class="site-title">gimmiCoffee</div>
|
||||
<div class="user-actions">
|
||||
<span class="username">Max Mustermann</span>
|
||||
<a href="/logout" class="logout">Logout</a>
|
||||
<span class="username">{{ username }}</span>
|
||||
<a onclick="logout()" class="logout">Logout</a>
|
||||
</div>
|
||||
</header>
|
||||
<div id="waterData" style="display: none;">{{ water | tojson }}</div>
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
<input type="text" placeholder="Username" id="usrnm">
|
||||
<input type="password" placeholder="Passwort" id="pw">
|
||||
<button id="login-btn">Login</button>
|
||||
<button>Erstelle Nutzer</button>
|
||||
<button id="create-btn">Erstelle Nutzer</button>
|
||||
</div>
|
||||
|
||||
<script src="{{ url_for('static', filename='login.js') }}"></script>
|
||||
|
||||
Reference in New Issue
Block a user