Add example project

This commit is contained in:
Aurélien Delobelle 2017-08-03 12:41:30 +02:00
parent 916b08374a
commit 9449481bd4
16 changed files with 525 additions and 0 deletions

1
example/app/__init__.py Normal file
View file

@ -0,0 +1 @@
default_app_config = 'app.apps.BasicAppConfig'

27
example/app/admin.py Normal file
View file

@ -0,0 +1,27 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext as _
from .models import User
class ExtendedUserAdmin(UserAdmin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
base_fields = [field.name for field in AbstractUser._meta.fields]
all_fields = [field.name for field in self.model._meta.fields]
extra_fields = [
f for f in all_fields
if f not in base_fields and f != self.model._meta.pk.name
]
self.fieldsets += (
(_('Champs additionnels'), {'fields': extra_fields}),
)
admin.site.register(User, ExtendedUserAdmin)

73
example/app/apps.py Normal file
View file

@ -0,0 +1,73 @@
from django.apps import AppConfig
from django.db.models.signals import post_migrate
def prepare_site(sender, **kwargs):
from django.contrib.sites.models import Site
Site.objects.filter(id=1).update(name="Demo Site", domain="localhost")
def prepare_superuser(sender, **kwargs):
from django.contrib.auth import get_user_model
User = get_user_model()
root, created = User.objects.get_or_create(
username='root',
defaults={
'is_staff': True,
'is_superuser': True,
},
)
if created:
root.set_password('root')
root.save()
print('Superuser created - Credantials: root:root')
def setup_dummy_social(sender, **kwargs):
from django.contrib.sites.models import Site
from django.utils.module_loading import import_string
from allauth.socialaccount.models import SocialApp
from allauth.socialaccount.providers import registry
need_credentials = [
'allauth.socialaccount.providers.oauth.provider.OAuthProvider',
'allauth.socialaccount.providers.oauth2.provider.OAuth2Provider',
]
classes = tuple([import_string(cls_path) for cls_path in need_credentials])
site = Site.objects.get_current()
dummy_installed = []
for provider in registry.get_list():
if isinstance(provider, classes):
try:
SocialApp.objects.get(provider=provider.id, sites=site)
except SocialApp.DoesNotExist:
app = SocialApp.objects.create(
provider=provider.id,
secret='secret',
client_id='client-id',
name='Dummy %s app' % provider.id,
)
app.sites.add(site)
dummy_installed.append(provider.id)
if dummy_installed:
print(
"Dummy application credentials installed for: %s.\n"
"Authentication via these providers will not work until you "
"configure proper credentials via the Django admin (`SocialApp` "
"model)."
% ', '.join(sorted(dummy_installed))
)
class BasicAppConfig(AppConfig):
name = 'app'
def ready(self):
post_migrate.connect(prepare_site, sender=self)
post_migrate.connect(prepare_superuser, sender=self)
post_migrate.connect(setup_dummy_social, sender=self)

View file

@ -0,0 +1,46 @@
[
{
"model": "testapp.user",
"pk": 1,
"fields": {
"password": "pbkdf2_sha256$36000$RNuQMJ1hqN0P$GFFyxtTONjkh4IUMifNYrsXs4/SnX5uMnGtRNR2WrFo=",
"last_login": null,
"is_superuser": false,
"username": "user",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2017-07-03T10:10:18.675Z",
"departement": "",
"occupation": "1A",
"phone": "",
"promo": 2016,
"groups": [],
"user_permissions": []
}
},
{
"model": "testapp.user",
"pk": 2,
"fields": {
"password": "pbkdf2_sha256$36000$NFfbdDHHuq0A$auDXrWn6xr+FnsAOW8uq0aa8m2kyUPtgY/QgThMDKF0=",
"last_login": null,
"is_superuser": true,
"username": "root",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": true,
"is_active": true,
"date_joined": "2017-07-03T10:10:36.413Z",
"departement": "",
"occupation": "1A",
"phone": "",
"promo": 2016,
"groups": [],
"user_permissions": []
}
}
]

View file

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-27 15:06
from __future__ import unicode_literals
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0008_alter_user_username_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name_plural': 'users',
'verbose_name': 'user',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

View file

11
example/app/models.py Normal file
View file

@ -0,0 +1,11 @@
from django.contrib.auth.models import AbstractUser, UserManager
# from authens.models import ENSUserMixin
"""
class User(ENSUserMixin, AbstractUser):
objects = UserManager()
"""
class User(AbstractUser):
objects = UserManager()

View file

@ -0,0 +1,88 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8">
<title>Test app authens</title>
<style>
body {
font-family: Arial;
}
a {
color: blue;
text-decoration: none;
}
a:hover, a:focus {
color: red;
}
</style>
</head>
<body>
{% if messages %}
<h2>Messages</h2>
<ul>
{% for message in messages %}
<li>{{ message.level_tag|upper }} - {{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<h2>Utilisateur connecté</h2>
{% if user.is_authenticated %}
Connecté avec <b>{{ user }}</b> (superuser: <b>{{ user.is_superuser|yesno:"oui,non" }}</b>)
{% else %}
Non connecté
{% endif %}
<h3>Pages comptes</h3>
<ul>
<li><a href="{% url "account_signup" %}">Inscription</a></li>
</ul>
<p>Les pages suivantes nécessitent d'être connecté pour y accéder.</p>
<ul>
<li><a href="{% url "account_settings" %}">Paramètres</a></li>
<li><a href="{% url "account_change_password" %}">Modifier le mot de passe</a></li>
<li><a href="{% url "account_email" %}">Emails</a></li>
<li><a href="{% url "socialaccount_connections" %}">Connexions par tiers</a></li>
</ul>
<h2>Navigation</h2>
<h3>Accéder à une page</h3>
<ul>
<li><a href="{% url "view" %}"><tt>/view/</tt> : non protégée</a></li>
<li><a href="{% url "user-view" %}"><tt>/user/</tt> : authentification requise</a></li>
<li><a href="{% url "root-view" %}"><tt>/root/</tt> : super-utilisateurs seulement</a></li>
<li><a href="{% url "admin:index" %}"><tt>/admin/</tt></a></li>
</ul>
<h3>Connexion (<tt>/accounts/login/(?next=&lt;redirect&gt;)?</tt>)</h3>
<ul>
<li><a href="{% url "account_login" %}">Sans redirection</a></li>
<li><a href="{% url "account_login" %}?next=/view/">Redirection: /view/</a></li>
<li><a href="{% url "account_login" %}?next=/user/">Redirection: /user/</a></li>
<li><a href="{% url "account_login" %}?next=/root/">Redirection: /root/</a></li>
</ul>
<h3>Déconnexion (<tt>/accounts/logout/(?next=&lt;redirect&gt;)?</tt>)</h3>
<ul>
<li><a href="{% url "account_logout" %}">Sans redirection</a></li>
<li><a href="{% url "account_logout" %}?next=/view/">Redirection: /view/</a></li>
<li><a href="{% url "account_logout" %}?next=/user/">Redirection: /user/</a></li>
<li><a href="{% url "account_logout" %}?next=/root/">Redirection: /root/</a></li>
</ul>

5
example/app/views.py Normal file
View file

@ -0,0 +1,5 @@
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'app/home.html'

BIN
example/db.sqlite3 Normal file

Binary file not shown.

View file

@ -0,0 +1,38 @@
[
{
"model": "auth.user",
"pk": 1,
"fields": {
"password": "pbkdf2_sha256$36000$xjRTvXipQpaq$z0kj/h2b4yZp8DNOjhu2TUxSOWHWYX+S+0rvsaWx7TU=",
"last_login": null,
"is_superuser": false,
"username": "user",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": false,
"is_active": true,
"date_joined": "2017-07-01T07:11:08.549Z",
"groups": [],
"user_permissions": []
}
},
{
"model": "auth.user",
"pk": 3,
"fields": {
"password": "pbkdf2_sha256$36000$7IcQUVbp8OM1$7mKhCjAPFLkcEUfu9djXxn/scOw2uvlWLFrMtGfhd0U=",
"last_login": null,
"is_superuser": true,
"username": "root",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": true,
"is_active": true,
"date_joined": "2017-07-01T07:11:20.745Z",
"groups": [],
"user_permissions": []
}
}
]

22
example/manage.py Executable file
View file

@ -0,0 +1,22 @@
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)

1
example/requirements.txt Normal file
View file

@ -0,0 +1 @@
-e ../

121
example/settings.py Normal file
View file

@ -0,0 +1,121 @@
import os
import django
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SECRET_KEY = 'iamaplop'
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
SITE_ID = 1
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'widget_tweaks',
# This one must be before 'allauth' to replace its templates.
'allauth_ens',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth_cas',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'allauth_ens.providers.clipper',
'app',
]
_MIDDLEWARES = [
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.sites.middleware.CurrentSiteMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
if django.VERSION >= (1, 10):
MIDDLEWARE = _MIDDLEWARES
else:
MIDDLEWARE_CLASSES = _MIDDLEWARES
ROOT_URLCONF = 'urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Paris'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'app.User'
LOGIN_URL = '/account/login/'
LOGIN_REDIRECT_URL = '/account/settings/'
SOCIALACCOUNT_QUERY_EMAIL = True
# allauth settings
ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False

30
example/urls.py Normal file
View file

@ -0,0 +1,30 @@
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import RedirectView
from app import views
urlpatterns = [
# Catch admin login/logout views.
# url(r'^admin/login/', authens_views.CaptureLogin.as_view()),
# url(r'^admin/logout/', authens_views.CaptureLogout.as_view()),
# Admin urls include comes after.
url(r'^admin/', admin.site.urls),
# Base views with different required permissions.
url(r'^view/', views.HomeView.as_view(),
name='view'),
url(r'^user/', login_required()(views.HomeView.as_view()),
name='user-view'),
url(r'^root/', permission_required('foo.perm')(views.HomeView.as_view()),
name='root-view'),
# Authens urls (handle login/logout views).
url(r'^account/', include('allauth_ens.urls')),
# (Redirect from /)
url(r'^$', RedirectView.as_view(url='/view/')),
]

16
example/wsgi.py Normal file
View file

@ -0,0 +1,16 @@
"""
WSGI config for plop3 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "plop3.settings")
application = get_wsgi_application()