forked from developer italia

This commit is contained in:
gabdevele
2026-06-17 17:46:59 +02:00 Unverified
commit 69e71ec601
43 changed files with 6026 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
#!/bin/bash
./manage.py dumpdata -e admin -e spid_cie_oidc_relying_party -e auth -e contenttypes -e sessions --indent 2 > dumps/example.json
File diff suppressed because one or more lines are too long
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'relying_party.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
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?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
+16
View File
@@ -0,0 +1,16 @@
"""
ASGI config for relying_party project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'relying_party.settings')
application = get_asgi_application()
+89
View File
@@ -0,0 +1,89 @@
"""
Django settings for relying_party project.
Generated by 'django-admin startproject' using Django 4.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from .settingslocal import * # noqa: F401
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'relying_party.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 = 'relying_party.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'it-it'
TIME_ZONE = 'Europe/Rome'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
@@ -0,0 +1,110 @@
import aiohttp
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'visione-cie-rp-local-dev'
DEBUG = True
ADMIN_PATH = 'admin/'
APPEND_SLASH = False
OIDCFED_DEFAULT_TRUST_ANCHOR = "http://127.0.0.1:8000"
OIDCFED_TRUST_ANCHORS = [OIDCFED_DEFAULT_TRUST_ANCHOR]
OIDCFED_REQUIRED_TRUST_MARKS = []
OIDCFED_IDENTITY_PROVIDERS = {
"spid": {
"http://127.0.0.1:8000/oidc/op": OIDCFED_DEFAULT_TRUST_ANCHOR,
},
"cie": {
"http://127.0.0.1:8002/oidc/op": OIDCFED_DEFAULT_TRUST_ANCHOR,
},
}
HTTPC_PARAMS = {
"connection": {"ssl": True},
"session": {"timeout": aiohttp.ClientTimeout(total=4)},
}
LOGIN_REDIRECT_URL = "/visione/complete"
LOGOUT_REDIRECT_URL = "/oidc/rp/landing"
LOGIN_URL = "/oidc/rp/landing"
VISIONE_BACKEND_EXCHANGE_URL = "http://127.0.0.1:5555/api/v1/auth/cie/exchange"
VISIONE_SHARED_SECRET = "change-me-for-local-dev"
VISIONE_DEFAULT_PROVIDER = "http://127.0.0.1:8002/oidc/op"
VISIONE_DEFAULT_PROFILE = "cie"
ALLOWED_HOSTS = ['*']
AUTH_USER_MODEL = 'spid_cie_oidc_accounts.User'
INSTALLED_APPS = [
'spid_cie_oidc.accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"bootstrap_italia_template",
'spid_cie_oidc.entity',
'spid_cie_oidc.authority',
'spid_cie_oidc.relying_party',
'djagger'
]
TEMPLATE_LOADERS = (
'django.template.loaders.eggs.Loader'
)
DJAGGER_DOCUMENT = {
"app_names": ['spid_cie_oidc'],
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'it-it'
TIME_ZONE = 'Europe/Rome'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATA_UPLOAD_MAX_NUMBER_FIELDS = 65000
ADMINS = [('Visione', '[email protected]')]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
},
},
'handlers': {
'console': {
'formatter': 'default',
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'ERROR',
'propagate': False,
},
'spid_cie_oidc': {
'handlers': ['console'],
'level': 'INFO',
'propagate': False,
}
}
}
SESSION_COOKIE_NAME = 'visione_rp_sessionid'
CSRF_COOKIE_NAME = 'visione_rp_csrftoken'
@@ -0,0 +1,161 @@
import aiohttp
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
# CHANGE THIS VALUE
SECRET_KEY = 'lrx(fg&+2e=$l=y8$!£$%$/£%412345234534543--345234-dfdfgsdf-myg%r3z!yjm(lg*l%-z'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# the path corresponding the admin backend, default if not defined: admin/
# CHANGE THIS VALUE
ADMIN_PATH = 'admin/'
APPEND_SLASH = False
# required for onboarding checks and also for all the leafs
OIDCFED_DEFAULT_TRUST_ANCHOR = "http://127.0.0.1:8000"
OIDCFED_TRUST_ANCHORS = [OIDCFED_DEFAULT_TRUST_ANCHOR]
OIDCFED_REQUIRED_TRUST_MARKS = []
# for RP only
OIDCFED_IDENTITY_PROVIDERS = {
"spid": {
"http://127.0.0.1:8000/oidc/op" : OIDCFED_DEFAULT_TRUST_ANCHOR,
},
"cie": {
"http://127.0.0.1:8002/oidc/op" : OIDCFED_DEFAULT_TRUST_ANCHOR,
}
}
HTTPC_PARAMS = {
"connection": {"ssl": True},
"session": {"timeout": aiohttp.ClientTimeout(total=4)},
}
LOGIN_REDIRECT_URL = "/oidc/rp/echo_attributes"
LOGOUT_REDIRECT_URL = "/oidc/rp/landing"
LOGIN_URL = "/oidc/rp/landing"
ALLOWED_HOSTS = ['*']
AUTH_USER_MODEL = 'spid_cie_oidc_accounts.User'
INSTALLED_APPS = [
'spid_cie_oidc.accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"bootstrap_italia_template",
'spid_cie_oidc.entity',
'spid_cie_oidc.authority',
'spid_cie_oidc.relying_party',
'djagger'
]
TEMPLATE_LOADERS = (
'django.template.loaders.eggs.Loader'
)
DJAGGER_DOCUMENT = {
"app_names" : ['spid_cie_oidc'],
}
DATABASES = {
# if you need more power
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'that-username',
# 'HOST': 'localhost',
# 'USER': 'that-user',
# 'PASSWORD': 'that-password',
# 'PORT': '',
# 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"}
# },
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'it-it'
TIME_ZONE = 'Europe/Rome'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATA_UPLOAD_MAX_NUMBER_FIELDS = 65000
# email notification on errors
# DEFAULT_FROM_EMAIL = 'fedauth-noreply@DOMAIN'
# SERVER_EMAIL = DEFAULT_FROM_EMAIL
# EMAIL_HOST = 'smtpservice.yourdomain.it'
# EMAIL_HOST_USER = '[email protected]'
# EMAIL_HOST_PASSWORD = 'mypassword'
# EMAIL_PORT = 587
# EMAIL_USE_TLS = True
ADMINS = [('name surname', 'user1@DOMAIN'),
('name surnale', 'user2@DOMAIN'),]
# LOGGING
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
# exact format is not important, this is the minimum information
'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
},
'detailed': {
'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s [%(pathname)s %(funcName)s:%(lineno)s]'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'formatter': 'detailed',
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'formatter': 'default',
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
"daily": {
"class": "logging.handlers.TimedRotatingFileHandler",
"level": "INFO",
"formatter": "default",
"filename": f"{BASE_DIR}/logs/relying_party.log",
"when": "midnight",
"backupCount": 96
}
},
'loggers': {
'django': {
'handlers': ['console', 'mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'spid_cie_oidc': {
'handlers': ['console', 'mail_admins', "daily"],
'level': 'INFO',
'propagate': False,
}
}
}
+66
View File
@@ -0,0 +1,66 @@
"""acsia_agent_proj URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.contrib import admin
from django.urls import include, path, re_path
from django.views.static import serve
from spid_cie_oidc.entity.urls import urlpatterns as ta_urlpatterns
from .visione_views import VisioneCompleteView, VisioneStartView
admin.site.site_header = "OIDC Federation Relying Party Administration"
admin.site.site_title = "OIDC Federation Relying Party"
admin.site.index_title = "Welcome to OIDC Federation Relying Party Admin backend"
ADMIN_PATH = getattr(settings, 'ADMIN_PATH', 'admin/')
urlpatterns = [
path(f"{ADMIN_PATH}", admin.site.urls),
path("visione/start", VisioneStartView.as_view(), name="visione_start"),
path("visione/complete", VisioneCompleteView.as_view(), name="visione_complete"),
re_path('^static/(?P<path>.*)$',
serve, {
'document_root': settings.STATIC_ROOT,
'show_indexes': True
}
),
]
urlpatterns.extend(ta_urlpatterns)
if 'spid_cie_oidc.relying_party' in settings.INSTALLED_APPS:
from spid_cie_oidc.relying_party.urls import urlpatterns as rp_urlpatterns
urlpatterns.extend(rp_urlpatterns)
from spid_cie_oidc.entity.views import entity_configuration, resolve_entity_statement
urlpatterns.extend(
[
path(
"oidc/rp/.well-known/openid-federation",
entity_configuration,
name="rp_entity_configuration",
),
path(
"oidc/rp/resolve",
resolve_entity_statement,
name="rp_entity_resolve",
),
]
)
if 'djagger' in settings.INSTALLED_APPS:
urlpatterns.append(path('rest/', include('djagger.urls')))
@@ -0,0 +1,105 @@
import hashlib
import hmac
import json
import urllib.error
import urllib.request
from django.conf import settings
from django.http import HttpResponseBadRequest, HttpResponseRedirect, HttpResponseServerError
from django.views import View
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def _normalize_fiscal_code(value):
if not value:
return value
fiscal_code = value.strip().upper()
if fiscal_code.startswith("TINIT-"):
fiscal_code = fiscal_code[6:]
return fiscal_code
class VisioneStartView(View):
def get(self, request):
state = request.GET.get("state")
frontend_redirect_uri = request.GET.get("frontend_redirect_uri")
provider = request.GET.get("provider", settings.VISIONE_DEFAULT_PROVIDER)
profile = request.GET.get("profile", settings.VISIONE_DEFAULT_PROFILE)
if not state or not frontend_redirect_uri:
return HttpResponseBadRequest("Missing state or frontend_redirect_uri")
request.session["visione_state"] = state
request.session["visione_frontend_redirect_uri"] = frontend_redirect_uri
request.session["visione_provider_issuer"] = provider
return HttpResponseRedirect(
f"/oidc/rp/authorization?provider={provider}&profile={profile}"
)
class VisioneCompleteView(View):
def get(self, request):
user_attrs = request.session.get("oidc_rp_user_attrs", {})
state = request.session.get("visione_state")
issuer = request.session.get("visione_provider_issuer")
fiscal_code = user_attrs.get("fiscal_number") or user_attrs.get(
"https://attributes.eid.gov.it/fiscal_number"
)
fiscal_code = _normalize_fiscal_code(fiscal_code)
subject = user_attrs.get("sub") or user_attrs.get("username")
if not state or not issuer or not subject or not fiscal_code:
return HttpResponseBadRequest("Missing Visione auth session or user attributes")
payload = {
"state": state,
"issuer": issuer,
"subject": subject,
"fiscal_code": fiscal_code,
"first_name": user_attrs.get("given_name", ""),
"last_name": user_attrs.get("family_name", ""),
"email": user_attrs.get("email", ""),
}
raw_body = json.dumps(payload, separators=(",", ":"))
signature = hmac.new(
settings.VISIONE_SHARED_SECRET.encode("utf-8"),
raw_body.encode("utf-8"),
hashlib.sha256,
).hexdigest().upper()
req = urllib.request.Request(
settings.VISIONE_BACKEND_EXCHANGE_URL,
data=raw_body.encode("utf-8"),
headers={
"Content-Type": "application/json",
"X-Visione-Signature": signature,
},
method="POST",
)
opener = urllib.request.build_opener(_NoRedirectHandler)
try:
opener.open(req)
except urllib.error.HTTPError as exc:
if exc.code in (301, 302, 303, 307, 308):
location = exc.headers.get("Location")
if location:
return HttpResponseRedirect(location)
return HttpResponseServerError("Visione backend returned redirect without location")
error_body = ""
try:
error_body = exc.read().decode("utf-8").strip()
except Exception:
error_body = ""
detail = f" {error_body}" if error_body else ""
return HttpResponseServerError(
f"Visione backend exchange failed: {exc.code}{detail}"
)
except Exception as exc:
return HttpResponseServerError(f"Visione backend exchange failed: {exc}")
return HttpResponseServerError("Visione backend exchange did not redirect")
+16
View File
@@ -0,0 +1,16 @@
"""
WSGI config for relying_party 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/4.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'relying_party.settings')
application = get_wsgi_application()
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
./manage.py migrate
./manage.py runserver 0.0.0.0:8001