Requiring Confirmation for Authenticated Requests

In many applications, it’s desirable to require users to confirm their email address or other information before granting them full access to certain features or resources. This can help prevent spam and ensure the authenticity of user accounts. In this guide, we’ll demonstrate how to implement a confirmation requirement for authenticated requests in FastAPI.

Adding a Confirmation Flag to the User Model

Modify the User Model:

Python

from sqlalchemy import Column, Boolean

class User(Base):
# …
is_verified = Column(Boolean, default=False)

Update the Registration Endpoint:

Python

@router.post(“/register”, response_model=UserSchema)
async def register_user(user: UserCreate, db: Session = Depends(get_db)):
# …
db_user = User(email=user.email, password=hashed_password, is_verified=False)
# …

Enforcing Confirmation in Endpoints

Python

@app.get("/protected")
async def protected_route(current_user: User = Depends(get_current_user)):
    if not current_user.is_verified:
        raise HTTPException(status_code=403, detail="Email confirmation required")

    # ...

Confirmation Email: Send a confirmation email to the user’s registered email address with a link to confirm their account.

Resend Option: Allow users to resend the confirmation email if they don’t receive it.

Expiration: Set an expiration time for confirmation tokens to prevent abuse.

User Experience: Provide clear messaging to guide users through the confirmation process.

By requiring confirmation for authenticated requests, you can enhance the security and reliability of your FastAPI application and protect against unauthorized access.

Configuring Mailgun for Email Integration
Adding a User Confirmation Endpoint

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?