Class Reference
Admin Site
- class two_factor.admin.AdminSiteOTPRequired(name='admin')
AdminSite enforcing OTP verified staff users.
- class two_factor.admin.AdminSiteOTPRequiredMixin
Mixin for enforcing OTP verified staff users.
Custom admin views should either be wrapped using
admin_view()or usehas_permission()in order to secure those views.
Decorators
- django_otp.decorators.otp_required(view=None, redirect_field_name='next', login_url=None, if_configured=False)
Similar to
login_required(), but requires the user to be verified. By default, this redirects users toOTP_LOGIN_URL.- Parameters:
if_configured (bool) – If
True, an authenticated user with no confirmed OTP devices will be allowed. Default isFalse.
Models
- class two_factor.plugins.phonenumber.models.PhoneDevice(*args, **kwargs)
Model with phone number and token seed linked to a user.
- class django_otp.plugins.otp_static.models.StaticDevice(*args, **kwargs)
A static
Devicesimply consists of random tokens shared by the database and the user.These are frequently used as emergency tokens in case a user’s normal device is lost or unavailable. They can be consumed in any order; each token will be removed from the database as soon as it is used.
This model has no fields of its own, but serves as a container for
StaticTokenobjects.- token_set
The RelatedManager for our tokens.
- class django_otp.plugins.otp_static.models.StaticToken(*args, **kwargs)
A single token belonging to a
StaticDevice.- device
ForeignKey: A foreign key to
StaticDevice.
- token
CharField: A random string up to 16 characters.
- class django_otp.plugins.otp_totp.models.TOTPDevice(*args, **kwargs)
A generic TOTP
Device. The model fields mostly correspond to the arguments todjango_otp.oath.totp(). They all have sensible defaults, including the key, which is randomly generated.- key
CharField: A hex-encoded secret key of up to 40 bytes. (Default: 20 random bytes)
- step
PositiveSmallIntegerField: The time step in seconds. (Default: 30)
- t0
BigIntegerField: The Unix time at which to begin counting steps. (Default: 0)
- digits
PositiveSmallIntegerField: The number of digits to expect in a token (6 or 8). (Default: 6)
- tolerance
PositiveSmallIntegerField: The number of time steps in the past or future to allow. For example, if this is 1, we’ll accept any of three tokens: the current one, the previous one, and the next one. (Default: 1)
- drift
SmallIntegerField: The number of time steps the prover is known to deviate from our clock. If
OTP_TOTP_SYNCisTrue, we’ll update this any time we match a token that is not the current one. (Default: 0)
- last_t
BigIntegerField: The time step of the last verified token. To avoid verifying the same token twice, this will be updated on each successful verification. Only tokens at a higher time step will be verified subsequently. (Default: -1)
Middleware
- class django_otp.middleware.OTPMiddleware(get_response=None)
This must be installed after
AuthenticationMiddlewareand performs an analogous function. Just as AuthenticationMiddleware populatesrequest.userbased on session data, OTPMiddleware populatesrequest.user.otp_deviceto theDeviceobject that has verified the user, orNoneif the user has not been verified. As a convenience, this also installsuser.is_verified(), which returnsTrueifuser.otp_deviceis notNone.
Signals
- two_factor.signals.user_verified
Sent when a user is verified against a OTP device. Provides the following arguments:
senderThe class sending the signal (
'two_factor.views.core').userThe user that was verified.
deviceThe OTP device that was used.
requestThe
HttpRequestin which the user was verified.
Utilities
- class two_factor.views.utils.ExtraSessionStorage(*args, **kwargs)
SessionStorage that includes the property validated_step_data for storing cleaned form data per step.
- class two_factor.views.utils.IdempotentSessionWizardView(**kwargs)
WizardView that allows certain steps to be marked non-idempotent, in which case the form is only validated once and the cleaned values stored.
- get_next_step(step=None)
Returns the next step after the given step. If no more steps are available, None will be returned. If the step argument is None, the current step will be determined automatically.
- get_prev_step(step=None)
Returns the previous step before the given step. If there are no steps available, None will be returned. If the step argument is None, the current step will be determined automatically.
- is_step_visible(step, form_class)
Returns whether the given step should be included in the wizard; it is included if either the form is idempotent or not filled in before.
- post(*args, **kwargs)
Check if the current step is still available. It might not be if conditions have changed.
- process_step(form)
Stores the validated data for form and cleans out validated forms for next steps, as those might be affected by the current step. Note that this behaviour is relied upon by the LoginView to prevent users from bypassing the TokenForm by going steps back and changing credentials.
- render_done(form, **kwargs)
This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don’t validate, render_revalidation_failure should get called. If everything is fine call done.
- class two_factor.views.utils.LoginStorage(*args, **kwargs)
SessionStorage that includes the property ‘authenticated_user’ for storing backend authenticated users while logging in.
- two_factor.views.utils.get_remember_device_cookie(user, otp_device_id)
Compile a signed cookie from user.pk, user.password and otp_device_id, but only return the hashed and signatures and omit the data.
The cookie is composed of 3 parts: 1. A timestamp of signing. 2. A hashed value of otp_device_id and the timestamp. 3. A hashed value of user.pk, user.password, otp_device_id and the timestamp.
- two_factor.views.utils.validate_remember_device_cookie(cookie, user, otp_device_id)
Returns True if the cookie was returned by get_remember_device_cookie using the same user.pk, user.password and otp_device_id. Moreover the cookie must not be expired. Returns False if the otp_device_id does not match. Otherwise raises an exception.
Views
- class two_factor.views.LoginView(**kwargs)
View for handling the login process, including OTP verification.
The login process is composed like a wizard. The first step asks for the user’s credentials. If the credentials are correct, the wizard proceeds to the OTP verification step. If the user has a default OTP device configured, that device is asked to generate a token (send sms / call phone) and the user is asked to provide the generated token. The backup devices are also listed, allowing the user to select a backup device for verification.
- class two_factor.views.SetupView(**kwargs)
View for handling OTP setup using a wizard.
The first step of the wizard shows an introduction text, explaining how OTP works and why it should be enabled. The user has to select the verification method (generator / call / sms) in the second step. Depending on the method selected, the third step configures the device. For the generator method, a QR code is shown which can be scanned using a mobile phone app and the user is asked to provide a generated token. For call and sms methods, the user provides the phone number which is then validated in the final step.
- class two_factor.views.SetupCompleteView(**kwargs)
View congratulation the user when OTP setup has completed.
- class two_factor.views.BackupTokensView(**kwargs)
View for listing and generating backup tokens.
A user can generate a number of static backup tokens. When the user loses its phone, these backup tokens can be used for verification. These backup tokens should be stored in a safe location; either in a safe or underneath a pillow ;-).
- class two_factor.views.ProfileView(**kwargs)
View used by users for managing two-factor configuration.
This view shows whether two-factor has been configured for the user’s account. If two-factor is enabled, it also lists the primary verification method and backup verification methods.
- class two_factor.views.DisableView(**kwargs)
View for disabling two-factor for a user’s account.
- class two_factor.plugins.phonenumber.views.PhoneSetupView(**kwargs)
View for configuring a phone number for receiving tokens.
A user can have multiple backup
PhoneDevicefor receiving OTP tokens. If the primary phone number is not available, as the battery might have drained or the phone is lost, these backup phone numbers can be used for verification.
- class two_factor.plugins.phonenumber.views.PhoneDeleteView(**kwargs)
View for removing a phone number used for verification.
View Mixins
- class two_factor.views.mixins.OTPRequiredMixin
View mixin which verifies that the user logged in using OTP.
Note
This mixin should be the left-most base class.
- get_login_url()
Returns login url to redirect to.
- get_verification_url()
Returns verification url to redirect to.
- login_url = None
If
raise_anonymousis set to False, this defines where the user will be redirected to. Defaults totwo_factor:login.
- raise_anonymous = False
Whether to raise PermissionDenied if the user isn’t logged in.
- raise_unverified = False
Whether to raise PermissionDenied if the user isn’t verified.
- redirect_field_name = 'next'
URL query name to use for providing the destination URL.
- verification_url = None
If
raise_unverifiedis set to False, this defines where the user will be redirected to. If set toNone, an explanation will be shown to the user on why access was denied.