Commit 5f2c46ba authored by Jacek Bzdak's avatar Jacek Bzdak

Django recipies.

parent 20c51b0a
Pipeline #75804199 passed with stages
in 2 minutes and 6 seconds
Expiring users in Django
========================
:date: 2019-08-08
:tags: python,django
:slug: expiring-user
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:
.. code-block:: python
# 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.
\ No newline at end of file
Expiring user passwords in Django
=================================
:date: 2019-08-08
:tags: python,django
:slug: expiring-passwords
I needed to add auto-expiry feature for user passwords in a Django project. It turned out to
be super simple.
Logic is: when expiry occurs user is redirected to a password change page.
.. note::
I'm well aware that recent NIST recommendations discourage this practice,
and I also think that monthly password rotation is moronic idea.
However it is mandated by law in Poland for certain usages.
You can easily implement this as a middleware, which works like that:
.. code-block:: python
class PasswordMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
user = request.user
password_change_path = reverse("password_change")
if user.is_authenticated and password_expired(user):
if request.path != password_change_path:
return redirect(password_change_path)
return self.get_response(request)
And you need to add this to middleware directly **after** ``AuthenticationMiddleware``.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment