Get the current user object, redirect to login if not authenticated.
(
request: Request,
db: AsyncSession = Depends(get_db),
settings: Settings = Depends(get_settings),
redirect_on_fail: bool = True,
)
| 115 | |
| 116 | |
| 117 | async def get_current_user( |
| 118 | request: Request, |
| 119 | db: AsyncSession = Depends(get_db), |
| 120 | settings: Settings = Depends(get_settings), |
| 121 | redirect_on_fail: bool = True, |
| 122 | ) -> User: |
| 123 | """Get the current user object, redirect to login if not authenticated.""" |
| 124 | session = request.cookies.get("auth_token") |
| 125 | if not session: |
| 126 | if redirect_on_fail: |
| 127 | raise HTTPException( |
| 128 | status.HTTP_303_SEE_OTHER, |
| 129 | headers={ |
| 130 | "Location": "/auth/login", |
| 131 | "Set-Cookie": _clear_auth_cookie_header(settings), |
| 132 | }, |
| 133 | detail="Authentication required", |
| 134 | ) |
| 135 | else: |
| 136 | return None |
| 137 | |
| 138 | try: |
| 139 | data = decode_jwt_claims(session, settings, required_type="auth_token") |
| 140 | user_id = data["sub"] |
| 141 | except Exception: |
| 142 | if redirect_on_fail: |
| 143 | raise HTTPException( |
| 144 | status.HTTP_303_SEE_OTHER, |
| 145 | headers={ |
| 146 | "Location": "/auth/login", |
| 147 | "Set-Cookie": _clear_auth_cookie_header(settings), |
| 148 | }, |
| 149 | detail="Authentication required", |
| 150 | ) |
| 151 | else: |
| 152 | return None |
| 153 | |
| 154 | result = await db.execute(select(User).where(User.id == user_id)) |
| 155 | user = result.scalar_one_or_none() |
| 156 | if not user: |
| 157 | if redirect_on_fail: |
| 158 | raise HTTPException( |
| 159 | status.HTTP_303_SEE_OTHER, |
| 160 | headers={ |
| 161 | "Location": "/auth/login", |
| 162 | "Set-Cookie": _clear_auth_cookie_header(settings), |
| 163 | }, |
| 164 | detail="Authentication required", |
| 165 | ) |
| 166 | else: |
| 167 | return None |
| 168 | issued_at = datetime.fromtimestamp(int(data["iat"]), tz=timezone.utc).replace( |
| 169 | tzinfo=None |
| 170 | ) |
| 171 | expires_at = datetime.fromtimestamp(int(data["exp"]), tz=timezone.utc).replace( |
| 172 | tzinfo=None |
| 173 | ) |
| 174 | if user.tokens_invalid_before and issued_at < user.tokens_invalid_before: |
no test coverage detected