Ahmed766 commited on
Commit
5cc9fab
·
verified ·
1 Parent(s): 23c1e46

Upload core/security.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. core/security.py +60 -0
core/security.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timedelta
2
+ from typing import Optional
3
+ from jose import JWTError, jwt
4
+ import hashlib
5
+ from fastapi import HTTPException, status, Depends
6
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
7
+ from sqlalchemy.orm import Session
8
+ import os
9
+
10
+ from database.models import User
11
+ from database.session import get_db
12
+
13
+ # Security configuration
14
+ SECRET_KEY = os.getenv("SECRET_KEY", "auranexus-secret-key-change-in-production")
15
+ ALGORITHM = "HS256"
16
+ ACCESS_TOKEN_EXPIRE_MINUTES = 30
17
+
18
+ # For demo purposes, using a simple hash function
19
+ # In production, use proper password hashing like bcrypt
20
+ security = HTTPBearer()
21
+
22
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
23
+ # Simple hash comparison for demo purposes
24
+ return get_password_hash(plain_password) == hashed_password
25
+
26
+ def get_password_hash(password: str) -> str:
27
+ # Simple hash for demo purposes
28
+ return hashlib.sha256(password.encode()).hexdigest()
29
+
30
+ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
31
+ to_encode = data.copy()
32
+ if expires_delta:
33
+ expire = datetime.utcnow() + expires_delta
34
+ else:
35
+ expire = datetime.utcnow() + timedelta(minutes=15)
36
+ to_encode.update({"exp": expire})
37
+ encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
38
+ return encoded_jwt
39
+
40
+ def get_current_user(
41
+ credentials: HTTPAuthorizationCredentials = Depends(security),
42
+ db: Session = Depends(get_db)
43
+ ) -> User:
44
+ credentials_exception = HTTPException(
45
+ status_code=status.HTTP_401_UNAUTHORIZED,
46
+ detail="Could not validate credentials",
47
+ headers={"WWW-Authenticate": "Bearer"},
48
+ )
49
+ try:
50
+ payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
51
+ user_id: str = payload.get("sub")
52
+ if user_id is None:
53
+ raise credentials_exception
54
+ except JWTError:
55
+ raise credentials_exception
56
+
57
+ user = db.query(User).filter(User.id == user_id).first()
58
+ if user is None:
59
+ raise credentials_exception
60
+ return user