Update services/auth.py
Browse files- services/auth.py +52 -46
services/auth.py
CHANGED
@@ -1,47 +1,53 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
from
|
6 |
-
from
|
7 |
-
from
|
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 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
from passlib.context import CryptContext
|
2 |
+
from sqlmodel import Session, select
|
3 |
+
from typing import Optional
|
4 |
+
|
5 |
+
from models.user import User, UserCreate
|
6 |
+
from models.db import get_session_context # Using context manager for direct use
|
7 |
+
from services.logger import app_logger
|
8 |
+
|
9 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
10 |
+
|
11 |
+
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
12 |
+
return pwd_context.verify(plain_password, hashed_password)
|
13 |
+
|
14 |
+
def get_password_hash(password: str) -> str:
|
15 |
+
return pwd_context.hash(password)
|
16 |
+
|
17 |
+
def get_user(db: Session, username: str) -> Optional[User]:
|
18 |
+
statement = select(User).where(User.username == username)
|
19 |
+
user = db.exec(statement).first()
|
20 |
+
return user
|
21 |
+
|
22 |
+
def create_user_in_db(user_data: UserCreate) -> Optional[User]:
|
23 |
+
hashed_password = get_password_hash(user_data.password)
|
24 |
+
db_user = User(
|
25 |
+
username=user_data.username,
|
26 |
+
hashed_password=hashed_password,
|
27 |
+
email=user_data.email,
|
28 |
+
full_name=user_data.full_name
|
29 |
)
|
30 |
+
try:
|
31 |
+
with get_session_context() as db:
|
32 |
+
# Check if user already exists
|
33 |
+
existing_user = get_user(db, user_data.username)
|
34 |
+
if existing_user:
|
35 |
+
app_logger.warning(f"User {user_data.username} already exists.")
|
36 |
+
return None # Or raise an exception
|
37 |
+
|
38 |
+
db.add(db_user)
|
39 |
+
db.commit() # Commit is handled by context manager, but explicit commit for return
|
40 |
+
db.refresh(db_user)
|
41 |
+
return db_user
|
42 |
+
except Exception as e:
|
43 |
+
app_logger.error(f"Error creating user {user_data.username}: {e}")
|
44 |
+
return None
|
45 |
+
|
46 |
+
def authenticate_user(username: str, password: str) -> Optional[User]:
|
47 |
+
with get_session_context() as db:
|
48 |
+
user = get_user(db, username)
|
49 |
+
if not user:
|
50 |
+
return None
|
51 |
+
if not verify_password(password, user.hashed_password):
|
52 |
+
return None
|
53 |
+
return user
|