83 lines
3.2 KiB
Python
83 lines
3.2 KiB
Python
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
|
|
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.
|
|
"""
|
|
def __init__(self, user_name=None, login_data=None):
|
|
self.user_name = user_name # Initialize the user name attribute for the login class
|
|
|
|
def check_logged_in():
|
|
if request.cookies.get('username') is None:
|
|
session['logged_in'] = False
|
|
session['username'] = 'Gast'
|
|
return False # Return False if the user name is not provided
|
|
else:
|
|
session['logged_in'] = True
|
|
session['username'] = request.cookies.get('username')
|
|
session['userid'] = request.cookies.get('userid')
|
|
|
|
return True # Otherwise, return True indicating a valid user name
|
|
|
|
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
|