diff --git a/example/app/__init__.py b/example/app/__init__.py new file mode 100644 index 0000000..a6ed466 --- /dev/null +++ b/example/app/__init__.py @@ -0,0 +1 @@ +default_app_config = 'app.apps.BasicAppConfig' diff --git a/example/app/admin.py b/example/app/admin.py new file mode 100644 index 0000000..bef3636 --- /dev/null +++ b/example/app/admin.py @@ -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) diff --git a/example/app/apps.py b/example/app/apps.py new file mode 100644 index 0000000..a76fcc9 --- /dev/null +++ b/example/app/apps.py @@ -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) diff --git a/example/app/fixtures/users.json b/example/app/fixtures/users.json new file mode 100644 index 0000000..6590604 --- /dev/null +++ b/example/app/fixtures/users.json @@ -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": [] + } +} +] diff --git a/example/app/migrations/0001_initial.py b/example/app/migrations/0001_initial.py new file mode 100644 index 0000000..0643401 --- /dev/null +++ b/example/app/migrations/0001_initial.py @@ -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()), + ], + ), + ] diff --git a/example/app/migrations/__init__.py b/example/app/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/example/app/models.py b/example/app/models.py new file mode 100644 index 0000000..c48bbda --- /dev/null +++ b/example/app/models.py @@ -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() diff --git a/example/app/templates/app/home.html b/example/app/templates/app/home.html new file mode 100644 index 0000000..910e176 --- /dev/null +++ b/example/app/templates/app/home.html @@ -0,0 +1,88 @@ + + + + + Test app authens + + + + +{% if messages %} + +

Messages

+ + + +{% endif %} + + +

Utilisateur connecté

+ +{% if user.is_authenticated %} +Connecté avec {{ user }} (superuser: {{ user.is_superuser|yesno:"oui,non" }}) +{% else %} +Non connecté +{% endif %} + +

Pages comptes

+ + + +

Les pages suivantes nécessitent d'être connecté pour y accéder.

+ + + + +

Navigation

+ + +

Accéder à une page

+ + + +

Connexion (/accounts/login/(?next=<redirect>)?)

+ + + +

Déconnexion (/accounts/logout/(?next=<redirect>)?)

+ + diff --git a/example/app/views.py b/example/app/views.py new file mode 100644 index 0000000..c7e2886 --- /dev/null +++ b/example/app/views.py @@ -0,0 +1,5 @@ +from django.views.generic import TemplateView + + +class HomeView(TemplateView): + template_name = 'app/home.html' diff --git a/example/db.sqlite3 b/example/db.sqlite3 new file mode 100644 index 0000000..21cac4b Binary files /dev/null and b/example/db.sqlite3 differ diff --git a/example/fixtures/users.json b/example/fixtures/users.json new file mode 100644 index 0000000..f87008f --- /dev/null +++ b/example/fixtures/users.json @@ -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": [] + } +} +] diff --git a/example/manage.py b/example/manage.py new file mode 100755 index 0000000..7646e46 --- /dev/null +++ b/example/manage.py @@ -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) diff --git a/example/requirements.txt b/example/requirements.txt new file mode 100644 index 0000000..c642fd0 --- /dev/null +++ b/example/requirements.txt @@ -0,0 +1 @@ +-e ../ diff --git a/example/settings.py b/example/settings.py new file mode 100644 index 0000000..5c04e80 --- /dev/null +++ b/example/settings.py @@ -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 diff --git a/example/urls.py b/example/urls.py new file mode 100644 index 0000000..98df25d --- /dev/null +++ b/example/urls.py @@ -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/')), +] diff --git a/example/wsgi.py b/example/wsgi.py new file mode 100644 index 0000000..d9986f9 --- /dev/null +++ b/example/wsgi.py @@ -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()