Spaces:
Sleeping
Sleeping
Update auth.py
Browse files
auth.py
CHANGED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import jwt
|
| 2 |
+
import datetime
|
| 3 |
+
from passlib.hash import bcrypt
|
| 4 |
+
from storage import get_user, add_user
|
| 5 |
+
from fastapi import HTTPException
|
| 6 |
+
|
| 7 |
+
SECRET_KEY = "your-secret-key-keep-it-safe" # Change this in production!
|
| 8 |
+
ALGORITHM = "HS256"
|
| 9 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
| 10 |
+
|
| 11 |
+
def verify_password(plain_password, hashed_password):
|
| 12 |
+
return bcrypt.verify(plain_password, hashed_password)
|
| 13 |
+
|
| 14 |
+
def get_password_hash(password):
|
| 15 |
+
return bcrypt.hash(password)
|
| 16 |
+
|
| 17 |
+
def create_access_token(data: dict, expires_delta: datetime.timedelta = None):
|
| 18 |
+
to_encode = data.copy()
|
| 19 |
+
if expires_delta:
|
| 20 |
+
expire = datetime.datetime.utcnow() + expires_delta
|
| 21 |
+
else:
|
| 22 |
+
expire = datetime.datetime.utcnow() + datetime.timedelta(minutes=15)
|
| 23 |
+
to_encode.update({"exp": expire})
|
| 24 |
+
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 25 |
+
return encoded_jwt
|
| 26 |
+
|
| 27 |
+
def authenticate_user(username: str, password: str):
|
| 28 |
+
user = get_user(username)
|
| 29 |
+
if not user:
|
| 30 |
+
return False
|
| 31 |
+
if not verify_password(password, user["password"]):
|
| 32 |
+
return False
|
| 33 |
+
return user
|
| 34 |
+
|
| 35 |
+
def register_user(username: str, password: str):
|
| 36 |
+
if get_user(username):
|
| 37 |
+
raise HTTPException(status_code=400, detail="Username already registered")
|
| 38 |
+
hashed_password = get_password_hash(password)
|
| 39 |
+
add_user(username, hashed_password)
|
| 40 |
+
return {"username": username, "message": "User created successfully"}
|