# -*- coding: utf-8 -*-

from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _


class PasswordExpiryMiddleware():

    def process_request(self, request):
        """
        Enforce the password security policy.

        Each time a request is made, we check that the logged-in user's
        password is still valid, and if not, we redirect them to the password
        change form, for immediate action.

        The only alternative for the user is then to go to the logout page,
        which is not affected by the restriction.
        """
        user = request.user

        url = request.path
        logout_url = reverse('logout')
        password_change_url = reverse('accounts:password_change')

        if (settings.PASSWORD_EXTRA_SECURITY
                and url != logout_url
                and url != password_change_url
                and user.is_authenticated()
                and not user.is_anonymous()):

            if request.user.check_password_expiry():
                messages.error(request, _(
                    u"Your password has expired. Please choose a new one now."
                ))
                return HttpResponseRedirect(password_change_url)
