Skip to content

Two-Factor Authentication API

This API provides endpoints to enable and manage Two-Factor Authentication (2FA) for users. Users can create or update their 2FA status, and an OTP will be sent to their email for verification.


1. Create Two-Factor Authentication

Endpoint: api/v1/accounts/twofa/
Method: POST
Permissions: IsAuthenticated

This endpoint creates a Two-Factor Authentication entry for the user and sends an OTP to the user's email. The 2FA status will remain disabled (is_enabled=False) until the OTP is verified.

Request Payload

{
  "email": "user@example.com"
}

Response Payload (Success)

{
  "message": "Two-factor authentication created, OTP sent.",
  "totp_secret": "secret-key-for-totp"
}

Response Payload (Error - Validation)

{
  "email": ["This field is required."]
}

Response Payload (Error - Server)

{
  "error": "Error message"
}

2. Update Two-Factor Authentication

Endpoint: api/v1/accounts/twofa/<str:pk>/
Method: PATCH
Permissions: IsAuthenticated

This endpoint updates an existing Two-Factor Authentication entry and sends a new OTP to the user's email.

Request Payload

{
  "email": "user@example.com"
}

Response Payload (Success)

{
  "detail": "Two-factor authentication status updated, OTP sent."
}

Response Payload (Error - Not Found)

{
  "error": "Two-factor authentication object does not exist."
}

Response Payload (Error - Validation)

{
  "email": ["This field is required."]
}

3. Verify Two-Factor Authentication OTP

This API provides an endpoint to verify the OTP sent to the user's email and enable Two-Factor Authentication. It also allows registering the user's device.

Endpoint: api/v1/accounts/security/verify/2fa_otp/
Method: POST
Permissions: IsAuthenticated

This endpoint verifies the OTP sent to the user's email. If the OTP is valid, it enables Two-Factor Authentication for the user and registers the user's device.

Request Payload

{
  "otp": "123456",
  "device_name": "John's iPhone",
  "device_uuid": "unique-device-identifier"
}

Response Payload (Success)

{
  "message": "Two-factor authentication enabled and device registered successfully."
}

Response Payload (Error - Invalid OTP)

{
  "error": "Invalid OTP."
}

Response Payload (Error - OTP Expired)

{
  "error": "OTP cannot be verified"
}

Response Payload (Error - 2FA Record Not Found)

{
  "error": "Two-factor authentication record not found."
}

Response Payload (Error - Device Validation)

{
  "device_name": ["This field is required."]
}