add support for django 1.11 in views (#21489)

This commit is contained in:
Elias Showk 2018-05-25 15:32:13 +02:00
parent 3352498ace
commit 737a56f148
17 changed files with 71 additions and 106 deletions

View File

@ -1,10 +1,9 @@
import logging
from django.utils.translation import ugettext as _
from django.shortcuts import render_to_response, render
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import TemplateView
from django.template import RequestContext
from django.template.loader import render_to_string
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
@ -57,8 +56,7 @@ def handle_request(request):
# No SSL entries and no user session, redirect account linking page
if not user and not request.user.is_authenticated():
return render_to_response('auth/account_linking_ssl.html',
context_instance=RequestContext(request))
return render(request, 'auth/account_linking_ssl.html')
# No SSL entries but active user session, perform account linking
if not user and request.user.is_authenticated():
@ -128,12 +126,9 @@ def post_account_linking(request):
return render(request, 'auth/account_linking_ssl.html')
def profile(request, template_name='ssl/profile.html', *args, **kwargs):
context_instance = kwargs.pop('context_instance', None) or \
RequestContext(request)
certificates = models.ClientCertificate.objects.filter(user=request.user)
ctx = { 'certificates': certificates }
return render_to_string(template_name, ctx,
context_instance=context_instance)
return render_to_string(template_name, context=ctx, request=request)
def delete_certificate(request, certificate_pk):
qs = models.ClientCertificate.objects.filter(pk=certificate_pk)

View File

@ -17,7 +17,6 @@ class LoginPasswordBackend(object):
return 'password'
def login(self, request, *args, **kwargs):
context_instance = kwargs.get('context_instance', None)
is_post = request.method == 'POST' and self.submit_name in request.POST
data = request.POST if is_post else None
form = forms.AuthenticationForm(request=request, data=data)
@ -39,8 +38,7 @@ class LoginPasswordBackend(object):
return utils.login(request, form.get_user(), how,
service_slug=request.GET.get(constants.SERVICE_FIELD_NAME))
context['form'] = form
return render(request, 'authentic2/login_password_form.html', context,
context_instance=context_instance)
return render(request, 'authentic2/login_password_form.html', context=context)
def profile(self, request, *args, **kwargs):
return views.login_password_profile(request, *args, **kwargs)

View File

@ -1,7 +1,6 @@
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.shortcuts import render
from authentic2.saml.models import LibertyProvider
@ -11,11 +10,10 @@ def consent_federation(request, nonce = '', next = None, provider_id = None):
'''On a GET produce a form asking for consentment,
On a POST handle the form and redirect to next'''
if request.method == "GET":
return render_to_response('interaction/consent_federation.html',
return render(request, 'interaction/consent_federation.html', context=
{'provider_id': request.GET.get('provider_id', ''),
'nonce': request.GET.get('nonce', ''),
'next': request.GET.get('next', '')},
context_instance=RequestContext(request))
'next': request.GET.get('next', '')})
else:
next = '/'
if 'next' in request.POST:
@ -57,13 +55,12 @@ def consent_attributes(request, nonce = '', next = None, provider_id = None):
name = request.GET.get('provider_id', '')
if provider:
name = provider.name or name
return render_to_response('interaction/consent_attributes.html',
return render(request, 'interaction/consent_attributes.html', context=
{'provider_id': name,
'attributes': attributes,
'allow_selection': request.session['allow_attributes_selection'],
'nonce': request.GET.get('nonce', ''),
'next': next},
context_instance=RequestContext(request))
'next': next})
elif request.method == "POST":
if request.session['allow_attributes_selection']:

View File

@ -123,7 +123,7 @@ class SamlBackend(object):
url = '{0}?provider_id={1}&nonce={2}'.format(
url, urllib.quote(provider_id), nonce)
name = name or provider_id
code = render_to_string('idp/saml/logout_fragment.html', {
code = render_to_string('idp/saml/logout_fragment.html', context={
'needs_iframe': policy.needs_iframe_logout,
'name': name, 'url': url,
'iframe_timeout': policy.iframe_logout_timeout})

View File

@ -46,7 +46,7 @@ from django.contrib import messages
from authentic2.compat import get_user_model
import authentic2.views as a2_views
from authentic2.saml.models import (LibertyArtifact,
LibertySession, LibertyFederation,
LibertySession, LibertyFederation,
nameid2kwargs, saml2_urn_to_nidformat,
nidformat_to_saml2_urn, save_key_values, get_and_delete_key_values,
LibertyProvider, LibertyServiceProvider, SAMLAttribute, NAME_ID_FORMATS)
@ -488,7 +488,7 @@ def sso(request):
add_url += '?' + urllib.urlencode({ 'entity_id': provider_id })
return render(request,
'idp/saml/unknown_provider.html',
{ 'entity_id': provider_id,
context={ 'entity_id': provider_id,
'add_url': add_url,
})
else:
@ -1566,7 +1566,7 @@ def slo_return(request):
logger.info('return from redirect')
relay_state = request.GET.get('RelayState')
if not relay_state:
return error_redirect(request, N_('slo no relay state in response'),
return error_redirect(request, N_('slo no relay state in response'),
default_url=icon_url('ko'))
logger.debug('relay_state %r', relay_state)
try:

View File

@ -7,7 +7,7 @@ from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.utils.html import format_html
from django.core.mail import EmailMultiAlternatives
from django.template import loader
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.contrib import messages
@ -221,10 +221,10 @@ class UserDetailView(OtherActionsMixin, BaseDetailView):
"""
Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
"""
subject = loader.render_to_string(subject_template_name, context)
subject = render_to_string(subject_template_name, context=context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
body = render_to_string(email_template_name, context=context)
email_message = EmailMultiAlternatives(subject, body, to=[to_email])
email_message.send()

View File

@ -220,7 +220,7 @@ class DisplayMessageBeforeRedirectMiddleware(object):
if not some_message:
return response
return render(request, 'authentic2/display_message_and_continue.html',
{'url': url, 'only_info': only_info})
context={'url': url, 'only_info': only_info})
class ServiceAccessControlMiddleware(object):

View File

@ -6,16 +6,13 @@ from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _, ugettext
from django.forms import ModelForm, Form, CharField, PasswordInput, EmailField
from django.utils.datastructures import SortedDict
from django.db.models.fields import FieldDoesNotExist
from django.forms.util import ErrorList
from django.forms.utils import ErrorList
from django.contrib.auth.models import BaseUserManager, Group
from django.contrib.auth import forms as auth_forms, get_user_model, REDIRECT_FIELD_NAME
from django.core.mail import send_mail
from django.core import signing
from django.template import RequestContext
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator

View File

@ -9,10 +9,9 @@ import datetime
import requests
from authentic2.compat_lasso import lasso
from django.template import RequestContext
from django.conf import settings
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.core.exceptions import ValidationError
from authentic2.saml.models import (LibertyFederation, LibertyProvider,
@ -181,23 +180,21 @@ def return_saml2_request(request, profile, title=''):
def return_saml2(request, profile, field_name, title=''):
'''Helper to handle SAMLv2 bindings to emit request and responses'''
context_instance = RequestContext(request)
logger.debug('profile.msgBody: %r', profile.msgBody)
logger.debug('profile.msgUrl: %r', profile.msgUrl)
logger.debug('profile.msgRelayState: %r', profile.msgRelayState)
logger.debug('field_name: %s', field_name)
if profile.msgBody:
if profile.msgUrl:
return render_to_response(
return render(request,
'saml/post_form.html',
{
context={
'title': title,
'url': profile.msgUrl,
'fieldname': field_name,
'body': profile.msgBody,
'relay_state': profile.msgRelayState
},
context_instance=context_instance)
})
return HttpResponse(profile.msgBody, content_type='text/xml')
elif profile.msgUrl:
return HttpResponseRedirect(profile.msgUrl)
@ -503,13 +500,12 @@ def error_page(request, message, back=None, logger=None, warning=False):
back = '/'
redirection_timeout = getattr(settings, 'REDIRECTION_TIMEOUT_AFTER_ERROR',
2000)
return render_to_response('error.html',
{
return render(request, 'error.html',
context={
'msg': message,
'back': back,
'redir_timeout': redirection_timeout
},
context_instance=RequestContext(request))
})
def redirect_next(request, next):

View File

@ -23,7 +23,7 @@ from django.contrib.auth import (REDIRECT_FIELD_NAME, login as auth_login, SESSI
HASH_SESSION_KEY, BACKEND_SESSION_KEY, authenticate,
get_user_model)
from django import forms
from django.forms.util import ErrorList
from django.forms.utils import ErrorList
from django.forms.utils import to_current_timezone
from django.utils import timezone
from django.utils import html, http
@ -36,7 +36,6 @@ from django.core.urlresolvers import reverse, NoReverseMatch
from django.utils.formats import localize
from django.contrib import messages
from django.utils.functional import empty
from django.template import RequestContext
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.shortcuts import render
@ -594,26 +593,21 @@ def send_templated_mail(user_or_email, template_names, context=None, with_html=T
user_or_email = user_or_email.email
if not request:
request = middleware.StoreRequestMiddleware().get_request()
if request:
ctx = RequestContext(request)
ctx.update(context or {})
else:
ctx = context or {}
subject_template_names = [template_name + '_subject.txt' for template_name in template_names]
subject_template_names += legacy_subject_templates or []
subject = render_to_string(subject_template_names, ctx).strip()
subject = render_to_string(subject_template_names, context=context, request=request).strip()
body_template_names = [template_name + '_body.txt' for template_name in template_names]
body_template_names += legacy_body_templates or []
body = render_to_string(body_template_names, ctx)
body = render_to_string(body_template_names, context=context, request=request)
html_body = None
html_body_template_names = [template_name + '_body.html' for template_name in template_names]
html_body_template_names += legacy_html_body_templates or []
if with_html:
try:
html_body = render_to_string(html_body_template_names, ctx)
html_body = render_to_string(html_body_template_names, context=context, request=request)
except TemplateDoesNotExist:
html_body = None
send_mail(subject, body, from_email or settings.DEFAULT_FROM_EMAIL, [user_or_email],

View File

@ -9,25 +9,22 @@ import collections
import django
from django.conf import settings
from django.shortcuts import render_to_response, render
from django.template import RequestContext
from django.template.loader import render_to_string, select_template
from django.shortcuts import render
from django.template.loader import render_to_string
from django.views.generic.edit import UpdateView, FormView
from django.views.generic import RedirectView, TemplateView
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.contrib.auth import SESSION_KEY
from django import http, shortcuts
from django.core import mail, signing
from django.core import signing
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.utils.http import urlencode, same_origin
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import (HttpResponseRedirect, HttpResponseForbidden,
HttpResponse)
from django.core.exceptions import PermissionDenied
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from django.views.decorators.cache import never_cache
from django.contrib.auth.decorators import login_required
@ -51,7 +48,7 @@ def redirect(request, next, template_name='redirect.html'):
if not next.startswith('http'):
next = '/%s%s' % (request.get_host(), next)
logging.info('Redirect to %r' % next)
return render_to_response(template_name, { 'next': next })
return render(request, template_name, context={ 'next': next })
def server_error(request, template_name='500.html'):
@ -291,14 +288,14 @@ def login(request, template_name='authentic2/login.html',
registration_url = utils.get_registration_url(
request, service_slug=request.GET.get(constants.SERVICE_FIELD_NAME))
context_instance = RequestContext(request, {
context = {
'cancel': nonce is not None,
'can_reset_password': app_settings.A2_CAN_RESET_PASSWORD,
'registration_authorized': getattr(settings, 'REGISTRATION_OPEN', True),
'registration_url': registration_url,
})
}
if django.VERSION >= (1, 8, 0):
context_instance['add_to_blocks'] = collections.defaultdict(lambda: [])
context['add_to_blocks'] = collections.defaultdict(lambda: [])
# Cancel button
if request.method == "POST" \
@ -330,7 +327,7 @@ def login(request, template_name='authentic2/login.html',
blocks.append(block)
else: # New frontends API
parameters = {'request': request,
'context_instance': context_instance}
'context': context}
block = utils.get_backend_method(frontend, 'login', parameters)
# If a login frontend method returns an HttpResponse with a status code != 200
# this response is returned.
@ -359,20 +356,20 @@ def login(request, template_name='authentic2/login.html',
context.update(frontend.get_context())
sub_template_name = frontend.template()
block['content'] = render_to_string(
sub_template_name, context,
context_instance=context_instance)
sub_template_name, context=context,
request=request)
request.session.set_test_cookie()
# legacy context variable
rendered_forms = [(block['name'], block['content']) for block in blocks]
return render_to_response(template_name, {
return render(request, template_name, context={
'methods': rendered_forms,
# new definition
'blocks': collections.OrderedDict((block['id'], block) for block in blocks),
redirect_field_name: redirect_to,
}, context_instance=context_instance)
})
def service_list(request):
@ -412,9 +409,9 @@ class ProfileView(cbv.TemplateNamesMixin, TemplateView):
request = self.request
context_instance = RequestContext(request, ctx)
context = ctx
if django.VERSION >= (1, 8, 0):
context_instance['add_to_blocks'] = collections.defaultdict(lambda: [])
context['add_to_blocks'] = collections.defaultdict(lambda: [])
if request.method == "POST":
for frontend in frontends:
if 'submit-%s' % frontend.id in request.POST:
@ -479,7 +476,7 @@ class ProfileView(cbv.TemplateNamesMixin, TemplateView):
# Credentials management
parameters = {'request': request,
'context_instance': context_instance}
'context': context}
profiles = [utils.get_backend_method(frontend, 'profile', parameters)
for frontend in frontends]
# Old frontends data structure for templates
@ -494,7 +491,7 @@ class ProfileView(cbv.TemplateNamesMixin, TemplateView):
for idp_backend in idp_backends:
if hasattr(idp_backend, 'federation_management'):
federation_management.extend(idp_backend.federation_management(request))
context_instance.update({
context.update({
'frontends_block': blocks,
'frontends_block_by_id': blocks_by_id,
'profile': profile,
@ -504,8 +501,8 @@ class ProfileView(cbv.TemplateNamesMixin, TemplateView):
'allow_password_change': app_settings.A2_REGISTRATION_CAN_CHANGE_PASSWORD,
'federation_management': federation_management,
})
hooks.call_hooks('modify_context_data', self, context_instance)
return context_instance
hooks.call_hooks('modify_context_data', self, context)
return context
profile = login_required(ProfileView.as_view())
@ -537,7 +534,7 @@ def logout(request, next_url=None, default_next_url='auth_homepage',
local_logout_done = False
if request.user.is_authenticated():
if check_referer and not utils.check_referer(request):
return render(request, 'authentic2/logout_confirm.html', ctx)
return render(request, 'authentic2/logout_confirm.html', context=ctx)
do_local = do_local and 'local' in request.GET
if not do_local:
l = logout_list(request)
@ -549,7 +546,7 @@ def logout(request, next_url=None, default_next_url='auth_homepage',
ctx['next_url'] = next_url
ctx['logout_list'] = l
ctx['message'] = _('Logging out from all your services')
return render(request, template, ctx)
return render(request, template, context=ctx)
# Get redirection targets for full logout with redirections
# (needed before local logout)
targets = redirect_logout_list(request)
@ -579,14 +576,13 @@ def logout(request, next_url=None, default_next_url='auth_homepage',
def login_password_profile(request, *args, **kwargs):
context_instance = kwargs.pop('context_instance', None) or RequestContext(request)
can_change_password = app_settings.A2_REGISTRATION_CAN_CHANGE_PASSWORD
has_usable_password = request.user.has_usable_password()
return render_to_string(['auth/login_password_profile.html',
'authentic2/login_password_profile.html'],
{'can_change_password' : can_change_password,
context={'can_change_password' : can_change_password,
'has_usable_password' : has_usable_password},
context_instance=context_instance)
request=request)
class LoggedInView(View):

View File

@ -15,9 +15,7 @@ class OIDCFrontend(object):
return 'oidc'
def login(self, request, *args, **kwargs):
context_instance = kwargs.get('context_instance', None)
ctx = {
'providers': utils.get_providers(shown=True),
}
return render(request, 'authentic2_auth_oidc/login.html', ctx,
context_instance=context_instance)
return render(request, 'authentic2_auth_oidc/login.html', context=ctx)

View File

@ -1,6 +1,5 @@
from django.utils.translation import gettext_noop
from django.template.loader import render_to_string
from django.template import RequestContext
from django.shortcuts import render
from mellon.utils import get_idp, get_idps
@ -19,20 +18,17 @@ class SAMLFrontend(object):
return gettext_noop('SAML')
def login(self, request, *args, **kwargs):
context_instance = kwargs.pop('context_instance', None) or RequestContext(request)
submit_name = 'login-%s' % self.id
if request.method == 'POST' and submit_name in request.POST:
return redirect_to_login(request, login_url='mellon_login')
return render(request, 'authentic2_auth_saml/login.html', {'submit_name': submit_name},
context_instance=context_instance)
return render(request, 'authentic2_auth_saml/login.html', context={'submit_name': submit_name})
def profile(self, request, *args, **kwargs):
context_instance = kwargs.pop('context_instance', None) or RequestContext(request)
user_saml_identifiers = request.user.saml_identifiers.all()
if not user_saml_identifiers:
return ''
for user_saml_identifier in user_saml_identifiers:
user_saml_identifier.idp = get_idp(user_saml_identifier.issuer)
return render_to_string('authentic2_auth_saml/profile.html',
{'user_saml_identifiers': user_saml_identifiers},
context_instance=context_instance)
context={'user_saml_identifiers': user_saml_identifiers},
request=request)

View File

@ -28,6 +28,6 @@ class Plugin(object):
'url': url,
'iframe_timeout': use_iframe_timeout,
}
content = render_to_string('authentic2_idp_cas/logout_fragment.html', ctx)
content = render_to_string('authentic2_idp_cas/logout_fragment.html', context=ctx)
fragments.append(content)
return fragments
return fragments

View File

@ -30,5 +30,5 @@ class Plugin(object):
fragments.append(
render_to_string(
'authentic2_idp_oidc/logout_fragment.html',
ctx))
return fragments
context=ctx))
return fragments

View File

@ -5,7 +5,7 @@ import base64
import time
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed
from django.utils.timezone import now, UTC
from django.utils.timezone import now, utc
from django.utils.http import urlencode
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
@ -244,7 +244,7 @@ def authorize(request, *args, **kwargs):
state=state,
fragment=fragment)
else:
return render(request, 'authentic2_idp_oidc/authorization.html',
return render(request, 'authentic2_idp_oidc/authorization.html', context=
{
'client': client,
'scopes': scopes - set(['openid']),
@ -254,7 +254,7 @@ def authorize(request, *args, **kwargs):
client=client, user=request.user, scopes=u' '.join(scopes),
state=state, nonce=nonce, redirect_uri=redirect_uri,
expired=start + datetime.timedelta(seconds=30),
auth_time=datetime.datetime.fromtimestamp(last_auth['when'], UTC()),
auth_time=datetime.datetime.fromtimestamp(last_auth['when'], utc),
session_key=request.session.session_key)
logger.info(u'sending code %s for scopes %s for service %s',
code.uuid, ' '.join(scopes),

View File

@ -7,8 +7,7 @@ import hashlib
import urlparse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.shortcuts import render
from django.utils.translation import ugettext as _
try:
from django.views.decorators.csrf import csrf_exempt
@ -209,12 +208,12 @@ def openid_xrds(request, identity=False, id=None):
types = [OPENID_IDP_2_0_TYPE,SREG_TYPE]
local_ids = []
endpoints = [request.build_absolute_uri(reverse('openid-provider-root'))]
return render_to_response('idp/openid/xrds.xml', {
return render(request, 'idp/openid/xrds.xml', context={
'host': request.build_absolute_uri('/'),
'types': types,
'endpoints': endpoints,
'local_ids': local_ids,
}, context_instance=RequestContext(request), mimetype=YADIS_CONTENT_TYPE)
}, mimetype=YADIS_CONTENT_TYPE)
class DecideForm(forms.Form):
def __init__(self, sreg_request=None, *args, **kwargs):
@ -274,24 +273,23 @@ because no OpenID request is saved')
except DiscoveryFailure:
trust_root_valid = "DISCOVERY_FAILED"
return render_to_response('idp/openid/decide.html', {
return render(request, 'idp/openid/decide.html', context={
'title': _('Trust this site?'),
'required': sreg_request.required,
'optional': sreg_request.optional,
'trust_root_valid': trust_root_valid,
'form': form,
}, context_instance=RequestContext(request))
})
@openid_enabled
def openid_discovery(request, id):
'''HTML discovery page'''
xrds_url = request.build_absolute_uri(
reverse('openid-provider-identity-xrds', args=[id]))
response = render_to_response('idp/openid/discovery.html', {
response = render(request, 'idp/openid/discovery.html', context={
'xrds': xrds_url,
'openid_server': request.build_absolute_uri(
reverse('openid-provider-root'))
}, context_instance=RequestContext(request))
'openid_server': request.build_absolute_uri(reverse('openid-provider-root'))
})
response['X-XRDS-Location'] = xrds_url
return response