first commit

This commit is contained in:
Benjamin Dauvergne 2015-08-26 09:46:40 +02:00
commit bbf7d00829
22 changed files with 627 additions and 0 deletions

17
.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
MANIFEST
*.pyc
*.pyo
*.db
.*.swp
cache/
dist/
./static/
doc/_build
authentic.egg-info
local_settings.py
log.log
authentic2/locale/fr/LC_MESSAGES/django.mo
local_settings.*
*.egg-info
*.mo
.tox

2
COPYING Normal file
View File

@ -0,0 +1,2 @@
authentic2-formiris is entirely under the copyright of Entr'ouvert and
distributed under the license AGPLv3 or later.

3
MANIFEST.in Normal file
View File

@ -0,0 +1,3 @@
include COPYING
recursive-include src/authentic2_formiris/templates *.html
recursive-include src/authentic2_formiris/static *.js *.css *.png

20
README Normal file
View File

@ -0,0 +1,20 @@
** THIS IS A TEMPLATE PROJECT **
To rename it to your taste:
$ ./adapt.sh
** THIS IS A TEMPLATE PROJECT **
Authentic2 Formiris
==========================
Install
-------
You just have to install the package in your virtualenv and relaunch, it will
be automatically loaded by authentic2.
Settings
--------
** DESCRIBE CUSTOM SETTINGS HERE **

55
setup.py Executable file
View File

@ -0,0 +1,55 @@
#!/usr/bin/python
import subprocess
from setuptools import setup, find_packages
import os
def get_version():
'''Use the VERSION, if absent generates a version with git describe, if not
tag exists, take 0.0.0- and add the length of the commit log.
'''
if os.path.exists('VERSION'):
with open('VERSION', 'r') as v:
return v.read()
if os.path.exists('.git'):
p = subprocess.Popen(['git','describe','--dirty','--match=v*'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = p.communicate()[0]
if p.returncode == 0:
return result.split()[0][1:].replace('-', '.')
else:
return '0.0.0-%s' % len(
subprocess.check_output(
['git', 'rev-list', 'HEAD']).splitlines())
return '0.0.0'
README = file(os.path.join(
os.path.dirname(__file__),
'README')).read()
setup(name='authentic2-formiris',
version=get_version(),
license='AGPLv3',
description='Authentic2 Formiris',
long_description=README,
author="Entr'ouvert",
author_email="info@entrouvert.com",
packages=find_packages('src'),
package_dir={
'': 'src',
},
package_data={
'authentic2_formiris': [
'templates/authentic2_formiris/*.html',
'static/authentic2_formiris/js/*.js',
'static/authentic2_formiris/css/*.css',
'static/authentic2_formiris/img/*.png',
],
},
install_requires=[
],
entry_points={
'authentic2.plugin': [
'authentic2-formiris= authentic2_formiris:Plugin',
],
},
)

View File

@ -0,0 +1,86 @@
class Plugin(object):
def get_before_urls(self):
from . import urls
return urls.urlpatterns
def get_after_urls(self):
return []
def get_apps(self):
return [__name__]
def get_before_middleware(self):
return []
def get_after_middleware(self):
return []
def get_authentication_backends(self):
return []
def get_auth_frontends(self):
return []
def get_idp_backends(self):
return []
def get_admin_modules(self):
from . import dashboard
return dashboard.get_admin_modules()
def service_list(self, request):
'''For IdP plugins this method add links to the user homepage.
It must return a list of authentic2.utils.Service objects, each
object has a name and can have an url and some actions.
Service(name=name[, url=url[, actions=actions]])
Actions are a list of tuples, whose parts are
- first the name of the action,
- the HTTP method for calling the action,
- the URL for calling the action,
- the paramters to pass to this URL as a sequence of key-value
tuples.
'''
return []
def logout_list(self, request):
'''For IdP or SP plugins this method add actions to logout from remote
IdP or SP.
It must returns a list of HTML fragments, each fragment is
responsible for calling the view doing the logout. Views are usually
called using <img/> or <iframge/> tags and finally redirect to an
icon indicating success or failure for the logout.
Authentic2 provide two such icons through the following URLs:
- os.path.join(settings.STATIC_URL, 'authentic2/img/ok.png')
- os.path.join(settings.STATIC_URL, 'authentic2/img/ok.png')
'''
return []
def check_view_restrictions(self, request):
from . import models
from django.utils.timezone import now
from datetime import timedelta
# no user logged in
if not request.user.is_authenticated():
return
try:
restriction = models.ProfileUpdate.objects.get(
user=request.user)
except models.ProfileUpdate.DoesNotExist:
# not profile update needed
return
# ok profile updated and validated
if restriction.validated is not None:
return
# user have 7 days to validate
if restriction.updated is not None and \
(now() - restriction.updated) < timedelta(days=7):
return
# force profile update
return 'authentic2-formiris-update-profile'

View File

@ -0,0 +1,51 @@
import logging
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from authentic2 import admin as a2_admin
from . import models
def force_profile_update(modeladmin, request, queryset):
# delete old ones
models.ProfileUpdate.objects.filter(user=queryset).delete()
# create new
logger = logging.getLogger(__name__)
for user in queryset:
models.ProfileUpdate.objects.get_or_create(
user=user)
logger.info(u'force update of profile for user %s', user)
force_profile_update.short_description = _('Force profile update')
a2_admin.AuthenticUserAdmin.actions = a2_admin.AuthenticUserAdmin.actions + \
[force_profile_update]
class ProfileUpdateAdmin(admin.ModelAdmin):
actions = ['validate', 'send_email']
list_display = ['user', 'created', 'updated', 'first_name', 'last_name',
'email', 'validated']
search_fields = ['user__email', 'user__last_name', 'user__first_name',
'first_name', 'last_name', 'email', 'user__username']
readonly_fields = ['token']
def validate(self, request, queryset):
logger = logging.getLogger(__name__)
for o in queryset:
if o.validate():
logger.info(u'profile update of user %s validated by '
'administrator', o.user)
validate.short_description = _('Validate profile update')
def send_email(self, request, queryset):
logger = logging.getLogger(__name__)
for o in queryset:
if o.validated is not None:
continue
o.send_mail(request)
logger.info(u'profile update validation email of user %s resent '
'by admin', o.user)
send_email.short_description = _('Resend validation email')
admin.site.register(models.ProfileUpdate, ProfileUpdateAdmin)

View File

@ -0,0 +1,23 @@
class AppSettings(object):
__DEFAULTS = {
'ENABLE': True,
}
def __init__(self, prefix):
self.prefix = prefix
def _setting(self, name, dflt):
from django.conf import settings
return getattr(settings, self.prefix+name, dflt)
def __getattr__(self, name):
if name not in self.__DEFAULTS:
raise AttributeError(name)
return self._setting(name, self.__DEFAULTS[name])
# Ugly? Guido recommends this himself ...
# http://mail.python.org/pipermail/python-ideas/2012-May/014969.html
import sys
app_settings = AppSettings('A2_PLUGIN_TEMPLATE_')
app_settings.__name__ = __name__
sys.modules[__name__] = app_settings

View File

@ -0,0 +1,11 @@
from django.utils.translation import ugettext_lazy as _
from admin_tools.dashboard import modules
def get_admin_modules():
'''Show Client model in authentic2 admin'''
model_list = modules.ModelList(_('Formiris'),
models=('authentic2_formiris.models.*',))
return (model_list,)

View File

@ -0,0 +1,35 @@
from django import forms
from django.contrib.auth import get_user_model
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from . import models
class UpdateProfileForm(forms.ModelForm):
first_name = forms.CharField(
label=_('first name').title(),
max_length=64)
last_name = forms.CharField(
label=_('last name').title(),
max_length=64)
email = forms.EmailField(
label=_('email address').title(),
max_length=254)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(UpdateProfileForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
self.instance.updated = now()
self.instance.send_mail(self.request)
return super(UpdateProfileForm, self).save(commit=commit)
class Meta:
model = models.ProfileUpdate
fields = [
'first_name',
'last_name',
'email',
]

View File

@ -0,0 +1,86 @@
# authentic2-formiris
# Copyright (C) 2015 Entr'ouvert
# This file is distributed under the same license as the authentic2-formiris package.
# Benjamin Dauvergne <bdauvergne@entrouvert.com>, 2015.
#
msgid ""
msgstr ""
"Project-Id-Version: authentic2-formiris 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2015-08-26 16:50+0200\n"
"PO-Revision-Date: 2015-08-26 16:50+0200\n"
"Last-Translator: Benjamin Dauvergne <bdauvergne@entrouvert.com>\n"
"Language-Team: French <fr@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: authentic2_formiris/admin.py:15
msgid "Force profile update"
msgstr "Forcer une mise à jour du profil"
#: authentic2_formiris/admin.py:30
msgid "Validate profile update"
msgstr "Valider les mises à jour du profil"
#: authentic2_formiris/admin.py:35
msgid "Resend validation email"
msgstr "Renvoyer les courriels de confirmation"
#: authentic2_formiris/dashboard.py:8
msgid "Formiris"
msgstr "Formiris"
#: authentic2_formiris/forms.py:11 authentic2_formiris/models.py:20
msgid "first name"
msgstr ""
#: authentic2_formiris/forms.py:14 authentic2_formiris/models.py:24
msgid "last name"
msgstr ""
#: authentic2_formiris/forms.py:17 authentic2_formiris/models.py:28
msgid "email address"
msgstr ""
#: authentic2_formiris/models.py:17
msgid "user"
msgstr ""
#: authentic2_formiris/models.py:33
msgid "token"
msgstr "jeton"
#: authentic2_formiris/models.py:36
msgid "created"
msgstr "date de création"
#: authentic2_formiris/models.py:40
msgid "updated"
msgstr "date de mise à jour"
#: authentic2_formiris/models.py:44
msgid "validated"
msgstr "date de confirmation"
#: authentic2_formiris/models.py:63
msgid "profile update"
msgstr "demande de mise à jour du profil"
#: authentic2_formiris/models.py:64
msgid "profile updates"
msgstr "demandes de mise à jour du profil"
#: authentic2_formiris/views.py:23
msgid "Validation mail sent again"
msgstr "Le courriel de confirmation a été renvoyé."
#: authentic2_formiris/views.py:39
msgid "Dead link, email not validated"
msgstr "Ce lien est mort, votre profil a déjà été confirmé."
#: authentic2_formiris/views.py:41
msgid "Email validated"
msgstr "Courriel confirmé."

View File

@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import authentic2_formiris.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ProfileUpdate',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)),
('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)),
('email', models.EmailField(max_length=75, verbose_name='email address', blank=True)),
('token', models.CharField(default=authentic2_formiris.models.get_token, max_length=64, verbose_name='token')),
('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
('updated', models.DateTimeField(null=True, verbose_name='updated')),
('validated', models.DateTimeField(null=True, verbose_name='validated')),
('user', models.ForeignKey(verbose_name='user', to=settings.AUTH_USER_MODEL, unique=True)),
],
options={
'ordering': ('user__last_name', 'user__first_name'),
'verbose_name': 'profile update',
'verbose_name_plural': 'profile updates',
},
bases=(models.Model,),
),
]

View File

@ -0,0 +1,70 @@
# -*- coding: utf-8 -*-
import random
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from django.conf import settings
from authentic2.utils import send_templated_mail
# put your models here
def get_token():
return str(random.randint(1, 100000000000))
class ProfileUpdate(models.Model):
user = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
verbose_name=_('user'),
unique=True)
first_name = models.CharField(
_('first name'),
max_length=30,
blank=True)
last_name = models.CharField(
_('last name'),
max_length=30,
blank=True)
email = models.EmailField(
_('email address'),
blank=True)
token = models.CharField(
default=get_token,
max_length=64,
verbose_name=_('token'))
created = models.DateTimeField(
auto_now_add=True,
verbose_name=_('created'))
updated = models.DateTimeField(
null=True,
blank=True,
verbose_name=_('updated'))
validated = models.DateTimeField(
null=True,
blank=True,
verbose_name=_('validated'))
def validate(self):
if self.validated is None:
self.user.first_name = self.first_name
self.user.last_name = self.last_name
self.user.email = self.email
self.user.save()
self.validated = now()
self.save()
return True
def send_mail(self, request):
ctx = {
'update': self,
'base_url': request.build_absolute_uri('/')[:-1],
}
send_templated_mail(self.email, 'authentic2_formiris/email', ctx)
def __unicode__(self):
return u"utilisateur %s" % self.user
class Meta:
verbose_name = _('profile update')
verbose_name_plural = _('profile updates')
ordering = ('user__last_name', 'user__first_name')

View File

@ -0,0 +1,2 @@
En cas de problème contactez Formiris Assistance au 0800 849 949 du lundi au
vendredi de 9h à 12h30 et de 13h30 à 17h.

View File

@ -0,0 +1,15 @@
Ce mail fait suite à la mise à jour de votre profil sur www.formelie.org,
veuillez vérifier les informations ci-contre et cliquer sur le lien suivant si
celles-ci sont corrects:
Prénom: {{ update.first_name }}
Nom: {{ update.last_name }}
Email: {{ update.email }}
Lien de validation: {{ base_url }}{% url 'authentic2-formiris-validate-profile' token=update.token %}
Vous diposez de 7 jours pour valider votre adresse de courriel, passé ce délais
votre compte sera bloqué.
{% include "authentic2_formiris/assistance.txt" %}

View File

@ -0,0 +1 @@
Validation de de votre profil formelie

View File

@ -0,0 +1,25 @@
{% extends "authentic2/base-page.html" %}
{% load i18n %}
{% block title %}Mise à jour de votre profil{% endblock %}
{% block content %}
<h1>Mise à jour de votre profil</h1>
<p>
Vous devez mettre à jour les informations votre profil. Pour pouvoir
continuer, remplissez le formulaire suivant avec vos informations puis
cliquer sur le bouton "Mettre à jour".
</p>
<p>
Après la mise à jour vous recevrez un
courriel de confirmation contenant un lien sur lequel cliquer pour valider
votre adresse de courriel. Sans confirmation de votre adresse de courriel
dans un délais de 7 jours, votre compte sera bloqué.
</p>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button>Mettre à jour</button>
</form>
<p>{% include "authentic2_formiris/assistance.txt" %}</p>
{% endblock %}

View File

@ -0,0 +1,20 @@
{% extends "authentic2/base-page.html" %}
{% load i18n %}
{% block title %}
Adresse de courriel non validée
{% endblock %}
{% block content %}
<h1>Adresse de courriel non validée</h1>
<p>
Suite à la mise à jour de votre profil, vous n'avez pas confirmé votre adresse de
courriel dans un délais de 7 jours. Si vous n'avez pas reçu le courriel de
confirmation cliquez sur le bouton.
</p>
<form method="post">
{% csrf_token %}
<button>Renvoyer un mail</button>
</form>
<p>{% include "authentic2_formiris/assistance.txt" %}</p>
{% endblock %}

View File

@ -0,0 +1,16 @@
from django.conf.urls import patterns, url
from authentic2.decorators import setting_enabled, required
from . import app_settings
from .views import index, validate
urlpatterns = required(
setting_enabled('ENABLE', settings=app_settings),
patterns('',
url('^accounts/update-profile/$', index,
name='authentic2-formiris-update-profile'),
url('^accounts/validate-profile/(?P<token>\d+)/$', validate,
name='authentic2-formiris-validate-profile'),
)
)

View File

@ -0,0 +1,53 @@
import logging
from datetime import timedelta
from django.shortcuts import render
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.utils.timezone import now
from authentic2.utils import continue_to_next_url, redirect
from . import models, forms
__ALL_ = ['index', 'validate']
def index(request):
logger = logging.getLogger(__name__)
try:
restriction = models.ProfileUpdate.objects.get(user=request.user)
except models.ProfileUpdate:
return continue_to_next_url(request)
if restriction.updated is not None and \
(now() - restriction.updated) >= timedelta(days=7):
logger.info(u'user blocked because its profile update has not been '
'validated in %s days', (now() - restriction.update).days)
if request.method == 'POST':
restriction.send_mail(request)
logger.info('profile update validation email resent')
messages.info(request, _('Validation mail sent again'))
return render(request, 'authentic2_formiris/timeout.html')
if request.method == 'POST':
form = forms.UpdateProfileForm(data=request.POST, instance=restriction,
request=request)
if form.is_valid():
logger.info(u'profile updated, waiting for validation')
form.save()
return continue_to_next_url(request)
else:
form = forms.UpdateProfileForm(instance=restriction, request=request)
return render(request, 'authentic2_formiris/index.html', {'form': form})
def validate(request, token):
logger = logging.getLogger(__name__)
try:
pu = models.ProfileUpdate.objects.get(token=token)
pu.validate()
except models.ProfileUpdate.DoesNotExist:
messages.info(request, _('Dead link, email not validated'))
else:
logger.info(u'profile update email %s validated', pu.email)
messages.info(request, _('Email validated'))
return redirect(request, 'auth_homepage')