Files
izbi-dns/app/auth.py
T

74 lines
2.2 KiB
Python
Raw Normal View History

2026-08-24 01:37:14 +02:00
import sqlite3
2026-08-24 15:18:45 +02:00
from hashlib import sha256
2026-08-24 01:37:14 +02:00
2026-08-24 13:35:59 +02:00
def init_db(path: str) -> None:
with sqlite3.connect(path) as connection:
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Tokens (
2026-08-24 15:18:45 +02:00
TKHASH TEXT PRIMARY KEY NOT NULL,
2026-08-24 13:35:59 +02:00
USERID INTEGER NOT NULL,
NAME TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS Domains (
DOMAIN TEXT PRIMARY KEY NOT NULL,
USERID INTEGER NOT NULL
)
''')
2026-08-24 15:18:45 +02:00
cursor.execute('''
CREATE TABLE IF NOT EXISTS Users (
USERID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
USERNAME TEXT NOT NULL UNIQUE,
PWHASH TEXT NOT NULL,
PWSALT TEXT NOT NULL,
EMAIL TEXT
IS_ADMIN INTEGER NOT NULL DEFAULT 0
)
''')
2026-08-24 13:35:59 +02:00
connection.commit()
cursor.close()
2026-08-24 01:37:14 +02:00
def check_token_domain(db_path: str, token: str, domain: str) -> bool:
with sqlite3.connect(db_path) as connection:
cursor = connection.cursor()
2026-08-24 15:18:45 +02:00
token_hash = sha256(token.encode('utf-8')).hexdigest()
2026-08-24 01:37:14 +02:00
cursor.execute('''
SELECT COUNT(*) FROM Tokens
2026-08-24 13:35:59 +02:00
JOIN Domains ON Tokens.userid = Domains.userid
2026-08-24 15:18:45 +02:00
WHERE tkhash = ?
2026-08-24 01:37:14 +02:00
AND domain = ?
2026-08-24 15:18:45 +02:00
''', (token_hash, domain))
2026-08-24 01:37:14 +02:00
return cursor.fetchone()[0] == 1
2026-08-24 15:18:45 +02:00
def user_login(db_path: str, username: str, password: str) -> bool:
with sqlite3.connect(db_path) as connection:
cursor = connection.cursor()
cursor.execute('''
SELECT pwsalt FROM Users
WHERE username = ?
''', (username,))
password_salt = cursor.fetchone()
if password_salt is None:
return False
password_salt = password_salt[0]
password_hash = sha256( (password_salt + password).encode('utf-8') ).hexdigest()
cursor.execute('''
SELECT COUNT(*) FROM Users
WHERE username = ?
AND pwhash = ?
''', (username, password_hash))
return cursor.fetchone()[0] == 1