```python
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, "your_secret_key", algorithms=["HS256"])
user_id = payload.get("sub")
if user_id is None:
raise credentials_exception
# 在这里,你可以检查用户是否存在以及用户所属的组是否存在
# 例如:user = get_user_from_db(user_id)
# if user is None or not user.group_exists:
# raise credentials_exception
except jwt.PyJWTError:
raise credentials_exception
return user_id
@
app.get("/users/me")
async def read_users_me(user_id: str = Depends(get_current_user)):
return {"user_id": user_id}
```