Login problem - cant read get_current_active_user over dependency in student route.
Published: 2024-05-17 00:46:32

Hello guys. I need your help. I've been working on the school project for 1 month and have a problem with part of code when user have to login. The goal of my project is to make a fastapi app with few functionalities: login and logout, and after login app should read some data from student profiles using the mongodb. When I working over swigger user can login and cannot read data about the student profiles before it is authorized. But problem arise when I tried to do that using the login.html page because user can make cookie variable with access token information, but endpoint cant read it after redirection. 
Using next library:

auth_router.py (part of code)

```
`@auth_router.post("/token", response_model=Token)
async def login_for_access_token(response:Response, form_data:Annotated[OAuth2PasswordRequestForm, Depends()]):

    user= get_user_data(form_data.username)
    user = authenticate_user(user,form_data.username, form_data.password)
    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.username}, expires_delta=access_token_expires)
    response.set_cookie(key="access_token", value=f"Bearer {access_token}", httponly=True)
    return {"access_token": access_token, "token_type": "bearer"}


@auth_router.get("/", response_class=HTMLResponse)
async def login_page(request: Request):
    return templejt.TemplateResponse("login.html", {"request": request})


@auth_router.post("/", response_class=HTMLResponse)
async def login(request: Request):
    form_data = LoginForm(request)
    await form_data.create_oauth_form()
# problem occur when i tried to redirect the response to the "/student" endpoint and give that response to login_for_access_token. 
    response = RedirectResponse(url="/auth", status_code=status.HTTP_302_FOUND)
    token_response = await login_for_access_token(response, form_data)
    if "access_token" not in token_response:
        message = "Invalid username or password"
        return templejt.TemplateResponse("login.html", {"request": request, "message": message})
    return response`
```

student_route.py (part of code)


```
# the problem is occurring in code below. can not read 
# current_user: Annotated[User, Depends(get_current_active_user)].


from routers.auth_router import get_current_active_user
import re

student_router = APIRouter(    
    prefix='/student',
    tags=['student']
    )

user_dependency=Annotated[User, Depends(get_current_active_user)]

templejt=Jinja2Templates(directory="templates")
user_dependency=Annotated[User, Depends(get_current_active_user)]
templejt=Jinja2Templates(directory="templates") 
@student_router.get("/", response_class=HTMLResponse)
async def get_all_student(request: Request, current_user: Annotated[User, Depends(get_current_active_user)]):
    print(f"Current user: {current_user.username}")
    studenti = list_serial(studenti_kolekcija.find())
    print("Lista studenata...")
    return templejt.TemplateResponse("read-student.html", {"request": request, "studenti": studenti}) 
```

> decode token for current_user:

```
async def get_current_user(token: str = Cookie(None)):
    print("testing token...")
    if token:
        token = token.replace("Bearer ", "")
        print(f"Token extracted from cookies: {token}")

    if not token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )

    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception

    user = _get_user(username)
    if user is None:
        raise credentials_exception

    return user
```