File size: 956 Bytes
9d9d2a1
 
 
8a409ad
 
 
 
 
 
 
 
 
9d9d2a1
 
 
 
8a409ad
 
 
f4cb7b4
8a409ad
9d9d2a1
 
8a409ad
f4cb7b4
9d9d2a1
8a409ad
9d9d2a1
 
8a409ad
 
 
 
 
9d9d2a1
 
f4cb7b4
 
d66fb93
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from passlib.context import CryptContext
from src.db.connection import get_conn

PWD_CTX = CryptContext(
    schemes=["bcrypt"],
    deprecated="auto",
)


def authenticate_user(db_path: str, username: str, password: str):
    if not username or not password:
        return None

    conn = get_conn(db_path)
    try:
        row = conn.execute(
            """
            SELECT username, role, password_hash, is_active
            FROM users
            WHERE username=?
            """,
            (username,),
        ).fetchone()

        if not row or not row["is_active"]:
            return None

        if not PWD_CTX.verify(password, row["password_hash"]):
            return None

        return {
            "username": row["username"],
            "role": row["role"],
        }
    finally:
        conn.close()


def is_admin(auth_state) -> bool:
    if not auth_state:
        return False
    return auth_state.get("role") == "admin"