CoolFace
Apppublic

pcb-defect-detector-project/new-version

sourceHugging Faceupdated 26d agoView on Hugging Face
0likes
auth.py76 linesDownload Raw Back to root
1# auth.py2from datetime import datetime, timedelta3from jose import JWTError, jwt4from passlib.context import CryptContext5from fastapi import HTTPException, status, Depends6from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials7from database import User  # إزالة get_db لأننا لا نستخدم SQLAlchemy Session8 9SECRET_KEY = "K7gJ3sF9xL2mN5pQ8rT1uV4wY6zA0bC3dE5fH7iJ9kL1nM2oP3qR4sT5uV6wX7yZ8"10ALGORITHM = "HS256"11ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7  # 7 أيام12 13# تكوين bcrypt مع تقييد طول كلمة المرور14pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")15 16security = HTTPBearer()17 18 19def verify_password(plain_password, hashed_password):20    """التحقق من صحة كلمة المرور"""21    # تقطيع كلمة المرور إذا كانت أطول من 72 حرف (حد bcrypt)22    if len(plain_password) > 72:23        plain_password = plain_password[:72]24    try:25        return pwd_context.verify(plain_password, hashed_password)26    except ValueError:27        return False28 29 30def get_password_hash(password):31    """تشفير كلمة المرور"""32    # تقطيع كلمة المرور إذا كانت أطول من 72 حرف (حد bcrypt)33    if len(password) > 72:34        password = password[:72]35    return pwd_context.hash(password)36 37 38def authenticate_user(username: str, password: str):39    """40    مصادقة المستخدم - إصدار متوافق مع DatasetStorage41    لا يحتاج إلى db: Session42    """43    user = User.get_by_username(username)44    if not user or not verify_password(password, user.hashed_password):45        return False46    return user47 48 49def create_access_token(data: dict):50    """إنشاء توكن JWT"""51    to_encode = data.copy()52    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)53    to_encode.update({"exp": expire})54    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)55    return encoded_jwt56 57 58def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):59    """60    استخراج المستخدم الحالي من التوكن - إصدار متوافق مع DatasetStorage61    لا يحتاج إلى db: Session62    """63    token = credentials.credentials64    try:65        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])66        user_id: str = payload.get("sub")67        if user_id is None:68            raise HTTPException(status_code=401, detail="Invalid token")69    except JWTError:70        raise HTTPException(status_code=401, detail="Invalid token")71    72    # استخدام DatasetStorage بدلاً من SQLAlchemy73    user = User.get_by_id(user_id)74    if user is None:75        raise HTTPException(status_code=401, detail="User not found")76    return user