Пример #1
0
 def __init__(self, *args, **kwargs):
     super(LoginViaToken, self).__init__(*args, **kwargs)
     fields_ordering = ['token', 'region']
     if getattr(settings, 'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT', False):
         self.fields['domain'] = forms.CharField(
             label=_("Domain"),
             required=True,
             widget=forms.TextInput(attrs={"autofocus": "autofocus"}))
         self.fields['token'].widget = forms.widget.TextInput()
         fields_ordering = ['domain', 'token', 'region']
     self.fields['region'].choices = self.get_region_choices()
     if len(self.fields['region'].choices) == 1:
         self.fields['region'].initial = self.fields['region'].choices[0][0]
         self.fields['region'].widget = forms.widget.HiddenInput()
     elif len(self.fields['region'].choices) > 1:
         self.fields['region'].initial = self.request.COOKIES.get(
             'login_region')
     if utils.is_websso_enabled():
         initial = getattr(settings, 'WEBSSO_INITIAL_CHOICE', 'credentials')
         self.fields['auth_type'] = forms.ChoiceField(
             label=("Authenticate using"),
             choices=getattr(settings, 'WEBSSO_CHOICES', ()),
             required=False,
             initial=initial)
         fields_ordering.insert(0, 'auth_type')
     elif getattr(settings, 'WEBSSO_ENABLED', False):
         msg = ("Websso is enabled but horizon is not configured to work " +
                "with keystone version 3 or above.")
         LOG.warning(msg)
     if django.VERSION >= (1, 7):
         self.fields = collections.OrderedDict(
             (key, self.fields[key]) for key in fields_ordering)
     else:
         self.fields.keyOrder = fields_ordering
Пример #2
0
def websso(request):

    if is_websso_enabled():
        return basic_websso(request)

    tempDict = {
        'error_header': _("Web SSO error"),
        'error_text': _("Web SSO is not supported"),
        'redirect_url': '/dashboard',
        'redirect_label': _("Home")
    }
    return shortcuts.render(request, 'aai_error.html', tempDict)
Пример #3
0
    def __init__(self, *args, **kwargs):
        super(Login, self).__init__(*args, **kwargs)
        fields_ordering = ['username', 'password', 'region']
        if getattr(settings,
                   'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT',
                   False):
            last_domain = self.request.COOKIES.get('login_domain', None)
            if getattr(settings,
                       'OPENSTACK_KEYSTONE_DOMAIN_DROPDOWN',
                       False):
                self.fields['domain'] = forms.ChoiceField(
                    label=_("Domain"),
                    initial=last_domain,
                    required=True,
                    choices=getattr(settings,
                                    'OPENSTACK_KEYSTONE_DOMAIN_CHOICES',
                                    ()))
            else:
                self.fields['domain'] = forms.CharField(
                    initial=last_domain,
                    label=_("Domain"),
                    required=True,
                    widget=forms.TextInput(attrs={"autofocus": "autofocus"}))
            self.fields['username'].widget = forms.widgets.TextInput()
            fields_ordering = ['domain', 'username', 'password', 'region']
        self.fields['region'].choices = self.get_region_choices()
        if len(self.fields['region'].choices) == 1:
            self.fields['region'].initial = self.fields['region'].choices[0][0]
            self.fields['region'].widget = forms.widgets.HiddenInput()
        elif len(self.fields['region'].choices) > 1:
            self.fields['region'].initial = self.request.COOKIES.get(
                'login_region')

        # if websso is enabled and keystone version supported
        # prepend the websso_choices select input to the form
        if utils.is_websso_enabled():
            initial = getattr(settings, 'WEBSSO_INITIAL_CHOICE', 'credentials')
            self.fields['auth_type'] = forms.ChoiceField(
                label=_("Authenticate using"),
                choices=getattr(settings, 'WEBSSO_CHOICES', ()),
                required=False,
                initial=initial)
            # add auth_type to the top of the list
            fields_ordering.insert(0, 'auth_type')

        # websso is enabled, but keystone version is not supported
        elif getattr(settings, 'WEBSSO_ENABLED', False):
            msg = ("Websso is enabled but horizon is not configured to work " +
                   "with keystone version 3 or above.")
            LOG.warning(msg)
        self.fields = collections.OrderedDict(
            (key, self.fields[key]) for key in fields_ordering)
Пример #4
0
    def __init__(self, *args, **kwargs):
        super(Login, self).__init__(*args, **kwargs)
        fields_ordering = ['username', 'password', 'region']
        if getattr(settings,
                   'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT',
                   False):
            last_domain = self.request.COOKIES.get('login_domain', None)
            if getattr(settings,
                       'OPENSTACK_KEYSTONE_DOMAIN_DROPDOWN',
                       False):
                self.fields['domain'] = forms.ChoiceField(
                    label=_("Domain"),
                    initial=last_domain,
                    required=True,
                    choices=getattr(settings,
                                    'OPENSTACK_KEYSTONE_DOMAIN_CHOICES',
                                    ()))
            else:
                self.fields['domain'] = forms.CharField(
                    initial=last_domain,
                    label=_("Domain"),
                    required=True,
                    widget=forms.TextInput(attrs={"autofocus": "autofocus"}))
            self.fields['username'].widget = forms.widgets.TextInput()
            fields_ordering = ['domain', 'username', 'password', 'region']
        self.fields['region'].choices = self.get_region_choices()
        if len(self.fields['region'].choices) == 1:
            self.fields['region'].initial = self.fields['region'].choices[0][0]
            self.fields['region'].widget = forms.widgets.HiddenInput()
        elif len(self.fields['region'].choices) > 1:
            self.fields['region'].initial = self.request.COOKIES.get(
                'login_region')

        # if websso is enabled and keystone version supported
        # prepend the websso_choices select input to the form
        if utils.is_websso_enabled():
            initial = getattr(settings, 'WEBSSO_INITIAL_CHOICE', 'credentials')
            self.fields['auth_type'] = forms.ChoiceField(
                label=_("Authenticate using"),
                choices=getattr(settings, 'WEBSSO_CHOICES', ()),
                required=False,
                initial=initial)
            # add auth_type to the top of the list
            fields_ordering.insert(0, 'auth_type')

        # websso is enabled, but keystone version is not supported
        elif getattr(settings, 'WEBSSO_ENABLED', False):
            msg = ("Websso is enabled but horizon is not configured to work " +
                   "with keystone version 3 or above.")
            LOG.warning(msg)
        self.fields = collections.OrderedDict(
            (key, self.fields[key]) for key in fields_ordering)
def websso(request):

    if not is_websso_enabled():
        tempDict = {
            'error_header': _("Web SSO error"),
            'error_text': _("Web SSO is not supported"),
            'redirect_url': '/dashboard',
            'redirect_label': _("Home")
        }
        return shortcuts.render(request, 'aai_error.html', tempDict)

    tmpresp = basic_websso(request)
    tmpresp.delete_cookie(AUTHZCOOKIE)
    return tmpresp
def login(request):

    if request.method == 'POST' and is_websso_enabled():
        auth_type = request.POST.get('auth_type', 'credentials')
        auth_url = request.POST.get('region', None)

        if auth_type != 'credentials' and auth_url != None:
            url = get_websso_url(request, auth_url, auth_type)
            tmpresp = shortcuts.redirect(url)
            tmpresp.set_cookie(AUTHZCOOKIE, auth_type)
            return tmpresp

    result = basic_login(request)
    if request.user.is_authenticated and request.user.is_superuser:
        checkFederationSetup(request)
    return result
def websso(request):

    if not is_websso_enabled():
        tempDict = {
            'error_header' : _("Web SSO error"),
            'error_text' : _("Web SSO is not supported"),
            'redirect_url' : '/dashboard',
            'redirect_label' : _("Home")
        }
        return shortcuts.render(request, 'aai_error.html', tempDict)

    code = request.POST.get('code', '200')
    if code <> '200':
        res = django_http.HttpResponseRedirect(settings.LOGIN_URL)
        res.set_cookie('logout_reason', "SSO unauthorized: %s" % code, max_age=10)
        return res

    return basic_websso(request)
Пример #8
0
def token(request, template_name = None, extra_context=None, **kwargs):
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and auth_type != 'credentials':
            auth_url = request.POST.get('region')
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)
    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_loginviatoken.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/loginviatoken.html'
    res = django_auth_views.login(request, template_name=template_name, authentication_form=form, extra_context = extra_context, **kwargs)
    if request.user.is_authentication():
        auth_user.set_session_form_user(request, request.user)
        regions = dict(forms.LoginViaToken.get_region_choices())
        region = request.user.endpoint
        region_name = region.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
    return res
Пример #9
0
 def __init__(self, *args, **kwargs):
     super(LoginViaToken, self).__init__(*args, **kwargs)
     fields_ordering = ['token', 'region']
     if getattr(settings, 'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT',
                False):
         self.fields['domain'] = forms.CharField(
             label =_("Domain"),
             required = True,
             widget = forms.TextInput(attrs={"autofocus":"autofocus"})
         )
         self.fields['token'].widget = forms.widget.TextInput()
         fields_ordering = ['domain', 'token', 'region']
     self.fields['region'].choices = self.get_region_choices()
     if len(self.fields['region'].choices) == 1:
         self.fields['region'].initial = self.fields['region'].choices[0][0]
         self.fields['region'].widget = forms.widget.HiddenInput()
     elif len(self.fields['region'].choices) > 1:
         self.fields['region'].initial = self.request.COOKIES.get('login_region')
     if utils.is_websso_enabled():
         initial = getattr(settings, 'WEBSSO_INITIAL_CHOICE', 'credentials')
         self.fields['auth_type'] = forms.ChoiceField(
             label = ("Authenticate using"),
             choices = getattr(settings, 'WEBSSO_CHOICES', ()),
             required = False,
             initial = initial
         )
         fields_ordering.insert(0, 'auth_type')
     elif getattr(settings, 'WEBSSO_ENABLED', False):
         msg = ("Websso is enabled but horizon is not configured to work " + "with keystone version 3 or above.")
         LOG.warning(msg)
     if django.VERSION >= (1,7):
         self.fields = collections.OrderedDict(
             (key, self.fields[key]) for key in fields_ordering
         )
     else:
         self.fields.keyOrder = fields_ordering
Пример #10
0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf.urls import patterns
from django.conf.urls import url

from openstack_auth import utils

utils.patch_middleware_get_user()


urlpatterns = patterns(
    'openstack_auth.views',
    url(r"^login/$", "login", name='login'),
    url(r"^logout/$", 'logout', name='logout'),
    url(r'^switch/(?P<tenant_id>[^/]+)/$', 'switch', name='switch_tenants'),
    url(r'^switch_services_region/(?P<region_name>[^/]+)/$', 'switch_region',
        name='switch_services_region')
)

if utils.is_websso_enabled():
    urlpatterns += patterns(
        'openstack_auth.views',
        url(r"^websso/$", "websso", name='websso')
    )
Пример #11
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and auth_type != 'credentials':
            auth_url = request.POST.get('region')
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated() and
                auth.REDIRECT_FIELD_NAME not in request.GET and
                auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        # NOTE(saschpe): Since https://code.djangoproject.com/ticket/15198,
        # the 'request' object is passed directly to AuthenticationForm in
        # django.contrib.auth.views#login:
        if django.VERSION >= (1, 6):
            form = functional.curry(forms.Login)
        else:
            form = functional.curry(forms.Login, request)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        region_name = regions.get(region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
    return res
Пример #12
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and auth_type != 'credentials':
            auth_url = request.POST.get('region')
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated()
                and auth.REDIRECT_FIELD_NAME not in request.GET
                and auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        form = functional.curry(forms.Login)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated():
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        login_region = request.POST.get('region')
        region_name = regions.get(login_region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        expiration_time = request.user.time_until_expiration()
        threshold_days = getattr(settings,
                                 'PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS', -1)
        if expiration_time is not None and \
                expiration_time.days <= threshold_days:
            expiration_time = str(expiration_time).rsplit(':', 1)[0]
            msg = (_('Please consider changing your password, it will expire'
                     ' in %s minutes') % expiration_time).replace(
                         ':', ' Hours and ')
            messages.warning(request, msg)
    return res
Пример #13
0
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf.urls import url
from django.views import generic

from openstack_auth import utils
from openstack_auth import views

utils.patch_middleware_get_user()

urlpatterns = [
    url(r"^login/$", views.login, name='login'),
    url(r"^logout/$", views.logout, name='logout'),
    url(r'^switch/(?P<tenant_id>[^/]+)/$', views.switch,
        name='switch_tenants'),
    url(r'^switch_services_region/(?P<region_name>[^/]+)/$',
        views.switch_region,
        name='switch_services_region'),
    url(r'^switch_keystone_provider/(?P<keystone_provider>[^/]+)/$',
        views.switch_keystone_provider,
        name='switch_keystone_provider')
]

if utils.is_websso_enabled():
    urlpatterns += [
        url(r"^websso/$", views.websso, name='websso'),
        url(r"^error/$",
            generic.TemplateView.as_view(template_name="403.html"))
    ]
Пример #14
0
def login(request):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and the default redirect
    # redirect to the default websso url
    if (request.method == 'GET' and utils.is_websso_enabled and
            utils.is_websso_default_redirect()):
        protocol = utils.get_websso_default_redirect_protocol()
        region = utils.get_websso_default_redirect_region()
        origin = utils.build_absolute_uri(request, '/auth/websso/')
        url = ('%s/auth/OS-FEDERATION/websso/%s?origin=%s' %
               (region, protocol, origin))
        return shortcuts.redirect(url)

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        request.session['auth_type'] = auth_type
        if utils.is_websso_enabled() and auth_type != 'credentials':
            region_id = request.POST.get('region')
            auth_url = getattr(settings, 'WEBSSO_KEYSTONE_URL', None)
            if auth_url is None:
                auth_url = forms.get_region_endpoint(region_id)
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated and
                auth.REDIRECT_FIELD_NAME not in request.GET and
                auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(settings.AVAILABLE_REGIONS)
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        form = functional.curry(forms.Login)
    else:
        form = functional.curry(forms.Login, initial=initial)

    choices = settings.WEBSSO_CHOICES
    extra_context = {
        'redirect_field_name': auth.REDIRECT_FIELD_NAME,
        'csrf_failure': request.GET.get('csrf_failure'),
        'show_sso_opts': utils.is_websso_enabled() and len(choices) > 1,
    }

    if request.is_ajax():
        template_name = 'auth/_login.html'
        extra_context['hide'] = True
    else:
        template_name = 'auth/login.html'

    try:
        res = django_auth_views.LoginView.as_view(
            template_name=template_name,
            redirect_field_name=auth.REDIRECT_FIELD_NAME,
            form_class=form,
            extra_context=extra_context,
            redirect_authenticated_user=False)(request)
    except exceptions.KeystonePassExpiredException as exc:
        res = django_http.HttpResponseRedirect(
            reverse('password', args=[exc.user_id]))
        msg = _("Your password has expired. Please set a new password.")
        res.set_cookie('logout_reason', msg, max_age=10)

    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated:
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.get_region_choices())
        region = request.user.endpoint
        login_region = request.POST.get('region')
        region_name = regions.get(login_region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        expiration_time = request.user.time_until_expiration()
        threshold_days = settings.PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS
        if (expiration_time is not None and
                expiration_time.days <= threshold_days and
                expiration_time > datetime.timedelta(0)):
            expiration_time = str(expiration_time).rsplit(':', 1)[0]
            msg = (_('Please consider changing your password, it will expire'
                     ' in %s minutes') %
                   expiration_time).replace(':', ' Hours and ')
            messages.warning(request, msg)
    return res
Пример #15
0
def login(request, template_name=None, extra_context=None, **kwargs):
    """Logs a user in using the :class:`~openstack_auth.forms.Login` form."""

    # If the user enabled websso and the default redirect
    # redirect to the default websso url
    if (request.method == 'GET' and utils.is_websso_enabled and
            utils.is_websso_default_redirect()):
        protocol = utils.get_websso_default_redirect_protocol()
        region = utils.get_websso_default_redirect_region()
        origin = utils.build_absolute_uri(request, '/auth/websso/')
        url = ('%s/auth/OS-FEDERATION/websso/%s?origin=%s' %
               (region, protocol, origin))
        return shortcuts.redirect(url)

    # If the user enabled websso and selects default protocol
    # from the dropdown, We need to redirect user to the websso url
    if request.method == 'POST':
        auth_type = request.POST.get('auth_type', 'credentials')
        if utils.is_websso_enabled() and auth_type != 'credentials':
            region_id = request.POST.get('region')
            auth_url = getattr(settings, 'WEBSSO_KEYSTONE_URL',
                               forms.get_region_endpoint(region_id))
            url = utils.get_websso_url(request, auth_url, auth_type)
            return shortcuts.redirect(url)

    if not request.is_ajax():
        # If the user is already authenticated, redirect them to the
        # dashboard straight away, unless the 'next' parameter is set as it
        # usually indicates requesting access to a page that requires different
        # permissions.
        if (request.user.is_authenticated and
                auth.REDIRECT_FIELD_NAME not in request.GET and
                auth.REDIRECT_FIELD_NAME not in request.POST):
            return shortcuts.redirect(settings.LOGIN_REDIRECT_URL)

    # Get our initial region for the form.
    initial = {}
    current_region = request.session.get('region_endpoint', None)
    requested_region = request.GET.get('region', None)
    regions = dict(getattr(settings, "AVAILABLE_REGIONS", []))
    if requested_region in regions and requested_region != current_region:
        initial.update({'region': requested_region})

    if request.method == "POST":
        form = functional.curry(forms.Login)
    else:
        form = functional.curry(forms.Login, initial=initial)

    if extra_context is None:
        extra_context = {'redirect_field_name': auth.REDIRECT_FIELD_NAME}

    extra_context['csrf_failure'] = request.GET.get('csrf_failure')

    choices = getattr(settings, 'WEBSSO_CHOICES', ())
    extra_context['show_sso_opts'] = (utils.is_websso_enabled() and
                                      len(choices) > 1)

    if not template_name:
        if request.is_ajax():
            template_name = 'auth/_login.html'
            extra_context['hide'] = True
        else:
            template_name = 'auth/login.html'

    res = django_auth_views.login(request,
                                  template_name=template_name,
                                  authentication_form=form,
                                  extra_context=extra_context,
                                  **kwargs)
    # Save the region in the cookie, this is used as the default
    # selected region next time the Login form loads.
    if request.method == "POST":
        utils.set_response_cookie(res, 'login_region',
                                  request.POST.get('region', ''))
        utils.set_response_cookie(res, 'login_domain',
                                  request.POST.get('domain', ''))

    # Set the session data here because django's session key rotation
    # will erase it if we set it earlier.
    if request.user.is_authenticated:
        auth_user.set_session_from_user(request, request.user)
        regions = dict(forms.Login.get_region_choices())
        region = request.user.endpoint
        login_region = request.POST.get('region')
        region_name = regions.get(login_region)
        request.session['region_endpoint'] = region
        request.session['region_name'] = region_name
        expiration_time = request.user.time_until_expiration()
        threshold_days = getattr(
            settings, 'PASSWORD_EXPIRES_WARNING_THRESHOLD_DAYS', -1)
        if expiration_time is not None and \
                expiration_time.days <= threshold_days:
            expiration_time = str(expiration_time).rsplit(':', 1)[0]
            msg = (_('Please consider changing your password, it will expire'
                     ' in %s minutes') %
                   expiration_time).replace(':', ' Hours and ')
            messages.warning(request, msg)
    return res