Projet

Général

Profil

0003-2.patch

Benjamin Dauvergne, 14 mars 2019 13:01

Télécharger (29,4 ko)

Voir les différences:

Subject: [PATCH 3/3] 2

 src/authentic2/a2_rbac/admin.py                  |  2 +-
 src/authentic2/a2_rbac/management.py             |  6 +++---
 src/authentic2/a2_rbac/models.py                 |  4 ++--
 src/authentic2/attribute_kinds.py                |  2 +-
 .../attributes_ng/sources/django_user.py         |  2 +-
 src/authentic2/custom_user/models.py             |  2 +-
 src/authentic2/decorators.py                     |  4 ++--
 src/authentic2/exponential_retry_timeout.py      |  2 +-
 src/authentic2/idp/saml/saml2_endpoints.py       |  4 ++--
 src/authentic2/log_filters.py                    |  2 +-
 .../management/commands/slapd-shell.py           |  2 +-
 src/authentic2/manager/forms.py                  |  4 ++--
 src/authentic2/manager/ou_views.py               |  2 +-
 src/authentic2/manager/resources.py              |  4 ++--
 src/authentic2/manager/service_views.py          |  2 +-
 src/authentic2/manager/views.py                  |  8 ++++----
 src/authentic2/manager/widgets.py                |  2 +-
 src/authentic2/models.py                         |  4 ++--
 src/authentic2/saml/admin.py                     |  2 +-
 src/authentic2/saml/common.py                    |  2 +-
 src/authentic2/saml/models.py                    |  2 +-
 src/authentic2/utils.py                          |  8 ++++----
 src/authentic2/views.py                          |  4 ++--
 src/authentic2_auth_oidc/backends.py             |  2 +-
 src/authentic2_auth_oidc/utils.py                | 16 ++++++++--------
 src/authentic2_idp_cas/views.py                  |  8 ++++----
 src/authentic2_idp_oidc/models.py                | 14 +++++++-------
 src/authentic2_idp_oidc/utils.py                 |  4 ++--
 src/authentic2_idp_oidc/views.py                 |  4 ++--
 src/django_rbac/models.py                        |  4 ++--
 src/django_rbac/utils.py                         |  4 ++--
 31 files changed, 66 insertions(+), 66 deletions(-)
src/authentic2/a2_rbac/admin.py
57 57
    list_select_related = True
58 58

  
59 59
    def name(self, obj):
60
        return text_type(obj)
60
        return six.text_type(obj)
61 61
    name.short_description = _('name')
62 62

  
63 63
admin.site.register(models.Role, RoleAdmin)
src/authentic2/a2_rbac/management.py
28 28
        # do not create scoped admin roles if the model is not scopable
29 29
        if not ou_model:
30 30
            continue
31
        name = text_type(MANAGED_CT[key]['name'])
31
        name = six.text_type(MANAGED_CT[key]['name'])
32 32
        slug = '_a2-' + slugify(name)
33
        scoped_name = text_type(MANAGED_CT[key]['scoped_name'])
33
        scoped_name = six.text_type(MANAGED_CT[key]['scoped_name'])
34 34
        name = scoped_name.format(ou=ou)
35 35
        ou_slug = slug + '-' + ou.slug
36 36
        if app_settings.MANAGED_CONTENT_TYPES == ():
......
113 113
        if ct_tuple not in MANAGED_CT:
114 114
            continue
115 115
        # General admin role
116
        name = text_type(MANAGED_CT[ct_tuple]['name'])
116
        name = six.text_type(MANAGED_CT[ct_tuple]['name'])
117 117
        slug = '_a2-' + slugify(name)
118 118
        if app_settings.MANAGED_CONTENT_TYPES is not None and ct_tuple not in \
119 119
                app_settings.MANAGED_CONTENT_TYPES:
src/authentic2/a2_rbac/models.py
187 187
        admin_role = self.__class__.objects.get_admin_role(
188 188
            self, ou=self.ou,
189 189
            name=_('Managers of role "{role}"').format(
190
                role=text_type(self)),
190
                role=six.text_type(self)),
191 191
            slug='_a2-managers-of-role-{role}'.format(
192
                role=slugify(text_type(self))),
192
                role=slugify(six.text_type(self))),
193 193
            permissions=(utils.get_view_user_perm(),),
194 194
            self_administered=True)
195 195
        return admin_role
src/authentic2/attribute_kinds.py
25 25
from . import app_settings
26 26
from .forms import widgets, fields
27 27

  
28
capfirst = allow_lazy(capfirst, text_type)
28
capfirst = allow_lazy(capfirst, six.text_type)
29 29

  
30 30
DEFAULT_TITLE_CHOICES = (
31 31
    (pgettext_lazy('title', 'Mrs'), pgettext_lazy('title', 'Mrs')),
src/authentic2/attributes_ng/sources/django_user.py
76 76
        ctx['django_user_' + str(av.attribute.name)] = serialized
77 77
        ctx['django_user_' + str(av.attribute.name) + ':verified'] = av.verified
78 78
    ctx['django_user_groups'] = [group for group in user.groups.all()]
79
    ctx['django_user_group_names'] = [text_type(group) for group in user.groups.all()]
79
    ctx['django_user_group_names'] = [six.text_type(group) for group in user.groups.all()]
80 80
    if user.username:
81 81
        splitted = user.username.rsplit('@', 1)
82 82
        ctx['django_user_domain'] = splitted[1] if '@' in user.username else ''
src/authentic2/custom_user/models.py
186 186
        return u'%s (%s)' % (human_name, short_id)
187 187

  
188 188
    def __repr__(self):
189
        return '<User: %r>' % text_type(self)
189
        return '<User: %r>' % six.text_type(self)
190 190

  
191 191
    def clean(self):
192 192
        pass
src/authentic2/decorators.py
165 165
        for i, arg in enumerate(args):
166 166
            if self.args and i not in self.args:
167 167
                continue
168
            parts.append(text_type(arg))
168
            parts.append(six.text_type(arg))
169 169

  
170 170
        for kw, arg in sorted(kwargs.iteritems(), key=lambda x: x[0]):
171 171
            if kw not in self.kwargs:
172 172
                continue
173
            parts.append(u'%s-%s' % (text_type(kw), text_type(arg)))
173
            parts.append(u'%s-%s' % (six.text_type(kw), six.text_type(arg)))
174 174
        return u'|'.join(parts)
175 175

  
176 176

  
src/authentic2/exponential_retry_timeout.py
27 27
        self.key_prefix = key_prefix
28 28

  
29 29
    def key(self, keys):
30
        key = u'-'.join(map(text_type, keys))
30
        key = u'-'.join(map(six.text_type, keys))
31 31
        key = key.encode('utf-8')
32 32
        return '%s%s' % (self.key_prefix or self.KEY_PREFIX, hashlib.md5(key).hexdigest())
33 33

  
src/authentic2/idp/saml/saml2_endpoints.py
707 707
        if dic and 'authz' in dic:
708 708
	    logger.info('decision is %s', dic['authz'])
709 709
            if 'message' in dic:
710
		logger.info(u'with message %s', text_type(dic['message']))
710
		logger.info(u'with message %s', six.text_type(dic['message']))
711 711
            if not dic['authz']:
712 712
                logger.info('access denied by an external function')
713 713
                access_granted = False
......
719 719
            'to the requester')
720 720
        set_saml2_response_responder_status_code(login.response,
721 721
                lasso.SAML2_STATUS_CODE_REQUEST_DENIED,
722
                msg=text_type(dic['message']))
722
                msg=six.text_type(dic['message']))
723 723
        return finish_sso(request, login)
724 724

  
725 725
    provider = load_provider(request, login.remoteProviderId,
src/authentic2/log_filters.py
18 18
        request_id = self.DEFAULT_REQUEST_ID
19 19
        if not request is None:
20 20
            if hasattr(request, 'user') and request.user.is_authenticated():
21
                user = text_type(request.user)
21
                user = six.text_type(request.user)
22 22
            ip = request.META.get('REMOTE_ADDR', self.DEFAULT_IP)
23 23
            request_id = request.request_id
24 24
        record.user = user
src/authentic2/management/commands/slapd-shell.py
72 72
            for user in qs:
73 73
                o = {}
74 74
                for user_attribute, ldap_attribute in MAPPING.iteritems():
75
                    o[ldap_attribute] = [text_type(getattr(user, user_attribute)).encode('utf-8')]
75
                    o[ldap_attribute] = [six.text_type(getattr(user, user_attribute)).encode('utf-8')]
76 76
                o['objectClass'] = ['inetOrgPerson']
77 77
                dn = 'uid=%s,%s' % (escape_dn_chars(o['uid'][0]), attrs['suffix'])
78 78
                self.logger.debug(u'sending entry %s %s', dn, o)
src/authentic2/manager/forms.py
49 49
    def save(self, commit=True):
50 50
        instance = self.instance
51 51
        if not instance.slug:
52
            instance.slug = slugify(text_type(instance.name)).lstrip('_')
52
            instance.slug = slugify(six.text_type(instance.name)).lstrip('_')
53 53
            qs = instance.__class__.objects.all()
54 54
            if instance.pk:
55 55
                qs = qs.exclude(pk=instance.pk)
......
478 478
            if self.show_all_ou and (len(self.ou_qs) > 1 or self.search_all_ous):
479 479
                choices.append(('all', all_ou_label))
480 480
            for ou in self.ou_qs:
481
                choices.append((str(ou.pk), text_type(ou)))
481
                choices.append((str(ou.pk), six.text_type(ou)))
482 482
            if self.search_all_ous:
483 483
                choices.append(('none', pgettext('organizational unit', 'None')))
484 484

  
src/authentic2/manager/ou_views.py
43 43

  
44 44
    @property
45 45
    def title(self):
46
        return text_type(self.object)
46
        return six.text_type(self.object)
47 47

  
48 48
    def authorize(self, request, *args, **kwargs):
49 49
        super(OrganizationalUnitDetailView, self).authorize(request, *args, **kwargs)
src/authentic2/manager/resources.py
12 12
        raise NotImplementedError
13 13

  
14 14
    def render(self, value):
15
        return u', '.join(map(text_type, value.all()))
15
        return u', '.join(map(six.text_type, value.all()))
16 16

  
17 17

  
18 18
class UserResource(ModelResource):
......
24 24
            result.add(role)
25 25
            for pr in role.parent_relation.all():
26 26
                result.add(pr.parent)
27
        return ', '.join(map(text_type, result))
27
        return ', '.join(map(six.text_type, result))
28 28

  
29 29
    class Meta:
30 30
        model = get_user_model()
src/authentic2/manager/service_views.py
31 31

  
32 32
    @property
33 33
    def title(self):
34
        return text_type(self.object)
34
        return six.text_type(self.object)
35 35

  
36 36
    def get_table_queryset(self):
37 37
        return self.object.authorized_roles.all()
src/authentic2/manager/views.py
383 383

  
384 384
    def get_instance_name(self):
385 385
        if hasattr(self, 'get_object'):
386
            return text_type(self.get_object())
386
            return six.text_type(self.get_object())
387 387
        return u''
388 388

  
389 389
    def get_context_data(self, **kwargs):
......
629 629
        menu_entries = []
630 630
        for entry in self.get_homepage_entries():
631 631
            menu_entries.append({
632
                'label': text_type(entry['label']),
632
                'label': six.text_type(entry['label']),
633 633
                'slug': entry.get('slug', ''),
634
                'url': request.build_absolute_uri(text_type(entry['href'])),
634
                'url': request.build_absolute_uri(six.text_type(entry['href'])),
635 635
            })
636 636
        return menu_entries
637 637

  
......
697 697
            with transaction.atomic():
698 698
                import_site(json_site, ImportContext())
699 699
        except DataImportError as e:
700
            form.add_error('site_json', text_type(e))
700
            form.add_error('site_json', six.text_type(e))
701 701
            return self.form_invalid(form)
702 702

  
703 703
        return super(SiteImportView, self).form_valid(form)
src/authentic2/manager/widgets.py
58 58

  
59 59
class RoleLabelMixin(object):
60 60
    def label_from_instance(self, obj):
61
        label = text_type(obj)
61
        label = six.text_type(obj)
62 62
        if obj.ou and utils.get_ou_count() > 1:
63 63
            label = u'{ou} - {obj}'.format(
64 64
                ou=obj.ou, obj=obj)
src/authentic2/models.py
318 318
        verbose_name_plural = _('password reset')
319 319

  
320 320
    def __unicode__(self):
321
        return text_type(self.user)
321
        return six.text_type(self.user)
322 322

  
323 323

  
324 324
class Service(models.Model):
......
374 374
        return self.name
375 375

  
376 376
    def __repr__(self):
377
        return '<%s %r>' % (self.__class__.__name__, text_type(self))
377
        return '<%s %r>' % (self.__class__.__name__, six.text_type(self))
378 378

  
379 379
    def authorize(self, user):
380 380
        if not self.authorized_roles.exists():
src/authentic2/saml/admin.py
51 51
    def render(self, name, value, attrs=None):
52 52
        if attrs is None:
53 53
            attrs = {}
54
        if isinstance(value, (str, text_type)):
54
        if isinstance(value, (str, six.text_type)):
55 55
            attrs['rows'] = value.count('\n') + 5
56 56
            attrs['cols'] = min(max((len(x) for x in value.split('\n'))), 150)
57 57
        return super(TextAndFileWidget, self).render(name, value, attrs)
src/authentic2/saml/common.py
319 319
        return None
320 320
    logger.debug('loaded %d bytes', len(metadata))
321 321
    try:
322
        metadata = text_type(metadata, 'utf8')
322
        metadata = six.text_type(metadata, 'utf8')
323 323
    except:
324 324
        logging.error('SAML metadata autoload: retrieved metadata for entity '
325 325
                      'id %s is not UTF-8', provider_id)
src/authentic2/saml/models.py
412 412
        return (self.liberty_provider.slug,)
413 413

  
414 414
    def __unicode__(self):
415
        return text_type(self.liberty_provider)
415
        return six.text_type(self.liberty_provider)
416 416

  
417 417
    class Meta:
418 418
        verbose_name = _('SAML service provider')
src/authentic2/utils.py
358 358
    # explicitly state that the session has been modified
359 359
    request.session.modified = True
360 360
    event = {
361
        'who': text_type(request.user),
361
        'who': six.text_type(request.user),
362 362
        'who_id': getattr(request.user, 'pk', None),
363 363
        'how': how,
364 364
        'when': int(time.time()),
365 365

  
366 366
    }
367 367
    kwargs = {
368
        'who': text_type(request.user)[:80],
368
        'who': six.text_type(request.user)[:80],
369 369
        'how': how,
370 370
    }
371 371
    nonce = nonce or get_nonce(request)
......
541 541
    for value in values:
542 542
        if isinstance(value, bool):
543 543
            value = str(value).lower()
544
        values_set.add(text_type(value))
544
        values_set.add(six.text_type(value))
545 545
    return values_set
546 546

  
547 547

  
......
847 847
        return dict((utf8_encode(a), utf8_encode(b)) for a, b in v.iteritems())
848 848
    if isinstance(v, (list, tuple)):
849 849
        return type(v)(utf8_encode(a) for a in v)
850
    if isinstance(v, text_type):
850
    if isinstance(v, six.text_type):
851 851
        return v.encode('utf-8')
852 852
    return v
853 853

  
src/authentic2/views.py
453 453
                value = filter(None, value)
454 454
                value = [html_value(attribute, at_value) for at_value in value]
455 455
                if not title:
456
                    title = text_type(attribute)
456
                    title = six.text_type(attribute)
457 457
            else:
458 458
                # fallback to model attributes
459 459
                try:
......
472 472
                if not isinstance(value, (list, tuple)):
473 473
                    value = (value,)
474 474
                raw_value = value
475
                value = map(text_type, value)
475
                value = map(six.text_type, value)
476 476
            if value or app_settings.A2_PROFILE_DISPLAY_EMPTY_FIELDS:
477 477
                profile.append((title, value))
478 478
                attributes.append({'attribute': attribute, 'values': raw_value})
src/authentic2_auth_oidc/backends.py
62 62
                      check_claims={}, algs=algs)
63 63
            jwt.claims
64 64

  
65
        if isinstance(id_token.aud, text_type) and provider.client_id != id_token.aud:
65
        if isinstance(id_token.aud, six.text_type) and provider.client_id != id_token.aud:
66 66
            logger.warning(u'auth_oidc: invalid id_token audience %s != provider client_id %s',
67 67
                           id_token.aud, provider.client_id)
68 68
            return None
src/authentic2_auth_oidc/utils.py
97 97

  
98 98
REQUIRED_ID_TOKEN_KEYS = set(['iss', 'sub', 'aud', 'exp', 'iat'])
99 99
KEY_TYPES = {
100
    'iss': text_type,
101
    'sub': text_type,
100
    'iss': six.text_type,
101
    'sub': six.text_type,
102 102
    'exp': int,
103 103
    'iat': int,
104 104
    'auth_time': int,
105
    'nonce': text_type,
106
    'acr': text_type,
107
    'azp': text_type,
105
    'nonce': six.text_type,
106
    'acr': six.text_type,
107
    'azp': six.text_type,
108 108
    # aud and amr havec specific checks
109 109
}
110 110

  
......
132 132
            raise ValueError('missing field: %s' % (REQUIRED_ID_TOKEN_KEYS - keys))
133 133
        for key in keys:
134 134
            if key == 'aud':
135
                if not isinstance(decoded['aud'], (text_type, list)):
135
                if not isinstance(decoded['aud'], (six.text_type, list)):
136 136
                    raise ValueError('invalid aud value: %r' % decoded['aud'])
137
                if isinstance(decoded['aud'], list) and not all(isinstance(v, text_type) for v in
137
                if isinstance(decoded['aud'], list) and not all(isinstance(v, six.text_type) for v in
138 138
                                                                decoded['aud']):
139 139
                    raise ValueError('invalid aud value: %r' % decoded['aud'])
140 140
            elif key == 'amr':
141 141
                if not isinstance(decoded['amr'], list):
142 142
                    raise ValueError('invalid amr value: %s' % decoded['amr'])
143
                if not all(isinstance(v, text_type) for v in decoded['amr']):
143
                if not all(isinstance(v, six.text_type) for v in decoded['amr']):
144 144
                    raise ValueError('invalid amr value: %s' % decoded['amr'])
145 145
            elif key in KEY_TYPES:
146 146
                if not isinstance(decoded[key], KEY_TYPES[key]):
src/authentic2_idp_cas/views.py
214 214
            attributes = self.get_attributes(request, st)
215 215
            if st.service.identifier_attribute not in attributes:
216 216
                self.logger.error('unable to compute an identifier for user %r and service %s',
217
                        text_type(st.user), st.service_url)
217
                        six.text_type(st.user), st.service_url)
218 218
                return self.validation_failure(request, service, INTERNAL_ERROR)
219 219
            # Compute user identifier
220 220
            identifier = attribute_values_to_identifier(
......
246 246

  
247 247
    def validation_success(self, request, st, identifier):
248 248
        self.logger.info('validation success service: %r ticket: %s '
249
                'user: %r identifier: %r', st.service_url, st.ticket_id, text_type(st.user), identifier)
249
                'user: %r identifier: %r', st.service_url, st.ticket_id, six.text_type(st.user), identifier)
250 250
        return self.real_validation_success(request, st, identifier)
251 251

  
252 252

  
......
275 275
        root = ET.Element(SERVICE_RESPONSE_ELT)
276 276
        success = ET.SubElement(root, AUTHENTICATION_SUCCESS_ELT)
277 277
        user = ET.SubElement(success, USER_ELT)
278
        user.text = text_type(identifier)
278
        user.text = six.text_type(identifier)
279 279
        self.provision_pgt(request, st, success)
280 280
        self.provision_attributes(request, st, success)
281 281
        return HttpResponse(ET.tostring(root, encoding='utf-8'),
......
298 298
        for key, values in values.iteritems():
299 299
            for value in values:
300 300
                attribute_elt = ET.SubElement(attributes_elt, '{%s}%s' % (CAS_NAMESPACE, key))
301
                attribute_elt.text = text_type(value)
301
                attribute_elt.text = six.text_type(value)
302 302

  
303 303

  
304 304
    def provision_pgt(self, request, st, success):
src/authentic2_idp_oidc/models.py
19 19

  
20 20

  
21 21
def generate_uuid():
22
    return text_type(uuid.uuid4())
22
    return six.text_type(uuid.uuid4())
23 23

  
24 24

  
25 25
def validate_https_url(data):
......
189 189

  
190 190
    def __repr__(self):
191 191
        return '<OIDCAuthorization client:%r user:%r scopes:%r>' % (
192
            self.client_id and text_type(self.client),
193
            self.user_id and text_type(self.user),
192
            self.client_id and six.text_type(self.client),
193
            self.user_id and six.text_type(self.user),
194 194
            self.scopes)
195 195

  
196 196

  
......
249 249
    def __repr__(self):
250 250
        return '<OIDCCode uuid:%s client:%s user:%s expired:%s scopes:%s>' % (
251 251
            self.uuid,
252
            self.client_id and text_type(self.client),
253
            self.user_id and text_type(self.user),
252
            self.client_id and six.text_type(self.client),
253
            self.user_id and six.text_type(self.user),
254 254
            self.expired,
255 255
            self.scopes)
256 256

  
......
299 299
    def __repr__(self):
300 300
        return '<OIDCAccessToken uuid:%s client:%s user:%s expired:%s scopes:%s>' % (
301 301
            self.uuid,
302
            self.client_id and text_type(self.client),
303
            self.user_id and text_type(self.user),
302
            self.client_id and six.text_type(self.client),
303
            self.user_id and six.text_type(self.user),
304 304
            self.expired,
305 305
            self.scopes)
306 306

  
src/authentic2_idp_oidc/utils.py
71 71

  
72 72
def clean_words(data):
73 73
    '''Clean and order a list of words'''
74
    return u' '.join(sorted(map(text_type.strip, data.split())))
74
    return u' '.join(sorted(map(six.text_type.strip, data.split())))
75 75

  
76 76

  
77 77
def url_domain(url):
......
82 82
    if client.identifier_policy in (client.POLICY_PAIRWISE, client.POLICY_PAIRWISE_REVERSIBLE):
83 83
        return make_pairwise_sub(client, user)
84 84
    elif client.identifier_policy == client.POLICY_UUID:
85
        return text_type(user.uuid)
85
        return six.text_type(user.uuid)
86 86
    elif client.identifier_policy == client.POLICY_EMAIL:
87 87
        return user.email
88 88
    else:
src/authentic2_idp_oidc/views.py
266 266
                    code.uuid, ' '.join(scopes),
267 267
                    client.name)
268 268
        params = {
269
            'code': text_type(code.uuid),
269
            'code': six.text_type(code.uuid),
270 270
        }
271 271
        if state is not None:
272 272
            params['state'] = state
......
414 414
    if oidc_code.nonce is not None:
415 415
        id_token['nonce'] = oidc_code.nonce
416 416
    response = HttpResponse(json.dumps({
417
        'access_token': text_type(access_token.uuid),
417
        'access_token': six.text_type(access_token.uuid),
418 418
        'token_type': 'Bearer',
419 419
        'expires_in': expires_in,
420 420
        'id_token': utils.make_idtoken(client, id_token),
src/django_rbac/models.py
54 54
    def save(self, *args, **kwargs):
55 55
        # truncate slug and add a hash if it's too long
56 56
        if not self.slug:
57
            self.slug = slugify(text_type(self.name)).lstrip('_')
57
            self.slug = slugify(six.text_type(self.name)).lstrip('_')
58 58
        if len(self.slug) > 256:
59 59
            self.slug = self.slug[:252] + \
60 60
                hashlib.md5(self.slug).hexdigest()[:4]
......
113 113
        return [self.slug]
114 114

  
115 115
    def __unicode__(self):
116
        return text_type(_(self.name))
116
        return six.text_type(_(self.name))
117 117

  
118 118
    def export_json(self):
119 119
        return {'slug': self.slug, 'name': self.name}
src/django_rbac/utils.py
65 65
def get_operation(operation_tpl):
66 66
    from . import models
67 67
    operation, created = models.Operation.objects.get_or_create(
68
        slug=text_type(operation_tpl.slug),
69
        defaults={'name': text_type(operation_tpl.name)})
68
        slug=six.text_type(operation_tpl.slug),
69
        defaults={'name': six.text_type(operation_tpl.name)})
70 70
    return operation
71
-