first commit

This commit is contained in:
jianxin committed 2023-09-02 17:24:47 +08:00
commit 438535fe98
29 files changed
+927

No files matched your search

+1
View File
@@ -0,0 +1 @@
from app.utils import encrypt
Binary file not shown.
Binary file not shown.
Binary file not shown.
+35
View File
@@ -0,0 +1,35 @@
import jwt
from sqlalchemy.orm import Session
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from app import models, schemas, crud
from app.utils.encrypt import decode_token
from app.database import SessionLocal
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/token")
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
def get_current_user(
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
) -> models.User:
try:
payload = decode_token(token)
print(payload)
except jwt.JWTError:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials",
)
user = crud.crud_user.get_user(db, username=payload.get("username"))
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
+31
View File
@@ -0,0 +1,31 @@
from datetime import timedelta, datetime
from passlib.context import CryptContext
from jose import jwt
SECRET_KEY = "6ed23d121dd868fd6c0bf3fce00140ccc196f162f842fda574901052f2127e09"
ACCESS_TOKEN_EXPIRE_MINUTES = 15
AlGORITHM = "HS256"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def create_token(data: dict):
to_encode = data.copy()
expires_delta = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
expire = datetime.now() + expires_delta
to_encode.update({"exp": expire})
encode_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=AlGORITHM)
return encode_jwt
def decode_token(token):
payload = jwt.decode(token, SECRET_KEY, algorithms=[AlGORITHM])
return payload