본문 바로가기
FastAPI

[FastAPI] Request에서 user 정보 얻기

by 혀넝 2023. 4. 23.

해당 내용은 Startlette 공식 페이지와 스택오버플로우를 참고했다.

Reqeust에 유저 정보 담기

FastAPI에서 Dependency를 이용해 token에서 유저 정보를 가져오기 위해서는 Request를 사용할 수 있다.

async def get_current_user(req: Request):
    try:
        token = req.headers.get("authorization")

        secret_key = token_settings.secret_key
        algorithms = token_settings.algorithm
        verified_token = jwt.decode(token, secret_key, algorithms=algorithms)
    except jwt.ExpiredSignatureError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="token expired",
        )

    req.state.user_id = verified_token["user_id"]

Request에 대해서 Startlette에서는 다음과 같이 설명을 하고 있다.

  • Request는 Starlette에서 제공하는 클래스로, 아래와 같은 역할을 한다.
    • request.headers: header에 담긴 값을 얻을 수 있다.
    • request.query_params: query parameter에 담긴 정보를 얻을 수 있다.
    • request.path_params: path parameter에 담긴 정보를 딕셔너리 형태로 얻을 수 있다.
    • request.state: 추가적인 정보를 request에 담고 싶을 때 사용할 수 있다.

코드의 마지막줄과 같이 request에 추가적인 정보를 담기 위해서는 reuqest.state.user_id와 같이 사용할 수 있다.
해당 함수는 FastAPI의 Dependency에 사용되고, 다른 함수에서 유저 정보를 가져올 때도 Request를 사용한다.

 

유저 정보 가져오기

예를 들어 다른 함수에서 해당 기능을 수행하기 위해서는 유저가 권한이 있는지 확인해야 하는 경우가 있다. 이때 Token을 검사할 수 있는데, 우리는 Request에 그 정보를 담아뒀기 때문에 아래와 같이 사용할 수 있다.

async def get_user(user_id: int):
    user_info = await models.User.filter(id=user_id).first()
    if user_info is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user_info
    

async def update_language(lang: UserLanguageDto, req: Request):
    user = await get_user(req.state.user_id)
    ...
  • get_user 함수는 user_id로 User 모델을 필터링해서 유저가 있는지 확인한다.
  • update_language 함수는 api.py에서 수행되는 함수로, 유저가 자신의 언어 정보를 업데이트할 때 사용한다. 따라서 유저 본인의 언어만 업데이트할 수 있기 때문에 해당 유저가 권한이 있는지 확인해야 한다.
  • req.state.user_id에 user_id가 있으므로 get_user 함수에 넣어서 확인하는 과정을 거친다.

'FastAPI' 카테고리의 다른 글

[FastAPI] 쿠키 설정 및 쿠키 삭제  (0) 2023.05.02
[FastAPI] Pydantic validator의 재사용  (0) 2023.04.21