From b66796d10dc5298688837655cfe5821ad750d0b7 Mon Sep 17 00:00:00 2001 From: Taha Jahangir Date: Tue, 4 Sep 2018 21:43:54 +0430 Subject: [PATCH] Apply PEP8 to some files --- src/authentic2/app_settings.py | 138 ++++++++++++++++++--------------- src/authentic2/settings.py | 61 +++++++-------- src/authentic2/urls.py | 8 +- src/authentic2/views.py | 103 ++++++++++++------------ 4 files changed, 158 insertions(+), 152 deletions(-) diff --git a/src/authentic2/app_settings.py b/src/authentic2/app_settings.py index 19154118..e1ee909d 100644 --- a/src/authentic2/app_settings.py +++ b/src/authentic2/app_settings.py @@ -1,8 +1,8 @@ import sys -import six -from django.utils.translation import ugettext_lazy as _ +import six from django.core.exceptions import ImproperlyConfigured +from django.utils.translation import ugettext_lazy as _ class Setting(object): @@ -19,6 +19,7 @@ class Setting(object): def has_default(self): return self.default != self.SENTINEL + class AppSettings(object): def __init__(self, defaults): self.defaults = defaults @@ -35,12 +36,14 @@ class AppSettings(object): realms = {} if self.A2_REGISTRATION_REALM: realms[self.A2_REGISTRATION_REALM] = self.A2_REGISTRATION_REALM + def add_realms(new_realms): for realm in new_realms: if not isinstance(realm, (tuple, list)): realms[realm] = realm else: realms[realm[0]] = realm[1] + from django.contrib.auth import get_backends for backend in get_backends(): if hasattr(backend, 'get_realms'): @@ -69,12 +72,12 @@ class AppSettings(object): if self.defaults[key].has_default(): return self.defaults[key].default raise ImproperlyConfigured('missing setting %s(%s) is mandatory' % - (key, self.defaults[key].description)) + (key, self.defaults[key].description)) # Registration default_settings = dict( - ATTRIBUTE_BACKENDS = Setting( + ATTRIBUTE_BACKENDS=Setting( names=('A2_ATTRIBUTE_BACKENDS',), default=('authentic2.attributes_ng.sources.format', 'authentic2.attributes_ng.sources.function', @@ -82,59 +85,64 @@ default_settings = dict( 'authentic2.attributes_ng.sources.ldap', 'authentic2.attributes_ng.sources.computed_targeted_id', 'authentic2.attributes_ng.sources.service_roles', - ), + ), definition='List of attribute backend classes or modules', ), - CAFILE = Setting(names=('AUTHENTIC2_CAFILE', 'CAFILE'), - default=None, - definition='File containing certificate chains as PEM certificates'), - A2_REGISTRATION_URLCONF = Setting(default='authentic2.registration_backend.urls', - definition='Root urlconf for the /accounts endpoints'), - A2_REGISTRATION_FORM_CLASS = Setting(default='authentic2.registration_backend.forms.RegistrationForm', - definition='Default registration form'), - A2_REGISTRATION_COMPLETION_FORM_CLASS = Setting(default='authentic2.registration_backend.forms.RegistrationCompletionForm', - definition='Default registration completion form'), - A2_REGISTRATION_SET_PASSWORD_FORM_CLASS = Setting(default='authentic2.registration_backend.forms.SetPasswordForm', - definition='Default set password form'), - A2_REGISTRATION_CHANGE_PASSWORD_FORM_CLASS = Setting(default='authentic2.registration_backend.forms.PasswordChangeForm', - definition='Default change password form'), - A2_REGISTRATION_CAN_DELETE_ACCOUNT = Setting(default=True, - definition='Can user self delete their account and all their data'), - A2_REGISTRATION_CAN_CHANGE_PASSWORD = Setting(default=True, definition='Allow user to change its own password'), - A2_REGISTRATION_EMAIL_BLACKLIST = Setting(default=[], definition='List of forbidden email ' - 'wildcards, ex.: ^.*@ville.fr$'), - A2_REGISTRATION_REDIRECT = Setting(default=None, definition='Forced redirection after each redirect, NEXT_URL ' - ' substring is replaced by the original next_url passed to /accounts/register/'), - A2_PROFILE_CAN_CHANGE_EMAIL = Setting(default=True, - definition='Can user self change their email'), - A2_PROFILE_CAN_EDIT_PROFILE = Setting(default=True, - definition='Can user self edit their profile'), - A2_PROFILE_CAN_MANAGE_FEDERATION = Setting(default=True, - definition='Can user manage its federations'), - A2_PROFILE_DISPLAY_EMPTY_FIELDS = Setting(default=False, - definition='Include empty fields in profile view'), - A2_HOMEPAGE_URL = Setting(default=None, definition='IdP has no homepage, ' - 'redirect to this one.'), - A2_USER_CAN_RESET_PASSWORD = Setting(default=None, definition='Allow online reset of passwords'), - A2_EMAIL_IS_UNIQUE = Setting(default=False, - definition='Email of users must be unique'), - A2_REGISTRATION_EMAIL_IS_UNIQUE = Setting(default=False, - definition='Email of registererd accounts must be unique'), + CAFILE=Setting(names=('AUTHENTIC2_CAFILE', 'CAFILE'), + default=None, + definition='File containing certificate chains as PEM certificates'), + A2_REGISTRATION_URLCONF=Setting(default='authentic2.registration_backend.urls', + definition='Root urlconf for the /accounts endpoints'), + A2_REGISTRATION_FORM_CLASS=Setting(default='authentic2.registration_backend.forms.RegistrationForm', + definition='Default registration form'), + A2_REGISTRATION_COMPLETION_FORM_CLASS=Setting( + default='authentic2.registration_backend.forms.RegistrationCompletionForm', + definition='Default registration completion form'), + A2_REGISTRATION_SET_PASSWORD_FORM_CLASS=Setting(default='authentic2.registration_backend.forms.SetPasswordForm', + definition='Default set password form'), + A2_REGISTRATION_CHANGE_PASSWORD_FORM_CLASS=Setting( + default='authentic2.registration_backend.forms.PasswordChangeForm', + definition='Default change password form'), + A2_REGISTRATION_CAN_DELETE_ACCOUNT=Setting(default=True, + definition='Can user self delete their account and all their data'), + A2_REGISTRATION_CAN_CHANGE_PASSWORD=Setting(default=True, definition='Allow user to change its own password'), + A2_REGISTRATION_EMAIL_BLACKLIST=Setting(default=[], definition='List of forbidden email ' + 'wildcards, ex.: ^.*@ville.fr$'), + A2_REGISTRATION_REDIRECT=Setting(default=None, definition='Forced redirection after each redirect, NEXT_URL' + ' substring is replaced by the original next_url' + ' passed to /accounts/register/'), + A2_PROFILE_CAN_CHANGE_EMAIL=Setting(default=True, + definition='Can user self change their email'), + A2_PROFILE_CAN_EDIT_PROFILE=Setting(default=True, + definition='Can user self edit their profile'), + A2_PROFILE_CAN_MANAGE_FEDERATION=Setting(default=True, + definition='Can user manage its federations'), + A2_PROFILE_DISPLAY_EMPTY_FIELDS=Setting(default=False, + definition='Include empty fields in profile view'), + A2_HOMEPAGE_URL=Setting(default=None, definition='IdP has no homepage, ' + 'redirect to this one.'), + A2_USER_CAN_RESET_PASSWORD=Setting(default=None, definition='Allow online reset of passwords'), + A2_EMAIL_IS_UNIQUE=Setting(default=False, + definition='Email of users must be unique'), + A2_REGISTRATION_EMAIL_IS_UNIQUE=Setting(default=False, + definition='Email of registererd accounts must be unique'), A2_REGISTRATION_FORM_USERNAME_REGEX=Setting(default=r'^[\w.@+-]+$', definition='Regex to validate usernames'), A2_REGISTRATION_FORM_USERNAME_HELP_TEXT=Setting(default=_('Required. At most ' - '30 characters. Letters, digits, and @/./+/-/_ only.')), + '30 characters. Letters, digits, and @/./+/-/_ only.')), A2_REGISTRATION_FORM_USERNAME_LABEL=Setting(default=_('Username')), A2_REGISTRATION_REALM=Setting(default=None, definition='Default realm to assign to self-registrated users'), A2_REGISTRATION_GROUPS=Setting(default=(), definition='Default groups for self-registered users'), A2_PROFILE_FIELDS=Setting(default=(), definition='Fields to show to the user in the profile page'), - A2_REGISTRATION_FIELDS=Setting(default=(), definition='Fields from the user model that must appear on the registration form'), + A2_REGISTRATION_FIELDS=Setting(default=(), + definition='Fields from the user model that must appear on the registration form'), A2_REQUIRED_FIELDS=Setting(default=(), definition='User fields that are required'), - A2_REGISTRATION_REQUIRED_FIELDS=Setting(default=(), definition='Fields from the registration form that must be required'), + A2_REGISTRATION_REQUIRED_FIELDS=Setting(default=(), + definition='Fields from the registration form that must be required'), A2_PRE_REGISTRATION_FIELDS=Setting(default=(), definition='User fields to ask with email'), A2_REALMS=Setting(default=(), definition='List of realms to search user accounts'), A2_USERNAME_REGEX=Setting(default=None, definition='Regex that username must validate'), A2_USERNAME_LABEL=Setting(default=None, definition='Alternate username label for the login' - ' form'), + ' form'), A2_USERNAME_HELP_TEXT=Setting(default=None, definition='Help text to explain validation rules of usernames'), A2_USERNAME_IS_UNIQUE=Setting(default=True, definition='Check username uniqueness'), A2_REGISTRATION_USERNAME_IS_UNIQUE=Setting(default=True, definition='Check username uniqueness on registration'), @@ -147,38 +155,40 @@ default_settings = dict( A2_ATTRIBUTE_KINDS=Setting(default=(), definition='List of other attribute kinds'), A2_VALIDATE_EMAIL=Setting(default=False, definition='Validate user email server by doing an RCPT command'), A2_VALIDATE_EMAIL_DOMAIN=Setting(default=True, definition='Validate user email domain'), - A2_PASSWORD_POLICY_MIN_CLASSES=Setting(default=3, definition='Minimum number of characters classes to be present in passwords'), + A2_PASSWORD_POLICY_MIN_CLASSES=Setting(default=3, definition='Minimum number of characters classes to be' + ' present in passwords'), A2_PASSWORD_POLICY_MIN_LENGTH=Setting(default=8, definition='Minimum number of characters in a password'), A2_PASSWORD_POLICY_REGEX=Setting(default=None, definition='Regular expression for validating passwords'), - A2_PASSWORD_POLICY_REGEX_ERROR_MSG=Setting(default=None, definition='Error message to show when the password do not validate the regular expression'), + A2_PASSWORD_POLICY_REGEX_ERROR_MSG=Setting(default=None, definition='Error message to show when the password' + ' do not validate the regular expression'), A2_PASSWORD_POLICY_CLASS=Setting( default='authentic2.passwords.DefaultPasswordChecker', definition='path of a class to validate passwords'), A2_PASSWORD_POLICY_SHOW_LAST_CHAR=Setting(default=False, definition='Show last character in password fields'), - A2_AUTH_PASSWORD_ENABLE=Setting(default=True, definition='Activate login/password authentication', names=('AUTH_PASSWORD',)), - A2_LOGIN_FAILURE_COUNT_BEFORE_WARNING=Setting(default=0, - definition='Failure count before logging a warning to ' - 'authentic2.user_login_failure. No warning will be send if value is ' - '0.'), + A2_AUTH_PASSWORD_ENABLE=Setting(default=True, definition='Activate login/password authentication', + names=('AUTH_PASSWORD',)), + A2_LOGIN_FAILURE_COUNT_BEFORE_WARNING=Setting( + default=0, definition='Failure count before logging a warning to ' + 'authentic2.user_login_failure. No warning will be send if value is 0.'), PUSH_PROFILE_UPDATES=Setting(default=False, definition='Push profile update to linked services'), TEMPLATE_VARS=Setting(default={}, definition='Variable to pass to templates'), A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_FACTOR=Setting(default=1.8, - definition='exponential backoff factor duration as seconds until ' - 'next try after a login failure'), - A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_DURATION=Setting(default=0, - definition='exponential backoff base factor duration as secondss ' - 'until next try after a login failure'), - A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MAX_DURATION=Setting(default=3600, - definition='maximum exponential backoff maximum duration as seconds until ' - 'next try after a login failure'), - A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MIN_DURATION=Setting(default=10, - definition='minimum exponential backoff maximum duration as seconds until ' - 'next try after a login failure'), + definition='exponential backoff factor duration as seconds until ' + 'next try after a login failure'), + A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_DURATION=Setting( + default=0, + definition='exponential backoff base factor duration as secondss until next try after a login failure'), + A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MAX_DURATION=Setting( + default=3600, + definition='maximum exponential backoff maximum duration as seconds until next try after a login failure'), + A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MIN_DURATION=Setting( + default=10, + definition='minimum exponential backoff maximum duration as seconds until next try after a login failure'), A2_VERIFY_SSL=Setting(default=True, definition='Verify SSL certificate in HTTP requests'), A2_ATTRIBUTE_KIND_TITLE_CHOICES=Setting(default=(), definition='Choices for the title attribute kind'), A2_CORS_WHITELIST=Setting(default=(), definition='List of origin URL to whitelist, must be scheme://netloc[:port]'), A2_EMAIL_CHANGE_TOKEN_LIFETIME=Setting(default=7200, definition='Lifetime in seconds of the ' - 'token sent to verify email adresses'), + 'token sent to verify email adresses'), A2_REDIRECT_WHITELIST=Setting( default=(), definition='List of origins which are authorized to ask for redirection.'), @@ -196,7 +206,7 @@ default_settings = dict( A2_USER_REMEMBER_ME=Setting( default=None, definition='Session duration as seconds when using the remember me ' - 'checkbox. Truthiness activates the checkbox.'), + 'checkbox. Truthiness activates the checkbox.'), A2_LOGIN_REDIRECT_AUTHENTICATED_USERS_TO_HOMEPAGE=Setting( default=False, definition='Redirect authenticated users to homepage'), diff --git a/src/authentic2/settings.py b/src/authentic2/settings.py index c045ce2a..29c1d320 100644 --- a/src/authentic2/settings.py +++ b/src/authentic2/settings.py @@ -1,9 +1,7 @@ -import logging import logging.config +import os # Load default from Django from django.conf import global_settings -import os - from gadjo.templatetags.gadjo import xstatic from . import plugins, logger @@ -12,7 +10,7 @@ from . import plugins, logger CACHES = global_settings.CACHES BASE_DIR = os.path.dirname(__file__) -### Quick-start development settings - unsuitable for production +# ### Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! @@ -34,7 +32,7 @@ DATABASES = { } } -### End of "Quick-start development settings" +# ### End of "Quick-start development settings" # Hey Entr'ouvert is in France !! @@ -70,7 +68,6 @@ TEMPLATES = [ }, ] - MIDDLEWARE_CLASSES = ( 'authentic2.middleware.StoreRequestMiddleware', 'authentic2.middleware.RequestIdMiddleware', @@ -103,7 +100,7 @@ STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATICFILES_FINDERS = list(global_settings.STATICFILES_FINDERS) + ['gadjo.finders.XStaticFinder'] -LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) +LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),) INSTALLED_APPS = ( 'django.contrib.staticfiles', @@ -145,10 +142,9 @@ AUTHENTICATION_BACKENDS = ( 'django_rbac.backends.DjangoRBACBackend', ) AUTHENTICATION_BACKENDS = plugins.register_plugins_authentication_backends( - AUTHENTICATION_BACKENDS) + AUTHENTICATION_BACKENDS) CSRF_FAILURE_VIEW = 'authentic2.views.csrf_failure_view' - LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/login/' LOGOUT_URL = '/logout/' @@ -186,12 +182,12 @@ IDP_BACKENDS = plugins.register_plugins_idp_backends(()) # Can be none, sp, idp or both PASSWORD_HASHERS = list(global_settings.PASSWORD_HASHERS) + [ - 'authentic2.hashers.Drupal7PasswordHasher', - 'authentic2.hashers.SHA256PasswordHasher', - 'authentic2.hashers.SSHA1PasswordHasher', - 'authentic2.hashers.SMD5PasswordHasher', - 'authentic2.hashers.SHA1OLDAPPasswordHasher', - 'authentic2.hashers.MD5OLDAPPasswordHasher' + 'authentic2.hashers.Drupal7PasswordHasher', + 'authentic2.hashers.SHA256PasswordHasher', + 'authentic2.hashers.SSHA1PasswordHasher', + 'authentic2.hashers.SMD5PasswordHasher', + 'authentic2.hashers.SHA1OLDAPPasswordHasher', + 'authentic2.hashers.MD5OLDAPPasswordHasher' ] # Admin tools @@ -201,7 +197,7 @@ ADMIN_TOOLS_MENU = 'authentic2.menu.CustomMenu' # Serialization module to support natural keys in generic foreign keys SERIALIZATION_MODULES = { - 'json': 'authentic2.serializers', + 'json': 'authentic2.serializers', } LOGGING_CONFIG = None @@ -210,10 +206,10 @@ LOGGING = { 'disable_existing_loggers': True, 'filters': { 'cleaning': { - '()': 'authentic2.utils.CleanLogMessage', + '()': 'authentic2.utils.CleanLogMessage', }, 'request_context': { - '()': 'authentic2.log_filters.RequestContextFilter', + '()': 'authentic2.log_filters.RequestContextFilter', }, 'force_debug': { '()': 'authentic2.log_filters.ForceDebugFilter', @@ -232,15 +228,15 @@ LOGGING = { 'handlers': { 'console': { 'level': 'DEBUG', - 'class':'logging.StreamHandler', + 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'filters': ['cleaning', 'request_context'], }, - # remove request_context filter for db log to prevent infinite loop - # when logging sql query to retrieve the session user + # remove request_context filter for db log to prevent infinite loop + # when logging sql query to retrieve the session user 'console_db': { 'level': 'DEBUG', - 'class':'logging.StreamHandler', + 'class': 'logging.StreamHandler', 'formatter': 'verbose_db', 'filters': ['cleaning'], }, @@ -249,16 +245,16 @@ LOGGING = { # even when debugging seeing SQL queries is too much, activate it # explicitly using DEBUG_DB 'django.db': { - 'handlers': ['console_db'], - 'level': logger.SettingsLogLevel('INFO', debug_setting='DEBUG_DB'), - 'propagate': False, + 'handlers': ['console_db'], + 'level': logger.SettingsLogLevel('INFO', debug_setting='DEBUG_DB'), + 'propagate': False, }, 'django': { - 'level': 'INFO', + 'level': 'INFO', }, # django_select2 outputs debug message at level INFO 'django_select2': { - 'level': 'WARNING', + 'level': 'WARNING', }, # lasso has the bad habit of logging everything as errors 'Lasso': { @@ -271,16 +267,16 @@ LOGGING = { 'filters': ['force_debug'], }, '': { - 'handlers': ['console'], - 'level': logger.SettingsLogLevel('INFO'), + 'handlers': ['console'], + 'level': logger.SettingsLogLevel('INFO'), }, }, } MIGRATION_MODULES = { - 'auth': 'authentic2.auth_migrations', - 'menu': 'authentic2.menu_migrations', - 'dashboard': 'authentic2.dashboard_migrations', + 'auth': 'authentic2.auth_migrations', + 'menu': 'authentic2.menu_migrations', + 'dashboard': 'authentic2.dashboard_migrations', } MIGRATION_MODULES['auth'] = 'authentic2.auth_migrations_18' @@ -302,7 +298,6 @@ REST_FRAMEWORK = { 'PAGE_SIZE': 100, } - # Authentic2 Auth SAML MELLON_ADAPTER = ('authentic2_auth_saml.adapters.AuthenticAdapter',) diff --git a/src/authentic2/urls.py b/src/authentic2/urls.py index 35b13139..f0812586 100644 --- a/src/authentic2/urls.py +++ b/src/authentic2/urls.py @@ -1,5 +1,5 @@ -from django.conf.urls import url, include from django.conf import settings +from django.conf.urls import url, include from django.contrib import admin from django.contrib.staticfiles.views import serve @@ -29,7 +29,6 @@ not_homepage_patterns += [ url(r'^api/', include('authentic2.api_urls')) ] - urlpatterns += not_homepage_patterns try: @@ -47,8 +46,9 @@ if settings.DEBUG: if settings.DEBUG and 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar + urlpatterns = [ - url(r'^__debug__/', include(debug_toolbar.urls)), - ] + urlpatterns + url(r'^__debug__/', include(debug_toolbar.urls)), + ] + urlpatterns urlpatterns = plugins.register_plugins_urls(urlpatterns) diff --git a/src/authentic2/views.py b/src/authentic2/views.py index c9d8d9a7..706c8294 100644 --- a/src/authentic2/views.py +++ b/src/authentic2/views.py @@ -1,44 +1,36 @@ +import collections import logging -from authentic2.compat_lasso import lasso -import thread -import requests -import urllib import re -import collections - - -from django.conf import settings -from django.shortcuts import render_to_response, render -from django.template.loader import render_to_string, select_template -from django.views.generic.edit import UpdateView, FormView -from django.views.generic import RedirectView, 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.urlresolvers import reverse -from django.core.exceptions import ValidationError +from django.conf import settings from django.contrib import messages -from django.utils.translation import ugettext as _ -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 import SESSION_KEY +from django.contrib.auth import logout as auth_logout from django.contrib.auth.decorators import login_required +from django.core import signing +from django.core.exceptions import ValidationError +from django.core.urlresolvers import reverse from django.db.models.fields import FieldDoesNotExist from django.db.models.query import Q +from django.http import (HttpResponseRedirect, HttpResponseForbidden, + HttpResponse) +from django.shortcuts import render_to_response, render +from django.template.loader import render_to_string +from django.utils.translation import ugettext as _ +from django.views.decorators.cache import never_cache +from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie +from django.views.generic import TemplateView +from django.views.generic.base import View +from django.views.generic.edit import UpdateView, FormView + +from . import (utils, app_settings, forms, compat, decorators, constants, models, cbv, hooks) # FIXME: this decorator has nothing to do with an idp, should be moved in the # a2 package # FIXME: this constant should be moved in the a2 package -from . import (utils, app_settings, forms, compat, decorators, constants, models, cbv, hooks) - - logger = logging.getLogger(__name__) @@ -48,7 +40,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_to_response(template_name, {'next': next}) def server_error(request, template_name='500.html'): @@ -101,8 +93,8 @@ class EditProfile(cbv.HookMixin, cbv.TemplateNamesMixin, UpdateView): else: default_fields = list(attributes.values_list('name', flat=True)) fields, labels = utils.get_fields_and_labels( - editable_profile_fields, - default_fields) + editable_profile_fields, + default_fields) if scopes: # restrict fields to those in the scopes fields = [field for field in fields if field in default_fields] @@ -145,6 +137,7 @@ class EditProfile(cbv.HookMixin, cbv.TemplateNamesMixin, UpdateView): hooks.call_hooks('event', name='edit-profile', user=self.request.user, form=form) return response + edit_profile = decorators.setting_enabled('A2_PROFILE_CAN_EDIT_PROFILE')( login_required(EditProfile.as_view())) @@ -200,6 +193,7 @@ class EmailChangeView(cbv.TemplateNamesMixin, FormView): logging.getLogger(__name__).info('email change request') return super(EmailChangeView, self).form_valid(form) + email_change = decorators.setting_enabled('A2_PROFILE_CAN_CHANGE_EMAIL')( login_required(EmailChangeView.as_view())) @@ -227,23 +221,23 @@ class EmailChangeVerifyView(TemplateView): user.email_verified = True user.save() messages.info(request, _('your request for changing your email for {0} ' - 'is successful').format(email)) + 'is successful').format(email)) logging.getLogger(__name__).info('user %s changed its email ' 'from %s to %s', user, old_email, email) hooks.call_hooks('event', name='change-email-confirm', user=user, email=email) except signing.SignatureExpired: messages.error(request, _('your request for changing your email is too ' - 'old, try again')) + 'old, try again')) except signing.BadSignature: messages.error(request, _('your request for changing your email is ' - 'invalid, try again')) + 'invalid, try again')) except ValueError: messages.error(request, _('your request for changing your email was not ' - 'on this site, try again')) + 'on this site, try again')) except User.DoesNotExist: messages.error(request, _('your request for changing your email is for ' - 'an unknown user, try again')) + 'an unknown user, try again')) except ValidationError as e: messages.error(request, e.message) else: @@ -278,7 +272,7 @@ def login(request, template_name='authentic2/login.html', # should be allowed. This regex checks if there is a '//' *before* a # question mark. elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to): - redirect_to = settings.LOGIN_REDIRECT_URL + redirect_to = settings.LOGIN_REDIRECT_URL nonce = request.GET.get(constants.NONCE_FIELD_NAME) frontends = utils.get_backends('AUTH_FRONTENDS') @@ -309,9 +303,9 @@ def login(request, template_name='authentic2/login.html', form_class = frontend.form() submit_name = 'submit-%s' % fid block = { - 'id': fid, - 'name': name, - 'frontend': frontend + 'id': fid, + 'name': name, + 'frontend': frontend } if request.method == 'POST' and submit_name in request.POST: form = form_class(data=request.POST) @@ -323,7 +317,7 @@ def login(request, template_name='authentic2/login.html', else: block['form'] = form_class() blocks.append(block) - else: # New frontends API + else: # New frontends API parameters = {'request': request, 'context': context} block = utils.get_backend_method(frontend, 'login', parameters) @@ -338,7 +332,6 @@ def login(request, template_name='authentic2/login.html', else: blocks[-1]['is_hidden'] = False - # Old frontends API for block in blocks: fid = block['id'] @@ -346,16 +339,16 @@ def login(request, template_name='authentic2/login.html', continue frontend = block['frontend'] context.update({ - 'submit_name': 'submit-%s' % fid, - redirect_field_name: redirect_to, - 'form': block['form'] + 'submit_name': 'submit-%s' % fid, + redirect_field_name: redirect_to, + 'form': block['form'] }) if hasattr(frontend, 'get_context'): context.update(frontend.get_context()) sub_template_name = frontend.template() block['content'] = render_to_string( - sub_template_name, context, - request=request) + sub_template_name, context, + request=request) request.session.set_test_cookie() @@ -389,6 +382,7 @@ class Homepage(cbv.TemplateNamesMixin, TemplateView): ctx['authorized_services'] = service_list(self.request) return ctx + homepage = Homepage.as_view() @@ -423,7 +417,7 @@ class ProfileView(cbv.TemplateNamesMixin, TemplateView): for field_name in getattr(request.user, 'USER_PROFILE', []): if field_name not in field_names: field_names.append(field_name) - qs = models.Attribute.objects.filter(Q(user_editable=True)|Q(user_visible=True)) + qs = models.Attribute.objects.filter(Q(user_editable=True) | Q(user_visible=True)) qs = qs.values_list('name', flat=True) for field_name in qs: if field_name not in field_names: @@ -478,7 +472,7 @@ class ProfileView(cbv.TemplateNamesMixin, TemplateView): parameters = {'request': request, 'context': context} profiles = [utils.get_backend_method(frontend, 'profile', parameters) - for frontend in frontends] + for frontend in frontends] # Old frontends data structure for templates blocks = [block['content'] for block in profiles if block] # New frontends data structure for templates @@ -506,19 +500,23 @@ class ProfileView(cbv.TemplateNamesMixin, TemplateView): hooks.call_hooks('modify_context_data', self, context) return context + profile = login_required(ProfileView.as_view()) + def logout_list(request): '''Return logout links from idp backends''' return utils.accumulate_from_backends(request, 'logout_list') + def redirect_logout_list(request): '''Return redirect logout links from idp backends''' return utils.accumulate_from_backends(request, 'redirect_logout_list') + def logout(request, next_url=None, default_next_url='auth_homepage', - redirect_field_name=REDIRECT_FIELD_NAME, - template='authentic2/logout.html', do_local=True, check_referer=True): + redirect_field_name=REDIRECT_FIELD_NAME, + template='authentic2/logout.html', do_local=True, check_referer=True): '''Logout first check if a logout request is authorized, i.e. that logout was done using a POST with CSRF token or with a GET from the same site. @@ -529,7 +527,7 @@ def logout(request, next_url=None, default_next_url='auth_homepage', logger = logging.getLogger(__name__) default_next_url = utils.make_url(default_next_url) next_url = next_url or request.GET.get(redirect_field_name, - default_next_url) + default_next_url) ctx = {} ctx['next_url'] = next_url ctx['redir_timeout'] = 60 @@ -608,12 +606,15 @@ class LoggedInView(View): content = u'{0}({1})'.format(callback, int(request.user.is_authenticated())) return HttpResponse(content, content_type='application/json') + logged_in = never_cache(LoggedInView.as_view()) + def csrf_failure_view(request, reason=""): messages.warning(request, _('The page is out of date, it was reloaded for you')) return HttpResponseRedirect(request.get_full_path()) + def test_redirect(request): next_url = request.GET.get(REDIRECT_FIELD_NAME, settings.LOGIN_REDIRECT_URL) messages.info(request, 'Une info') -- 2.18.0