trivial: apply black

This commit is contained in:
Frédéric Péters 2021-01-13 17:40:37 +01:00
parent d85bd28102
commit 7a234d5fe7
10 changed files with 139 additions and 99 deletions

View File

@ -23,6 +23,7 @@ class compile_translations(Command):
def run(self):
try:
from django.core.management import call_command
for path, dirs, files in os.walk('src'):
if 'locale' not in dirs:
continue
@ -39,7 +40,6 @@ class build(_build):
class eo_sdist(sdist):
def run(self):
if os.path.exists('VERSION'):
os.remove('VERSION')
@ -51,6 +51,7 @@ class eo_sdist(sdist):
if os.path.exists('VERSION'):
os.remove('VERSION')
class install_lib(_install_lib):
def run(self):
self.run_command('compile_translations')
@ -81,30 +82,32 @@ def get_version():
return '0.0'
setup(name='authentic2-auth-fedict',
version=get_version(),
license='AGPLv3',
description='Authentic2 Fedict plugin',
author="Entr'ouvert",
url='https://repos.entrouvert.org/authentic2-auth-fedict.git',
author_email="info@entrouvert.com",
packages=find_packages('src'),
package_dir={
'': 'src',
},
include_package_data=True,
install_requires=[
'authentic2',
setup(
name='authentic2-auth-fedict',
version=get_version(),
license='AGPLv3',
description='Authentic2 Fedict plugin',
author="Entr'ouvert",
url='https://repos.entrouvert.org/authentic2-auth-fedict.git',
author_email="info@entrouvert.com",
packages=find_packages('src'),
package_dir={
'': 'src',
},
include_package_data=True,
install_requires=[
'authentic2',
],
entry_points={
'authentic2.plugin': [
'authentic2-auth-fedict = authentic2_auth_fedict:Plugin',
],
entry_points={
'authentic2.plugin': [
'authentic2-auth-fedict = authentic2_auth_fedict:Plugin',
],
},
cmdclass={
'build': build,
'install_lib': install_lib,
'compile_translations': compile_translations,
'sdist': eo_sdist},
zip_safe=False,
},
cmdclass={
'build': build,
'install_lib': install_lib,
'compile_translations': compile_translations,
'sdist': eo_sdist,
},
zip_safe=False,
)

View File

@ -26,14 +26,17 @@ class AppConfig(django.apps.AppConfig):
def ready(self):
from . import signals
user_logged_in.connect(signals.on_user_logged_in)
default_app_config = 'authentic2_auth_fedict.AppConfig'
class Plugin(object):
def get_before_urls(self):
from . import urls
return urls.urlpatterns
def get_apps(self):
@ -50,6 +53,7 @@ class Plugin(object):
def redirect_logout_list(self, request, next_url=None):
from mellon.views import logout
if 'mellon_session' in request.session:
response = logout(request)
if 'Location' in response:
@ -58,47 +62,66 @@ class Plugin(object):
def registration_form_prefill(self, request):
if request.token.get('first_name'):
return [{'first_name': [request.token.get('first_name')],
'last_name': [request.token.get('last_name')]}]
return [
{
'first_name': [request.token.get('first_name')],
'last_name': [request.token.get('last_name')],
}
]
else:
return [{'first_name': [], 'last_name': []}]
def attribute_kinds(self):
from . import fields
return [
{'label': _('National Register Number'),
'name': 'nrn',
'serialize': json.dumps,
'deserialize': json.loads,
'field_class': fields.NrnField, },
{'label': _('Date'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'date',
'field_class': fields.DateField, },
{'label': _('Date'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'fedict_date',
'field_class': fields.DateField, },
{'label': _('Street'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'street',
'field_class': fields.StreetField, },
{'label': _('House number'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'num_house',
'field_class': fields.NumHouseField, },
{'label': _('Phone number'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'phone',
'field_class': fields.NumPhoneField, },
{'label': _('Country'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'country',
'field_class': fields.CountryField, },
{
'label': _('National Register Number'),
'name': 'nrn',
'serialize': json.dumps,
'deserialize': json.loads,
'field_class': fields.NrnField,
},
{
'label': _('Date'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'date',
'field_class': fields.DateField,
},
{
'label': _('Date'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'fedict_date',
'field_class': fields.DateField,
},
{
'label': _('Street'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'street',
'field_class': fields.StreetField,
},
{
'label': _('House number'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'num_house',
'field_class': fields.NumHouseField,
},
{
'label': _('Phone number'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'phone',
'field_class': fields.NumPhoneField,
},
{
'label': _('Country'),
'serialize': json.dumps,
'deserialize': json.loads,
'name': 'country',
'field_class': fields.CountryField,
},
]

View File

@ -42,6 +42,7 @@ def check_nrn(nrn):
remainder = 97
return int(remainder) == int(nrn[-2:])
def check_nrn_y2k(nrn):
remainder = (97 - int('2' + nrn[:9])) % 97
if remainder == 0:
@ -104,14 +105,12 @@ class AuthenticAdapter(DefaultAdapter):
return
logger = logging.getLogger(__name__)
try:
response = requests.get(settings.RRN_POP_SERVICE_URL + nrn,
verify=False, timeout=5)
response = requests.get(settings.RRN_POP_SERVICE_URL + nrn, verify=False, timeout=5)
except requests.exceptions.RequestException as e:
logger.error('error connecting to rrn pop service (%r)', e)
return
if response.status_code != 200:
logger.error('wrong status code from rrn pop service (%s)',
response.status_code)
logger.error('wrong status code from rrn pop service (%s)', response.status_code)
return
attributes = response.json()
if attributes.get('rue'):
@ -143,7 +142,7 @@ class AuthenticAdapter(DefaultAdapter):
('nom', 'last_name'),
('commune', 'city'),
('rue', 'street'),
('rue', 'address'), # alternative attribute name
('rue', 'address'), # alternative attribute name
('numero', 'num_house'),
('codePostal', 'zipcode'),
('boite', 'num_box'),
@ -154,9 +153,9 @@ class AuthenticAdapter(DefaultAdapter):
]
for nrn_attribute, user_attribute in attribute_mapping:
try:
Attribute.objects.get(name=user_attribute).set_value(user,
attributes.get(nrn_attribute) or '',
verified=True)
Attribute.objects.get(name=user_attribute).set_value(
user, attributes.get(nrn_attribute) or '', verified=True
)
except Attribute.DoesNotExist:
pass
@ -172,8 +171,7 @@ class AuthenticAdapter(DefaultAdapter):
nrn = saml_attributes['egovNRN'][0]
for attr_name in ('niss', 'nrn'):
try:
Attribute.objects.get(name=attr_name).set_value(user, nrn,
verified=True)
Attribute.objects.get(name=attr_name).set_value(user, nrn, verified=True)
except Attribute.DoesNotExist:
pass
if nrn[:6] == '0000001': # unknown date
@ -186,23 +184,24 @@ class AuthenticAdapter(DefaultAdapter):
else:
birthdate = ''
try:
Attribute.objects.get(name='birthdate').set_value(user, birthdate,
verified=True)
Attribute.objects.get(name='birthdate').set_value(user, birthdate, verified=True)
except AttributeError: # native authentic date field
birthdate = datetime.datetime.strptime(birthdate, '%d/%m/%Y').date()
Attribute.objects.get(name='birthdate').set_value(user, birthdate,
verified=True)
Attribute.objects.get(name='birthdate').set_value(user, birthdate, verified=True)
if int(nrn[6:9]) % 2:
title = 'Monsieur'
else:
title = 'Madame'
Attribute.objects.get(name='title').set_value(user, title,
verified=True)
Attribute.objects.get(name='title').set_value(user, title, verified=True)
if saml_attributes.get('givenName'):
Attribute.objects.get(name='first_name').set_value(user, saml_attributes['givenName'][0], verified=True)
Attribute.objects.get(name='first_name').set_value(
user, saml_attributes['givenName'][0], verified=True
)
if saml_attributes.get('surname'):
Attribute.objects.get(name='last_name').set_value(user, saml_attributes['surname'][0], verified=True)
Attribute.objects.get(name='last_name').set_value(
user, saml_attributes['surname'][0], verified=True
)
user.save()

View File

@ -14,8 +14,10 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class AppSettings(object):
'''Thanks django-allauth'''
__SENTINEL = object()
def __init__(self, prefix):

View File

@ -52,5 +52,4 @@ class FedictAuthenticator(BaseAuthenticator):
for user_saml_identifier in user_saml_identifiers:
user_saml_identifier.idp = get_idp(user_saml_identifier.issuer)
context['user_saml_identifiers'] = user_saml_identifiers
return render_to_string('authentic2_auth_fedict/profile.html', context,
request=request)
return render_to_string('authentic2_auth_fedict/profile.html', context, request=request)

View File

@ -17,6 +17,7 @@
import lasso
from mellon.backends import SAMLBackend
class FedictBackend(SAMLBackend):
def get_saml2_authn_context(self):
# The Fedict will return one of:

View File

@ -23,13 +23,16 @@ from django.utils.translation import ugettext_lazy as _
import re
import requests
class NrnField(forms.CharField):
def validate(self, value):
super(NrnField, self).validate(value)
if not value:
return
try:
if (97 - int(value[:9]) % 97) != int(value[-2:]) and (97 - int('2' + value[:9]) % 97) != int(value[-2:]):
if (97 - int(value[:9]) % 97) != int(value[-2:]) and (97 - int('2' + value[:9]) % 97) != int(
value[-2:]
):
raise ValueError()
except ValueError:
raise forms.ValidationError(_('Invalid format for national registry number.'))
@ -38,9 +41,11 @@ class NrnField(forms.CharField):
class DateWidget(forms.TextInput):
class Media:
css = {'all': ('authentic2_auth_fedict/css/datetimepicker.css',)}
js = ('authentic2_auth_fedict/js/bootstrap-datetimepicker.js',
'authentic2_auth_fedict/js/bootstrap-datetimepicker.fr.js',
'authentic2_auth_fedict/js/support.js',)
js = (
'authentic2_auth_fedict/js/bootstrap-datetimepicker.js',
'authentic2_auth_fedict/js/bootstrap-datetimepicker.fr.js',
'authentic2_auth_fedict/js/support.js',
)
def __init__(self, attrs=None):
if not attrs:
@ -69,8 +74,10 @@ class DateField(forms.CharField):
class StreetWidget(forms.TextInput):
class Media:
css = {'all': ('xstatic/themes/smoothness/jquery-ui.css',)}
js = ('xstatic/jquery-ui.js',
'authentic2_auth_fedict/js/support.js',)
js = (
'xstatic/jquery-ui.js',
'authentic2_auth_fedict/js/support.js',
)
def __init__(self, attrs=None):
if not attrs:
@ -92,8 +99,10 @@ class StreetField(forms.CharField):
class CountryWidget(forms.Select):
class Media:
css = {'all': ('xstatic/themes/smoothness/jquery-ui.css',)}
js = ('xstatic/jquery-ui.js',
'authentic2_auth_fedict/js/support.js',)
js = (
'xstatic/jquery-ui.js',
'authentic2_auth_fedict/js/support.js',
)
def __init__(self, attrs=None):
if not attrs:

View File

@ -19,6 +19,7 @@ from authentic2.models import Attribute, AttributeValue
from . import app_settings
from .adapters import AuthenticAdapter
def on_user_logged_in(sender, request, user, **kwargs):
if not app_settings.enable:
return

View File

@ -21,5 +21,9 @@ from . import views
urlpatterns = [
url(r'^accounts/saml/', include('mellon.urls')),
url(r'^accounts/fedict/login/$', views.login, name='fedict-login'),
url(r'^accounts/fedict/register/(?P<token>[a-zA-Z0-9:_-]+)/$', views.registration, name='fedict-registration'),
url(
r'^accounts/fedict/register/(?P<token>[a-zA-Z0-9:_-]+)/$',
views.registration,
name='fedict-registration',
),
]

View File

@ -38,17 +38,15 @@ class RegistrationView(View):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
if not 'email' in data:
data[REDIRECT_FIELD_NAME] = redirect_to
return HttpResponseRedirect("{}?token={}".format(reverse('registration_register'),
signing.dumps(data)))
return HttpResponseRedirect(
"{}?token={}".format(reverse('registration_register'), signing.dumps(data))
)
data['valid_email'] = False
activation_url = \
a2_utils.build_activation_url(request,
next_url=redirect_to,
**data)
activation_url = a2_utils.build_activation_url(request, next_url=redirect_to, **data)
return HttpResponseRedirect(activation_url)
registration = RegistrationView.as_view()
registration = RegistrationView.as_view()
class LoginView(mellon.views.LoginView):
@ -72,4 +70,5 @@ class LoginView(mellon.views.LoginView):
user.save()
return super(LoginView, self).authenticate(request, login, attributes)
login = transaction.non_atomic_requests(csrf_exempt(LoginView.as_view()))