Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 18 additions & 16 deletions app/auth.py → app/core/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

from app.database.models import UserRole
from app.schemas.common_schema import UserRole
from app.repositories.user_repository import UserRepository

JWT_SECRET = os.getenv("JWT_SECRET", "CVRanking@JWT")
ALGORITHM = "HS256"
Expand All @@ -24,6 +25,7 @@ class CurrentUser(BaseModel):
email: EmailStr
role: UserRole
company_id: Optional[str] = None
department_id: Optional[str] = None

def verify_password(plain_password: str, hashed_password: str):
pre_hashed_password = hashlib.sha256(plain_password.encode()).hexdigest()
Expand Down Expand Up @@ -63,24 +65,24 @@ async def get_current_user(token: str = Depends(oauth2_scheme)) -> CurrentUser:
except jwt.PyJWTError:
raise credentials_exception

from app.database.config import get_db, Collections
from bson import ObjectId
user = await UserRepository.get_by_id(user_id)

db = get_db()
user = await db[Collections.USERS].find_one({"_id": ObjectId(user_id)})

if not user:
if not user or user.get("deleted_at") is not None:
raise credentials_exception

try:
return CurrentUser(
id=str(user["_id"]),
email=user["email"],
role=UserRole(user.get("role", UserRole.APPLICANT.value)),
company_id=user.get("company_id")

if not user.get("is_active", True):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Tài khoản của bạn đã bị khóa."
)
except ValueError:
raise credentials_exception

return CurrentUser(
id=str(user["_id"]),
email=user["email"],
role=UserRole(user.get("role", UserRole.APPLICANT.value)),
company_id=user.get("company_id"),
department_id=user.get("department_id")
)

async def require_admin(current_user: CurrentUser = Depends(get_current_user)) -> CurrentUser:
if current_user.role != UserRole.ADMIN:
Expand Down
24 changes: 20 additions & 4 deletions app/database/config.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import os
import pymongo
from motor.motor_asyncio import AsyncIOMotorClient
from dotenv import load_dotenv

load_dotenv()

MONGO_URL = os.getenv("MONGO_URL", "mongodb://localhost:27017")
MONGO_URL = os.getenv("MONGO_URL", "mongodb://localhost:27017/cv-ranking")

class Database:
client: AsyncIOMotorClient = None
Expand All @@ -19,17 +20,32 @@ class Collections:
CVS = "cvs"
APPLICATIONS = "applications"
NOTIFICATIONS = "notifications"
CV_VECTORS = "cv_vectors"
JD_VECTORS = "jd_vectors"
AUDIT_LOGS = "audit_logs"
DEPARTMENTS = "departments"
SKILLS = "skills"
ADMINISTRATIVE_UNITS = "administrative_units"
REFRESH_TOKENS = "refresh_tokens"
SUBSCRIPTION_PLANS = "subscription_plans"
APPLICANT_PROFILES = "applicant_profiles"
INTERVIEW_FEEDBACKS = "interview_feedbacks"
COMPANY_REVIEWS = "company_reviews"
SAVED_JOBS = "saved_jobs"
JOB_ALERTS = "job_alerts"

MONGO_DB_NAME = os.getenv("MONGO_DB_NAME", "cv-ranking")

async def connect_to_mongo():
try:
db_instance.client = AsyncIOMotorClient(MONGO_URL)
db_instance.db = db_instance.client.get_default_database(MONGO_DB_NAME)
print("Đã kết nối thành công với MongoDB!")

await db_instance.db[Collections.AUDIT_LOGS].create_index(
[("created_at", pymongo.ASCENDING)],
expireAfterSeconds=7776000,
name="ttl_90_days_audit_logs"
)

print("Đã kết nối thành công với MongoDB và thiết lập TTL Index!")
except Exception as e:
print(f"Lỗi kết nối MongoDB: {e}")

Expand Down
Loading
Loading