tranny / App /Users /UserRoutes.py
Mbonea's picture
token does not expire
9ad8e24
raw
history blame
1.83 kB
from fastapi import APIRouter, Request, Depends, HTTPException
from .Schemas import BaseRequest, UserSchema
from pydantic import BaseModel
from .Model import User
from sqlalchemy import and_
from fastapi_jwt_auth import AuthJWT
class Settings(BaseModel):
authjwt_secret_key: str = "secret"
authjwt_access_token_expires: bool = False
user_router = APIRouter(tags=["User"])
@AuthJWT.load_config
def get_config():
return Settings()
@user_router.post("/user/register")
async def register_user(user: BaseRequest):
data = await User.objects.filter(email=user.email).first()
if data != None:
return {"code": 400, "message": "user exists", "payload": None}
else:
user.hash_password()
sample = await User.objects.create(**user.dict())
return {"code": 200, "message": "success", "payload": None}
async def get_token_owner(Authorize: AuthJWT = Depends()):
Authorize.jwt_required()
current_user = Authorize.get_jwt_subject()
user = await User.objects.filter(id=int(current_user)).first()
if not user:
raise HTTPException(status_code=401, detail="Invalid Credentials")
return UserSchema.from_orm(user)
@user_router.post("/user/login")
async def register_user(user: BaseRequest, Authorize: AuthJWT = Depends()):
db_user = await User.objects.filter(email=user.email).first()
if not db_user:
raise HTTPException(status_code=401, detail="Invalid Credentials")
if not db_user.verify_password(user.password):
raise HTTPException(status_code=401, detail="Invalid Credentials")
user = UserSchema.from_orm(db_user)
access_token = Authorize.create_access_token(subject=user.id)
return {
"code": 200,
"message": "success",
"payload": db_user.__dict__,
"access_token": access_token,
}