I needed to add auto-expiry feature for users in a Django project. It turned out to be super simple.
In this case this was made super-easy since I could override User model.
So here is example snippet:
# Need to inherit from AbstractBaseUser as AbstractUser has already defined
# ``is_active`` as a database backed field.
class MyUser(AbstractBaseUser, PermissionsMixin):
# ... You need to define all "profile" fields here since AbstractBaseUser user
# deals only with permissions and friends.
full_name = models.CharField(ugettext_lazy("User full name", ...))
# You will also need this for admin support.
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
@property
def is_active(self) -> bool:
# Your business logic here.
return is_user_active(self)
Default ModelBackend checks is active when logging user in, and when loading user from session, so when user expires they will loose access to the site immediately.