Projet

Général

Profil

0001-Apply-PEP8-to-some-files.patch

Taha Jahangir, 04 septembre 2018 19:26

Télécharger (34,2 ko)

Voir les différences:

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(-)
src/authentic2/app_settings.py
1 1
import sys
2
import six
3 2

  
4
from django.utils.translation import ugettext_lazy as _
3
import six
5 4
from django.core.exceptions import ImproperlyConfigured
5
from django.utils.translation import ugettext_lazy as _
6 6

  
7 7

  
8 8
class Setting(object):
......
19 19
    def has_default(self):
20 20
        return self.default != self.SENTINEL
21 21

  
22

  
22 23
class AppSettings(object):
23 24
    def __init__(self, defaults):
24 25
        self.defaults = defaults
......
35 36
        realms = {}
36 37
        if self.A2_REGISTRATION_REALM:
37 38
            realms[self.A2_REGISTRATION_REALM] = self.A2_REGISTRATION_REALM
39

  
38 40
        def add_realms(new_realms):
39 41
            for realm in new_realms:
40 42
                if not isinstance(realm, (tuple, list)):
41 43
                    realms[realm] = realm
42 44
                else:
43 45
                    realms[realm[0]] = realm[1]
46

  
44 47
        from django.contrib.auth import get_backends
45 48
        for backend in get_backends():
46 49
            if hasattr(backend, 'get_realms'):
......
69 72
        if self.defaults[key].has_default():
70 73
            return self.defaults[key].default
71 74
        raise ImproperlyConfigured('missing setting %s(%s) is mandatory' %
72
                (key, self.defaults[key].description))
75
                                   (key, self.defaults[key].description))
73 76

  
74 77

  
75 78
# Registration
76 79
default_settings = dict(
77
    ATTRIBUTE_BACKENDS = Setting(
80
    ATTRIBUTE_BACKENDS=Setting(
78 81
        names=('A2_ATTRIBUTE_BACKENDS',),
79 82
        default=('authentic2.attributes_ng.sources.format',
80 83
                 'authentic2.attributes_ng.sources.function',
......
82 85
                 'authentic2.attributes_ng.sources.ldap',
83 86
                 'authentic2.attributes_ng.sources.computed_targeted_id',
84 87
                 'authentic2.attributes_ng.sources.service_roles',
85
        ),
88
                 ),
86 89
        definition='List of attribute backend classes or modules',
87 90
    ),
88
    CAFILE = Setting(names=('AUTHENTIC2_CAFILE', 'CAFILE'),
89
            default=None,
90
            definition='File containing certificate chains as PEM certificates'),
91
    A2_REGISTRATION_URLCONF = Setting(default='authentic2.registration_backend.urls',
92
                definition='Root urlconf for the /accounts endpoints'),
93
    A2_REGISTRATION_FORM_CLASS = Setting(default='authentic2.registration_backend.forms.RegistrationForm',
94
                definition='Default registration form'),
95
    A2_REGISTRATION_COMPLETION_FORM_CLASS = Setting(default='authentic2.registration_backend.forms.RegistrationCompletionForm',
96
                definition='Default registration completion form'),
97
    A2_REGISTRATION_SET_PASSWORD_FORM_CLASS = Setting(default='authentic2.registration_backend.forms.SetPasswordForm',
98
                definition='Default set password form'),
99
    A2_REGISTRATION_CHANGE_PASSWORD_FORM_CLASS = Setting(default='authentic2.registration_backend.forms.PasswordChangeForm',
100
                definition='Default change password form'),
101
    A2_REGISTRATION_CAN_DELETE_ACCOUNT = Setting(default=True,
102
                definition='Can user self delete their account and all their data'),
103
    A2_REGISTRATION_CAN_CHANGE_PASSWORD = Setting(default=True, definition='Allow user to change its own password'),
104
    A2_REGISTRATION_EMAIL_BLACKLIST = Setting(default=[], definition='List of forbidden email '
105
                                              'wildcards, ex.: ^.*@ville.fr$'),
106
    A2_REGISTRATION_REDIRECT = Setting(default=None, definition='Forced redirection after each redirect, NEXT_URL '
107
                                       ' substring is replaced by the original next_url passed to /accounts/register/'),
108
    A2_PROFILE_CAN_CHANGE_EMAIL = Setting(default=True,
109
                definition='Can user self change their email'),
110
    A2_PROFILE_CAN_EDIT_PROFILE = Setting(default=True,
111
                definition='Can user self edit their profile'),
112
    A2_PROFILE_CAN_MANAGE_FEDERATION = Setting(default=True,
113
                definition='Can user manage its federations'),
114
    A2_PROFILE_DISPLAY_EMPTY_FIELDS = Setting(default=False,
115
                definition='Include empty fields in profile view'),
116
    A2_HOMEPAGE_URL = Setting(default=None, definition='IdP has no homepage, '
117
        'redirect to this one.'),
118
    A2_USER_CAN_RESET_PASSWORD = Setting(default=None, definition='Allow online reset of passwords'),
119
    A2_EMAIL_IS_UNIQUE = Setting(default=False,
120
        definition='Email of users must be unique'),
121
    A2_REGISTRATION_EMAIL_IS_UNIQUE = Setting(default=False,
122
        definition='Email of registererd accounts must be unique'),
91
    CAFILE=Setting(names=('AUTHENTIC2_CAFILE', 'CAFILE'),
92
                   default=None,
93
                   definition='File containing certificate chains as PEM certificates'),
94
    A2_REGISTRATION_URLCONF=Setting(default='authentic2.registration_backend.urls',
95
                                    definition='Root urlconf for the /accounts endpoints'),
96
    A2_REGISTRATION_FORM_CLASS=Setting(default='authentic2.registration_backend.forms.RegistrationForm',
97
                                       definition='Default registration form'),
98
    A2_REGISTRATION_COMPLETION_FORM_CLASS=Setting(
99
        default='authentic2.registration_backend.forms.RegistrationCompletionForm',
100
        definition='Default registration completion form'),
101
    A2_REGISTRATION_SET_PASSWORD_FORM_CLASS=Setting(default='authentic2.registration_backend.forms.SetPasswordForm',
102
                                                    definition='Default set password form'),
103
    A2_REGISTRATION_CHANGE_PASSWORD_FORM_CLASS=Setting(
104
        default='authentic2.registration_backend.forms.PasswordChangeForm',
105
        definition='Default change password form'),
106
    A2_REGISTRATION_CAN_DELETE_ACCOUNT=Setting(default=True,
107
                                               definition='Can user self delete their account and all their data'),
108
    A2_REGISTRATION_CAN_CHANGE_PASSWORD=Setting(default=True, definition='Allow user to change its own password'),
109
    A2_REGISTRATION_EMAIL_BLACKLIST=Setting(default=[], definition='List of forbidden email '
110
                                                                   'wildcards, ex.: ^.*@ville.fr$'),
111
    A2_REGISTRATION_REDIRECT=Setting(default=None, definition='Forced redirection after each redirect, NEXT_URL'
112
                                                              ' substring is replaced by the original next_url'
113
                                                              ' passed to /accounts/register/'),
114
    A2_PROFILE_CAN_CHANGE_EMAIL=Setting(default=True,
115
                                        definition='Can user self change their email'),
116
    A2_PROFILE_CAN_EDIT_PROFILE=Setting(default=True,
117
                                        definition='Can user self edit their profile'),
118
    A2_PROFILE_CAN_MANAGE_FEDERATION=Setting(default=True,
119
                                             definition='Can user manage its federations'),
120
    A2_PROFILE_DISPLAY_EMPTY_FIELDS=Setting(default=False,
121
                                            definition='Include empty fields in profile view'),
122
    A2_HOMEPAGE_URL=Setting(default=None, definition='IdP has no homepage, '
123
                                                     'redirect to this one.'),
124
    A2_USER_CAN_RESET_PASSWORD=Setting(default=None, definition='Allow online reset of passwords'),
125
    A2_EMAIL_IS_UNIQUE=Setting(default=False,
126
                               definition='Email of users must be unique'),
127
    A2_REGISTRATION_EMAIL_IS_UNIQUE=Setting(default=False,
128
                                            definition='Email of registererd accounts must be unique'),
123 129
    A2_REGISTRATION_FORM_USERNAME_REGEX=Setting(default=r'^[\w.@+-]+$', definition='Regex to validate usernames'),
124 130
    A2_REGISTRATION_FORM_USERNAME_HELP_TEXT=Setting(default=_('Required. At most '
125
        '30 characters. Letters, digits, and @/./+/-/_ only.')),
131
                                                              '30 characters. Letters, digits, and @/./+/-/_ only.')),
126 132
    A2_REGISTRATION_FORM_USERNAME_LABEL=Setting(default=_('Username')),
127 133
    A2_REGISTRATION_REALM=Setting(default=None, definition='Default realm to assign to self-registrated users'),
128 134
    A2_REGISTRATION_GROUPS=Setting(default=(), definition='Default groups for self-registered users'),
129 135
    A2_PROFILE_FIELDS=Setting(default=(), definition='Fields to show to the user in the profile page'),
130
    A2_REGISTRATION_FIELDS=Setting(default=(), definition='Fields from the user model that must appear on the registration form'),
136
    A2_REGISTRATION_FIELDS=Setting(default=(),
137
                                   definition='Fields from the user model that must appear on the registration form'),
131 138
    A2_REQUIRED_FIELDS=Setting(default=(), definition='User fields that are required'),
132
    A2_REGISTRATION_REQUIRED_FIELDS=Setting(default=(), definition='Fields from the registration form that must be required'),
139
    A2_REGISTRATION_REQUIRED_FIELDS=Setting(default=(),
140
                                            definition='Fields from the registration form that must be required'),
133 141
    A2_PRE_REGISTRATION_FIELDS=Setting(default=(), definition='User fields to ask with email'),
134 142
    A2_REALMS=Setting(default=(), definition='List of realms to search user accounts'),
135 143
    A2_USERNAME_REGEX=Setting(default=None, definition='Regex that username must validate'),
136 144
    A2_USERNAME_LABEL=Setting(default=None, definition='Alternate username label for the login'
137
                              ' form'),
145
                                                       ' form'),
138 146
    A2_USERNAME_HELP_TEXT=Setting(default=None, definition='Help text to explain validation rules of usernames'),
139 147
    A2_USERNAME_IS_UNIQUE=Setting(default=True, definition='Check username uniqueness'),
140 148
    A2_REGISTRATION_USERNAME_IS_UNIQUE=Setting(default=True, definition='Check username uniqueness on registration'),
......
147 155
    A2_ATTRIBUTE_KINDS=Setting(default=(), definition='List of other attribute kinds'),
148 156
    A2_VALIDATE_EMAIL=Setting(default=False, definition='Validate user email server by doing an RCPT command'),
149 157
    A2_VALIDATE_EMAIL_DOMAIN=Setting(default=True, definition='Validate user email domain'),
150
    A2_PASSWORD_POLICY_MIN_CLASSES=Setting(default=3, definition='Minimum number of characters classes to be present in passwords'),
158
    A2_PASSWORD_POLICY_MIN_CLASSES=Setting(default=3, definition='Minimum number of characters classes to be'
159
                                                                 ' present in passwords'),
151 160
    A2_PASSWORD_POLICY_MIN_LENGTH=Setting(default=8, definition='Minimum number of characters in a password'),
152 161
    A2_PASSWORD_POLICY_REGEX=Setting(default=None, definition='Regular expression for validating passwords'),
153
    A2_PASSWORD_POLICY_REGEX_ERROR_MSG=Setting(default=None, definition='Error message to show when the password do not validate the regular expression'),
162
    A2_PASSWORD_POLICY_REGEX_ERROR_MSG=Setting(default=None, definition='Error message to show when the password'
163
                                                                        ' do not validate the regular expression'),
154 164
    A2_PASSWORD_POLICY_CLASS=Setting(
155 165
        default='authentic2.passwords.DefaultPasswordChecker',
156 166
        definition='path of a class to validate passwords'),
157 167
    A2_PASSWORD_POLICY_SHOW_LAST_CHAR=Setting(default=False, definition='Show last character in password fields'),
158
    A2_AUTH_PASSWORD_ENABLE=Setting(default=True, definition='Activate login/password authentication', names=('AUTH_PASSWORD',)),
159
    A2_LOGIN_FAILURE_COUNT_BEFORE_WARNING=Setting(default=0,
160
            definition='Failure count before logging a warning to '
161
            'authentic2.user_login_failure. No warning will be send if value is '
162
            '0.'),
168
    A2_AUTH_PASSWORD_ENABLE=Setting(default=True, definition='Activate login/password authentication',
169
                                    names=('AUTH_PASSWORD',)),
170
    A2_LOGIN_FAILURE_COUNT_BEFORE_WARNING=Setting(
171
        default=0, definition='Failure count before logging a warning to '
172
                              'authentic2.user_login_failure. No warning will be send if value is 0.'),
163 173
    PUSH_PROFILE_UPDATES=Setting(default=False, definition='Push profile update to linked services'),
164 174
    TEMPLATE_VARS=Setting(default={}, definition='Variable to pass to templates'),
165 175
    A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_FACTOR=Setting(default=1.8,
166
            definition='exponential backoff factor duration as seconds until '
167
            'next try after a login failure'),
168
    A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_DURATION=Setting(default=0,
169
            definition='exponential backoff base factor duration as secondss '
170
            'until next try after a login failure'),
171
    A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MAX_DURATION=Setting(default=3600,
172
            definition='maximum exponential backoff maximum duration as seconds until '
173
            'next try after a login failure'),
174
    A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MIN_DURATION=Setting(default=10,
175
            definition='minimum exponential backoff maximum duration as seconds until '
176
            'next try after a login failure'),
176
                                                      definition='exponential backoff factor duration as seconds until '
177
                                                                 'next try after a login failure'),
178
    A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_DURATION=Setting(
179
        default=0,
180
        definition='exponential backoff base factor duration as secondss until next try after a login failure'),
181
    A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MAX_DURATION=Setting(
182
        default=3600,
183
        definition='maximum exponential backoff maximum duration as seconds until next try after a login failure'),
184
    A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MIN_DURATION=Setting(
185
        default=10,
186
        definition='minimum exponential backoff maximum duration as seconds until next try after a login failure'),
177 187
    A2_VERIFY_SSL=Setting(default=True, definition='Verify SSL certificate in HTTP requests'),
178 188
    A2_ATTRIBUTE_KIND_TITLE_CHOICES=Setting(default=(), definition='Choices for the title attribute kind'),
179 189
    A2_CORS_WHITELIST=Setting(default=(), definition='List of origin URL to whitelist, must be scheme://netloc[:port]'),
180 190
    A2_EMAIL_CHANGE_TOKEN_LIFETIME=Setting(default=7200, definition='Lifetime in seconds of the '
181
                                           'token sent to verify email adresses'),
191
                                                                    'token sent to verify email adresses'),
182 192
    A2_REDIRECT_WHITELIST=Setting(
183 193
        default=(),
184 194
        definition='List of origins which are authorized to ask for redirection.'),
......
196 206
    A2_USER_REMEMBER_ME=Setting(
197 207
        default=None,
198 208
        definition='Session duration as seconds when using the remember me '
199
                  'checkbox. Truthiness activates the checkbox.'),
209
                   'checkbox. Truthiness activates the checkbox.'),
200 210
    A2_LOGIN_REDIRECT_AUTHENTICATED_USERS_TO_HOMEPAGE=Setting(
201 211
        default=False,
202 212
        definition='Redirect authenticated users to homepage'),
src/authentic2/settings.py
1
import logging
2 1
import logging.config
2
import os
3 3
# Load default from Django
4 4
from django.conf import global_settings
5
import os
6

  
7 5

  
8 6
from gadjo.templatetags.gadjo import xstatic
9 7
from . import plugins, logger
......
12 10
CACHES = global_settings.CACHES
13 11

  
14 12
BASE_DIR = os.path.dirname(__file__)
15
### Quick-start development settings - unsuitable for production
13
# ### Quick-start development settings - unsuitable for production
16 14
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
17 15

  
18 16
# SECURITY WARNING: keep the secret key used in production secret!
......
34 32
    }
35 33
}
36 34

  
37
### End of "Quick-start development settings"
35
# ### End of "Quick-start development settings"
38 36

  
39 37

  
40 38
# Hey Entr'ouvert is in France !!
......
70 68
    },
71 69
]
72 70

  
73

  
74 71
MIDDLEWARE_CLASSES = (
75 72
    'authentic2.middleware.StoreRequestMiddleware',
76 73
    'authentic2.middleware.RequestIdMiddleware',
......
103 100

  
104 101
STATICFILES_FINDERS = list(global_settings.STATICFILES_FINDERS) + ['gadjo.finders.XStaticFinder']
105 102

  
106
LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), )
103
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
107 104

  
108 105
INSTALLED_APPS = (
109 106
    'django.contrib.staticfiles',
......
145 142
    'django_rbac.backends.DjangoRBACBackend',
146 143
)
147 144
AUTHENTICATION_BACKENDS = plugins.register_plugins_authentication_backends(
148
        AUTHENTICATION_BACKENDS)
145
    AUTHENTICATION_BACKENDS)
149 146
CSRF_FAILURE_VIEW = 'authentic2.views.csrf_failure_view'
150 147

  
151

  
152 148
LOGIN_REDIRECT_URL = '/'
153 149
LOGIN_URL = '/login/'
154 150
LOGOUT_URL = '/logout/'
......
186 182
# Can be none, sp, idp or both
187 183

  
188 184
PASSWORD_HASHERS = list(global_settings.PASSWORD_HASHERS) + [
189
        'authentic2.hashers.Drupal7PasswordHasher',
190
        'authentic2.hashers.SHA256PasswordHasher',
191
        'authentic2.hashers.SSHA1PasswordHasher',
192
        'authentic2.hashers.SMD5PasswordHasher',
193
        'authentic2.hashers.SHA1OLDAPPasswordHasher',
194
        'authentic2.hashers.MD5OLDAPPasswordHasher'
185
    'authentic2.hashers.Drupal7PasswordHasher',
186
    'authentic2.hashers.SHA256PasswordHasher',
187
    'authentic2.hashers.SSHA1PasswordHasher',
188
    'authentic2.hashers.SMD5PasswordHasher',
189
    'authentic2.hashers.SHA1OLDAPPasswordHasher',
190
    'authentic2.hashers.MD5OLDAPPasswordHasher'
195 191
]
196 192

  
197 193
# Admin tools
......
201 197

  
202 198
# Serialization module to support natural keys in generic foreign keys
203 199
SERIALIZATION_MODULES = {
204
        'json': 'authentic2.serializers',
200
    'json': 'authentic2.serializers',
205 201
}
206 202

  
207 203
LOGGING_CONFIG = None
......
210 206
    'disable_existing_loggers': True,
211 207
    'filters': {
212 208
        'cleaning': {
213
            '()':  'authentic2.utils.CleanLogMessage',
209
            '()': 'authentic2.utils.CleanLogMessage',
214 210
        },
215 211
        'request_context': {
216
            '()':  'authentic2.log_filters.RequestContextFilter',
212
            '()': 'authentic2.log_filters.RequestContextFilter',
217 213
        },
218 214
        'force_debug': {
219 215
            '()': 'authentic2.log_filters.ForceDebugFilter',
......
232 228
    'handlers': {
233 229
        'console': {
234 230
            'level': 'DEBUG',
235
            'class':'logging.StreamHandler',
231
            'class': 'logging.StreamHandler',
236 232
            'formatter': 'verbose',
237 233
            'filters': ['cleaning', 'request_context'],
238 234
        },
239
	# remove request_context filter for db log to prevent infinite loop
240
	# when logging sql query to retrieve the session user
235
        # remove request_context filter for db log to prevent infinite loop
236
        # when logging sql query to retrieve the session user
241 237
        'console_db': {
242 238
            'level': 'DEBUG',
243
            'class':'logging.StreamHandler',
239
            'class': 'logging.StreamHandler',
244 240
            'formatter': 'verbose_db',
245 241
            'filters': ['cleaning'],
246 242
        },
......
249 245
        # even when debugging seeing SQL queries is too much, activate it
250 246
        # explicitly using DEBUG_DB
251 247
        'django.db': {
252
                'handlers': ['console_db'],
253
                'level': logger.SettingsLogLevel('INFO', debug_setting='DEBUG_DB'),
254
                'propagate': False,
248
            'handlers': ['console_db'],
249
            'level': logger.SettingsLogLevel('INFO', debug_setting='DEBUG_DB'),
250
            'propagate': False,
255 251
        },
256 252
        'django': {
257
                'level': 'INFO',
253
            'level': 'INFO',
258 254
        },
259 255
        # django_select2 outputs debug message at level INFO
260 256
        'django_select2': {
261
                'level': 'WARNING',
257
            'level': 'WARNING',
262 258
        },
263 259
        # lasso has the bad habit of logging everything as errors
264 260
        'Lasso': {
......
271 267
            'filters': ['force_debug'],
272 268
        },
273 269
        '': {
274
                'handlers': ['console'],
275
                'level': logger.SettingsLogLevel('INFO'),
270
            'handlers': ['console'],
271
            'level': logger.SettingsLogLevel('INFO'),
276 272
        },
277 273
    },
278 274
}
279 275

  
280 276
MIGRATION_MODULES = {
281
        'auth': 'authentic2.auth_migrations',
282
        'menu': 'authentic2.menu_migrations',
283
        'dashboard': 'authentic2.dashboard_migrations',
277
    'auth': 'authentic2.auth_migrations',
278
    'menu': 'authentic2.menu_migrations',
279
    'dashboard': 'authentic2.dashboard_migrations',
284 280
}
285 281
MIGRATION_MODULES['auth'] = 'authentic2.auth_migrations_18'
286 282

  
......
302 298
    'PAGE_SIZE': 100,
303 299
}
304 300

  
305

  
306 301
# Authentic2 Auth SAML
307 302
MELLON_ADAPTER = ('authentic2_auth_saml.adapters.AuthenticAdapter',)
308 303

  
src/authentic2/urls.py
1
from django.conf.urls import url, include
2 1
from django.conf import settings
2
from django.conf.urls import url, include
3 3
from django.contrib import admin
4 4
from django.contrib.staticfiles.views import serve
5 5

  
......
29 29
    url(r'^api/', include('authentic2.api_urls'))
30 30
]
31 31

  
32

  
33 32
urlpatterns += not_homepage_patterns
34 33

  
35 34
try:
......
47 46

  
48 47
if settings.DEBUG and 'debug_toolbar' in settings.INSTALLED_APPS:
49 48
    import debug_toolbar
49

  
50 50
    urlpatterns = [
51
        url(r'^__debug__/', include(debug_toolbar.urls)),
52
    ] + urlpatterns
51
                      url(r'^__debug__/', include(debug_toolbar.urls)),
52
                  ] + urlpatterns
53 53

  
54 54
urlpatterns = plugins.register_plugins_urls(urlpatterns)
src/authentic2/views.py
1
import collections
1 2
import logging
2
from authentic2.compat_lasso import lasso
3
import thread
4
import requests
5
import urllib
6 3
import re
7
import collections
8

  
9

  
10
from django.conf import settings
11
from django.shortcuts import render_to_response, render
12
from django.template.loader import render_to_string, select_template
13
from django.views.generic.edit import UpdateView, FormView
14
from django.views.generic import RedirectView, TemplateView
15
from django.views.generic.base import View
16
from django.contrib.auth import SESSION_KEY
17 4
from django import http, shortcuts
18
from django.core import mail, signing
19
from django.core.urlresolvers import reverse
20
from django.core.exceptions import ValidationError
5
from django.conf import settings
21 6
from django.contrib import messages
22
from django.utils.translation import ugettext as _
23
from django.contrib.auth import logout as auth_logout
24 7
from django.contrib.auth import REDIRECT_FIELD_NAME
25
from django.http import (HttpResponseRedirect, HttpResponseForbidden,
26
    HttpResponse)
27
from django.core.exceptions import PermissionDenied
28
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
29
from django.views.decorators.cache import never_cache
8
from django.contrib.auth import SESSION_KEY
9
from django.contrib.auth import logout as auth_logout
30 10
from django.contrib.auth.decorators import login_required
11
from django.core import signing
12
from django.core.exceptions import ValidationError
13
from django.core.urlresolvers import reverse
31 14
from django.db.models.fields import FieldDoesNotExist
32 15
from django.db.models.query import Q
16
from django.http import (HttpResponseRedirect, HttpResponseForbidden,
17
                         HttpResponse)
18
from django.shortcuts import render_to_response, render
19
from django.template.loader import render_to_string
20
from django.utils.translation import ugettext as _
21
from django.views.decorators.cache import never_cache
22
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
23
from django.views.generic import TemplateView
24
from django.views.generic.base import View
25
from django.views.generic.edit import UpdateView, FormView
26

  
27
from . import (utils, app_settings, forms, compat, decorators, constants, models, cbv, hooks)
33 28

  
34 29
# FIXME: this decorator has nothing to do with an idp, should be moved in the
35 30
# a2 package
36 31
# FIXME: this constant should be moved in the a2 package
37 32

  
38 33

  
39
from . import (utils, app_settings, forms, compat, decorators, constants, models, cbv, hooks)
40

  
41

  
42 34
logger = logging.getLogger(__name__)
43 35

  
44 36

  
......
48 40
    if not next.startswith('http'):
49 41
        next = '/%s%s' % (request.get_host(), next)
50 42
    logging.info('Redirect to %r' % next)
51
    return render_to_response(template_name, { 'next': next })
43
    return render_to_response(template_name, {'next': next})
52 44

  
53 45

  
54 46
def server_error(request, template_name='500.html'):
......
101 93
        else:
102 94
            default_fields = list(attributes.values_list('name', flat=True))
103 95
        fields, labels = utils.get_fields_and_labels(
104
                editable_profile_fields,
105
                default_fields)
96
            editable_profile_fields,
97
            default_fields)
106 98
        if scopes:
107 99
            # restrict fields to those in the scopes
108 100
            fields = [field for field in fields if field in default_fields]
......
145 137
        hooks.call_hooks('event', name='edit-profile', user=self.request.user, form=form)
146 138
        return response
147 139

  
140

  
148 141
edit_profile = decorators.setting_enabled('A2_PROFILE_CAN_EDIT_PROFILE')(
149 142
    login_required(EditProfile.as_view()))
150 143

  
......
200 193
        logging.getLogger(__name__).info('email change request')
201 194
        return super(EmailChangeView, self).form_valid(form)
202 195

  
196

  
203 197
email_change = decorators.setting_enabled('A2_PROFILE_CAN_CHANGE_EMAIL')(
204 198
    login_required(EmailChangeView.as_view()))
205 199

  
......
227 221
                user.email_verified = True
228 222
                user.save()
229 223
                messages.info(request, _('your request for changing your email for {0} '
230
                    'is successful').format(email))
224
                                         'is successful').format(email))
231 225
                logging.getLogger(__name__).info('user %s changed its email '
232 226
                                                 'from %s to %s', user,
233 227
                                                 old_email, email)
234 228
                hooks.call_hooks('event', name='change-email-confirm', user=user, email=email)
235 229
            except signing.SignatureExpired:
236 230
                messages.error(request, _('your request for changing your email is too '
237
                    'old, try again'))
231
                                          'old, try again'))
238 232
            except signing.BadSignature:
239 233
                messages.error(request, _('your request for changing your email is '
240
                    'invalid, try again'))
234
                                          'invalid, try again'))
241 235
            except ValueError:
242 236
                messages.error(request, _('your request for changing your email was not '
243
                    'on this site, try again'))
237
                                          'on this site, try again'))
244 238
            except User.DoesNotExist:
245 239
                messages.error(request, _('your request for changing your email is for '
246
                    'an unknown user, try again'))
240
                                          'an unknown user, try again'))
247 241
            except ValidationError as e:
248 242
                messages.error(request, e.message)
249 243
            else:
......
278 272
    # should be allowed. This regex checks if there is a '//' *before* a
279 273
    # question mark.
280 274
    elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
281
            redirect_to = settings.LOGIN_REDIRECT_URL
275
        redirect_to = settings.LOGIN_REDIRECT_URL
282 276
    nonce = request.GET.get(constants.NONCE_FIELD_NAME)
283 277

  
284 278
    frontends = utils.get_backends('AUTH_FRONTENDS')
......
309 303
            form_class = frontend.form()
310 304
            submit_name = 'submit-%s' % fid
311 305
            block = {
312
                    'id': fid,
313
                    'name': name,
314
                    'frontend': frontend
306
                'id': fid,
307
                'name': name,
308
                'frontend': frontend
315 309
            }
316 310
            if request.method == 'POST' and submit_name in request.POST:
317 311
                form = form_class(data=request.POST)
......
323 317
            else:
324 318
                block['form'] = form_class()
325 319
            blocks.append(block)
326
        else: # New frontends API
320
        else:  # New frontends API
327 321
            parameters = {'request': request,
328 322
                          'context': context}
329 323
            block = utils.get_backend_method(frontend, 'login', parameters)
......
338 332
        else:
339 333
            blocks[-1]['is_hidden'] = False
340 334

  
341

  
342 335
    # Old frontends API
343 336
    for block in blocks:
344 337
        fid = block['id']
......
346 339
            continue
347 340
        frontend = block['frontend']
348 341
        context.update({
349
                'submit_name': 'submit-%s' % fid,
350
                redirect_field_name: redirect_to,
351
                'form': block['form']
342
            'submit_name': 'submit-%s' % fid,
343
            redirect_field_name: redirect_to,
344
            'form': block['form']
352 345
        })
353 346
        if hasattr(frontend, 'get_context'):
354 347
            context.update(frontend.get_context())
355 348
        sub_template_name = frontend.template()
356 349
        block['content'] = render_to_string(
357
                sub_template_name, context,
358
                request=request)
350
            sub_template_name, context,
351
            request=request)
359 352

  
360 353
    request.session.set_test_cookie()
361 354

  
......
389 382
        ctx['authorized_services'] = service_list(self.request)
390 383
        return ctx
391 384

  
385

  
392 386
homepage = Homepage.as_view()
393 387

  
394 388

  
......
423 417
            for field_name in getattr(request.user, 'USER_PROFILE', []):
424 418
                if field_name not in field_names:
425 419
                    field_names.append(field_name)
426
            qs = models.Attribute.objects.filter(Q(user_editable=True)|Q(user_visible=True))
420
            qs = models.Attribute.objects.filter(Q(user_editable=True) | Q(user_visible=True))
427 421
            qs = qs.values_list('name', flat=True)
428 422
            for field_name in qs:
429 423
                if field_name not in field_names:
......
478 472
        parameters = {'request': request,
479 473
                      'context': context}
480 474
        profiles = [utils.get_backend_method(frontend, 'profile', parameters)
481
                            for frontend in frontends]
475
                    for frontend in frontends]
482 476
        # Old frontends data structure for templates
483 477
        blocks = [block['content'] for block in profiles if block]
484 478
        # New frontends data structure for templates
......
506 500
        hooks.call_hooks('modify_context_data', self, context)
507 501
        return context
508 502

  
503

  
509 504
profile = login_required(ProfileView.as_view())
510 505

  
506

  
511 507
def logout_list(request):
512 508
    '''Return logout links from idp backends'''
513 509
    return utils.accumulate_from_backends(request, 'logout_list')
514 510

  
511

  
515 512
def redirect_logout_list(request):
516 513
    '''Return redirect logout links from idp backends'''
517 514
    return utils.accumulate_from_backends(request, 'redirect_logout_list')
518 515

  
516

  
519 517
def logout(request, next_url=None, default_next_url='auth_homepage',
520
        redirect_field_name=REDIRECT_FIELD_NAME,
521
        template='authentic2/logout.html', do_local=True, check_referer=True):
518
           redirect_field_name=REDIRECT_FIELD_NAME,
519
           template='authentic2/logout.html', do_local=True, check_referer=True):
522 520
    '''Logout first check if a logout request is authorized, i.e.
523 521
       that logout was done using a POST with CSRF token or with a GET
524 522
       from the same site.
......
529 527
    logger = logging.getLogger(__name__)
530 528
    default_next_url = utils.make_url(default_next_url)
531 529
    next_url = next_url or request.GET.get(redirect_field_name,
532
            default_next_url)
530
                                           default_next_url)
533 531
    ctx = {}
534 532
    ctx['next_url'] = next_url
535 533
    ctx['redir_timeout'] = 60
......
608 606
        content = u'{0}({1})'.format(callback, int(request.user.is_authenticated()))
609 607
        return HttpResponse(content, content_type='application/json')
610 608

  
609

  
611 610
logged_in = never_cache(LoggedInView.as_view())
612 611

  
612

  
613 613
def csrf_failure_view(request, reason=""):
614 614
    messages.warning(request, _('The page is out of date, it was reloaded for you'))
615 615
    return HttpResponseRedirect(request.get_full_path())
616 616

  
617

  
617 618
def test_redirect(request):
618 619
    next_url = request.GET.get(REDIRECT_FIELD_NAME, settings.LOGIN_REDIRECT_URL)
619 620
    messages.info(request, 'Une info')
620
-