Lerndatenbank/lernplattform/classes.py

83 lines
3.2 KiB
Python
Raw Normal View History

2024-08-08 11:55:21 +02:00
from flask import Flask, request, session, make_response, redirect, url_for
from werkzeug.security import generate_password_hash, check_password_hash
from lernplattform import app, db
from lernplattform.models import User
2024-08-08 11:55:21 +02:00
import random
import string
def generate_random_string(length=8):
characters = string.ascii_letters + string.digits
random_string = ''.join(random.choice(characters) for _ in range(length))
return random_string
class login():
"""
A class for handling user login functionality.
Attributes:
user_name (str): The username to be checked for authentication.
Methods:
__init__(self, user_name=None): Initializes the login object with a given user name.
check(user_name): A static method that checks if the provided user name is valid.
login(self): Prints "Login" to indicate that the login method has been called.
"""
2024-08-08 11:55:21 +02:00
def __init__(self, user_name=None, login_data=None):
self.user_name = user_name # Initialize the user name attribute for the login class
2024-08-08 11:55:21 +02:00
def check_logged_in():
if request.cookies.get('username') is None:
2024-08-06 20:11:36 +02:00
session['logged_in'] = False
2024-08-08 11:55:21 +02:00
session['username'] = 'Gast'
return False # Return False if the user name is not provided
else:
2024-08-06 20:11:36 +02:00
session['logged_in'] = True
2024-08-08 11:55:21 +02:00
session['username'] = request.cookies.get('username')
session['userid'] = request.cookies.get('userid')
2024-08-06 20:11:36 +02:00
return True # Otherwise, return True indicating a valid user name
2024-08-08 11:55:21 +02:00
def login(login_data):
# get password from db
user = User.query.filter_by(username = login_data.get('username')).first()
if user and check_password_hash(user.password, login_data.get('password')):
if not user.email_check == "":
return False
session['userid'] = user.id
session['username'] = user.username
session['logged_in'] = True
if login_data['remember'] == 'on':
resp = make_response(redirect(url_for('index')))
resp.set_cookie('userid', user.id)
resp.set_cookie('username', user.username)
return True
else:
return False
def logout():
resp = make_response(redirect(url_for('index')))
resp.set_cookie('username', '', expires=0)
resp.set_cookie('userid', '', expires=0)
session['logged_in'] = False
return resp
def register(request):
username = request.form.get('username')
email = request.form.get('email')
password = request.form.get('password')
hashed_password = generate_password_hash(password, method='pbkdf2:sha256')
if User.query.filter_by(username = username).first():
return False # Return False if the user name is already in use
else:
random_string = generate_random_string()
user = User(username = username, email = email, password = hashed_password, email_check = random_string)
db.session.add(user)
db.session.commit()
return True