Config is not properly working with .env file as of now Cost Centre is mostly working, going to work on Accounts now
55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
from datetime import timedelta
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
from ..core.security import (
|
|
Token,
|
|
authenticate_user,
|
|
ACCESS_TOKEN_EXPIRE_MINUTES,
|
|
create_access_token,
|
|
)
|
|
from ..db.session import SessionLocal
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
# Dependency
|
|
def get_db():
|
|
try:
|
|
db = SessionLocal()
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@router.post("/token", response_model=Token)
|
|
async def login_for_access_token(
|
|
form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)
|
|
):
|
|
user = authenticate_user(form_data.username, form_data.password, db)
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect username or password",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
access_token = create_access_token(
|
|
data={
|
|
"sub": user.name,
|
|
"scopes": ["authenticated"]
|
|
+ list(
|
|
set(
|
|
[
|
|
p.name.replace(" ", "-").lower()
|
|
for g in user.groups
|
|
for p in g.roles
|
|
]
|
|
)
|
|
),
|
|
},
|
|
expires_delta=access_token_expires,
|
|
)
|
|
return {"access_token": access_token, "token_type": "bearer"}
|