80 lines
2.4 KiB
Python
80 lines
2.4 KiB
Python
from argon2 import PasswordHasher
|
|
import db
|
|
from dotenv import load_dotenv
|
|
import logging
|
|
import os
|
|
import mariadb
|
|
#Logging
|
|
|
|
logging.basicConfig(
|
|
filename='auth/user.log', # Log to a file
|
|
level=logging.DEBUG, # Log everything (DEBUG and above)
|
|
format='%(asctime)s %(levelname)s %(message)s'
|
|
)
|
|
|
|
logging.info('Application started')
|
|
try:
|
|
logging.debug('Debug info here')
|
|
except Exception as e:
|
|
logging.exception('An error occurred')
|
|
|
|
load_dotenv()
|
|
db_name = os.getenv("DB_NAME")
|
|
db_psswd = os.getenv("DB_PASSWORD")
|
|
db_user = os.getenv("DB_USER")
|
|
db_port = os.getenv("DB_PORT") or "3306"
|
|
db_host = os.getenv("DB_HOST")
|
|
if db_host == None:
|
|
logging.error("no hostname provided")
|
|
os._exit(1)
|
|
|
|
db.connect(db_user, db_psswd, db_host, int(db_port), db_name)
|
|
cursor = db.connection.cursor()
|
|
|
|
def create_user(username, password):
|
|
user = username
|
|
passwd = PasswordHasher().hash(password)
|
|
cursor = db.connection.cursor()
|
|
executed = "INSERT INTO user (username, password) VALUES (?, ?)"
|
|
executed_data = (user, passwd)
|
|
cursor.execute(executed, executed_data)
|
|
db.connection.commit()
|
|
|
|
def check_login(username, password):
|
|
cursor = db.connection.cursor()
|
|
hash_passwd = cursor.execute("SELECT password FROM user WHERE username = ?", (username,))
|
|
valid = False
|
|
try:
|
|
valid = PasswordHasher().verify(hash_passwd, password)
|
|
if valid == True:
|
|
return valid
|
|
except Exception as e:
|
|
logging.error(e)
|
|
return False
|
|
|
|
def delete_user(username, password):
|
|
cursor = db.connection.cursor()
|
|
hash_password = cursor.execute("SELECT password FROM user WHERE username = ?", (username,))#
|
|
valid = False
|
|
try:
|
|
valid = PasswordHasher().verify(hash_password, password)
|
|
except Exception as e:
|
|
logging.error(e)
|
|
if valid == True:
|
|
try:
|
|
cursor.execute("DELETE FROM user WHERE username = ?", (username,))
|
|
db.connection.commit()
|
|
logging.info(f"User {username} was successfully deleted")
|
|
except Exception as e:
|
|
logging.error(e)
|
|
|
|
def check_username(username):
|
|
try:
|
|
cursor.execute("SELECT 1 FROM user WHERE username = ?", (username,))
|
|
exists = cursor.fetchone() is not None
|
|
return exists # True if taken, False if available
|
|
except db.IntegrityError as e:
|
|
if e.errno == 1062:
|
|
logging.error("Username taken")
|
|
return True #If the username is not available it returns True
|
|
|