diff --git a/.coverage b/.coverage
new file mode 100644
index 0000000000..5a5c463248
Binary files /dev/null and b/.coverage differ
diff --git a/.env.docker b/.env.docker
new file mode 100644
index 0000000000..fc81249476
--- /dev/null
+++ b/.env.docker
@@ -0,0 +1,20 @@
+# --- Security ---
+DJANGO_SETTINGS_MODULE=config.django.dev.docker
+SECRET_KEY=change-me-in-prod-secret-key
+EXPOSITION_PORT=8000
+
+# --- Database ---
+MYSQL_DATABASE=pod_db
+MYSQL_USER=pod_user
+MYSQL_PASSWORD=pod_password
+MYSQL_ROOT_PASSWORD=root_password
+MYSQL_HOST=db
+MYSQL_PORT=3307
+
+# --- Superuser ---
+DJANGO_SUPERUSER_USERNAME=admin
+DJANGO_SUPERUSER_EMAIL=admin@example.com
+DJANGO_SUPERUSER_PASSWORD=admin
+
+# --- Versioning ---
+VERSION=5.0.0-DEV
diff --git a/.flake8 b/.flake8
new file mode 100644
index 0000000000..ce72676e35
--- /dev/null
+++ b/.flake8
@@ -0,0 +1,46 @@
+[flake8]
+exclude =
+ # Version Control & Environments
+ .git,
+ .venv,
+ venv,
+ __pycache__,
+
+ # Testing & Coverage
+ .pytest_cache,
+ htmlcov,
+
+ # Migrations
+ */migrations/*,
+
+ # Static & Media
+ src/static/*,
+ staticfiles,
+ media,
+ node_modules,
+
+ # Specific Custom ignores
+ *_settings.py,
+ src/custom/tenants/*/*,
+ docs
+
+max-complexity = 9
+max-line-length = 90
+
+# See https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#flake8
+ignore =
+ # Black
+ E501,
+ E203,
+ W503,
+
+ # Pydocstyle
+ D107,
+ D105,
+
+ # flake8-annotations
+ ANN002,
+ ANN003,
+ ANN101,
+ ANN102,
+ ANN204
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000..7cdd1e9c63
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,3 @@
+# Set the default behaviour, in case users have not set core.autocrlf.
+* text=auto
+Dockerfile text eol=lf
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000000..2b49aff89e
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,5 @@
+# Before sending your pull request, make sure the following are done
+
+* [ ] You have read our [contribution guidelines](CONTRIBUTING.md).
+* [ ] Your PR targets the `dev_v5` branch.
+* [ ] Your PR status is in `draft` if it’s still a work in progress.
\ No newline at end of file
diff --git a/.github/workflows/build-dev.yml b/.github/workflows/build-dev.yml
new file mode 100644
index 0000000000..c2169aa047
--- /dev/null
+++ b/.github/workflows/build-dev.yml
@@ -0,0 +1,52 @@
+name: Build and Push Dev Image
+
+on:
+ push:
+ branches:
+ - "**"
+ paths:
+ - "deployment/dev/**"
+ - "src/**"
+ - "requirements.txt"
+ - ".github/workflows/build-dev.yml"
+
+env:
+ REGISTRY: ghcr.io
+ IMAGE_NAME: ${{ github.repository }}
+
+jobs:
+ build-and-push-dev:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ packages: write
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Log in to the Container registry
+ uses: docker/login-action@v3
+ with:
+ registry: ${{ env.REGISTRY }}
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Extract metadata (tags, labels) for Docker
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
+ tags: |
+ type=ref,event=branch
+ type=sha,format=short
+ type=raw,value=dev-{{branch}}-{{sha}}
+
+ - name: Build and push Docker image
+ uses: docker/build-push-action@v5
+ with:
+ context: .
+ file: deployment/dev/Dockerfile
+ push: true
+ tags: ${{ steps.meta.outputs.tags }}
+ labels: ${{ steps.meta.outputs.labels }}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000000..ef076fcc27
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,114 @@
+name: Pod V5 CI/CD
+
+on:
+ push:
+ branches:
+ - "**"
+ pull_request:
+ branches:
+ - dev_v5
+ - main
+
+jobs:
+ # 1. Code Quality
+ quality-check:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python 3.12
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ cache: 'pip'
+
+ - name: Install dependencies
+ run: |
+ pip install flake8 black
+
+ - name: Format code with Black
+ run: |
+ black . -l 90
+
+ - name: Lint with flake8
+ run: flake8 src --count --show-source --statistics
+
+ - name: Check for non-breaking spaces (NBSP)
+ run: |
+ if grep -rnIP "\xa0" src; then
+ echo "Error: Non-breaking spaces (NBSP) found in the codebase. Please remove them."
+ exit 1
+ fi
+
+ # 2. Docker Integration, E2E & Security (The Authoritative Test)
+ test-docker-full:
+ needs: [quality-check]
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python 3.12
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+
+ - name: Create .env file
+ run: cp .env.docker .env
+
+ - name: Build Stack
+ env:
+ VERSION: 5.0.0-DEV
+ DJANGO_SETTINGS_MODULE: config.django.dev.docker
+ run: make build
+
+ - name: Start Stack
+ env:
+ VERSION: 5.0.0-DEV
+ DJANGO_SETTINGS_MODULE: config.django.dev.docker
+ run: make start
+
+ - name: Wait for Services
+ run: |
+ set -e
+ echo "Waiting for API..."
+ # Retry loop to wait for API to be ready
+ count=0
+ until curl -sf http://127.0.0.1:8000/api/docs/ > /dev/null || [ $count -eq 60 ]; do
+ echo "Waiting for API... ($count/60)"
+ sleep 2
+ count=$((count+1))
+ done
+
+ if [ $count -eq 60 ]; then
+ echo "API failed to start"
+ make logs
+ exit 1
+ fi
+
+ - name: Run Tests with Coverage (Inside Docker)
+ run: make test
+
+ - name: Install E2E dependencies
+ run: |
+ pip install --upgrade pip
+ pip install requests
+
+ - name: Run Smoke & E2E Tests
+ # Runs against the running docker container from the host
+ run: python src/config/django/test/e2e_scenario.py
+
+ - name: Basic Load Test
+ run: |
+ fail=0
+ for i in {1..50}; do
+ curl -sf http://127.0.0.1:8000/api/docs/ > /dev/null || fail=1 &
+ done
+ wait
+ if [ "$fail" -ne 0 ]; then
+ echo "Load test failed"
+ exit 1
+ fi
+
+ - name: Teardown
+ if: always()
+ run: make clean
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000..79418b3918
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,43 @@
+# --- Python ---
+__pycache__/
+*.py[cod]
+*$py.class
+*.pyc
+
+# --- Django ---
+*.log
+settings_local.py
+db.sqlite3
+db.sqlite3-journal
+media/
+staticfiles/
+
+# --- Environnement & Secrets ---
+.env
+.env.prod
+
+.venv/
+venv/
+env/
+
+# --- IDE & OS ---
+.idea/
+.vscode/
+*.swp
+.DS_Store
+Thumbs.db
+
+# --- Docker ---
+mysql_data/
+
+# --- Custom files ---
+log/
+media/
+transcription/
+
+
+# --- Tests & Coverage ---
+.coverage
+.pytest_cache/
+htmlcov/
+.coverage
diff --git a/AUTHORS.md b/AUTHORS.md
new file mode 100644
index 0000000000..d27133dbfd
--- /dev/null
+++ b/AUTHORS.md
@@ -0,0 +1,45 @@
+Esup-Pod Authors
+================
+
+Maintainer
+----------
+
+ [Esup Portail](https://www.esup-portail.org/)
+
+Original Authors
+----------------
+
+* Nicolas Can, University of Lille, France ([@ptitloup](https://github.com/ptitloup))
+
+Contributors for the V3
+----------------------------
+
+A list of much-appreciated contributors
+who have submitted patches and reported bugs for the V3:
+
+* Olivier Bado-Faustin, University Cote d'Azur (design and template)
+* Nicolas Lahoche, University of Lille (design and template) with all the PRI Team
+* Nathaniel Burlot, University of Lille (member of PRI team for Logo and color of V3)
+* Céline Didier and Matthieu Bildstein, University of Lorraine (Live's Event App)
+* Farid Ait Karra, University of Lille (Docker part)
+* Maxime Taisne and Laurine Sajdak, University of Lille (Documentation and User part)
+* French Ministry of Education (who funded the development of some features)
+
+Partnership
+----------------------------
+
+* Elygames
+* OrionStudio
+
+Previous Author/Contributors
+----------------------------
+
+A list of much-appreciated contributors who have submitted patches and reported bugs:
+
+* Joël Obled, Esup-Portail Consortium, France ([@DrClockwork](https://github.com/DrClockwork))
+* Charlotte Benard (Logo and color of V2)
+* Frederic Sene, INSA Rennes
+* Frédéric Colau, Eliam Lotonga and Jeremie Grepilloux, University Grenoble Alpes
+* Loic Bonavent, University of Montpellier
+* Guillaume Condesse, University of Bordeaux
+* All participants of the October 2018 Pod Technical Workshop
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000..085908eaba
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,141 @@
+# Code de conduite *Esup-Pod*
+
+## Notre engagement
+
+En tant que membres, contributeur·trice·s et dirigeant·e·s, nous nous
+engageons à faire de la participation à notre communauté
+une expérience sans harcèlement, quel que soit l'âge,
+la taille corporelle, le handicap visible ou invisible, l'appartenance ethnique,
+les caractéristiques sexuelles, l'identité et l'expression de genre,
+le niveau d'expérience, l'éducation, le statut socio-économique,
+la nationalité, l'apparence personnelle, la race, la religion,
+ou l'identité et l'orientation sexuelle.
+
+Nous nous engageons à agir et interagir de manière à contribuer à une communauté ouverte,
+accueillante, diversifiée, inclusive et saine.
+
+## Nos critères
+
+Exemples de comportements qui contribuent à créer un environnement positif :
+
+* Faire preuve d'empathie et de bienveillance envers les autres
+* Être respectueux des opinions, points de vue et expériences divergents
+* Donner et recevoir avec grâce les critiques constructives
+* Assumer ses responsabilités et s'excuser auprès des personnes
+ affectées par nos erreurs et apprendre de ces expériences
+* Se concentrer sur ce qui est le meilleur non pas uniquement pour nous
+ en tant qu'individu, mais aussi pour l'ensemble de la communauté
+
+Exemples de comportements inacceptables :
+
+* L'utilisation de langage ou d'images sexualisés et d'attentions
+ ou d'avances sexuelles de toute nature
+* Le *trolling*, les commentaires insultants ou désobligeants et les attaques
+ personnelles ou d'ordre politique
+* Le harcèlement en public ou en privé
+* La publication d'informations privées d'autrui, telle qu'une
+ adresse postale ou une adresse électronique, sans leur autorisation explicite
+* Toute autre conduite qui pourrait raisonnablement
+ être considérée comme inappropriée dans un cadre professionnel
+
+## Responsabilités d'application
+
+Les dirigeant·e·s de la communauté sont chargé·e·s de clarifier
+et de faire respecter nos normes de comportements acceptables
+et prendront des mesures correctives appropriées et équitables en
+réponse à tout comportement qu'ils ou elles jugent
+inapproprié, menaçant, offensant ou nuisible.
+
+Les dirigeant·e·s de la communauté ont le droit et la responsabilité de supprimer,
+modifier ou rejeter les commentaires,
+les contributions, le code, les modifications de wikis,
+les rapports d'incidents ou de bogues et autres contributions qui
+ne sont pas alignés sur ce code de conduite,
+et communiqueront les raisons des décisions de modération le cas échéant.
+
+## Portée d'application
+
+Ce code de conduite s'applique à la fois au sein des espaces du projet
+ainsi que dans les espaces publics lorsqu'un individu
+représente officiellement le projet ou sa communauté.
+Font parties des exemples de représentation d'un projet ou d'une
+communauté l'utilisation d'une adresse électronique officielle,
+la publication sur les réseaux sociaux à l'aide d'un compte officiel
+ou le fait d'agir en tant que représentant·e désigné·e
+lors d'un événement en ligne ou hors-ligne.
+
+## Application
+
+Les cas de comportements abusifs, harcelants ou tout autre comportement
+inacceptables peuvent être signalés aux dirigeant·e·s de la communauté
+responsables de l'application du code de conduite à
+[Esup-Pod](https://github.com/EsupPortail/Esup-Pod).
+Toutes les plaintes seront examinées et feront l'objet d'une enquête rapide et équitable.
+
+Tou·te·s les dirigeant·e·s de la communauté sont tenu·e·s de
+respecter la vie privée et la sécurité des personnes ayant signalé un incident.
+
+## Directives d'application
+
+Les dirigeant·e·s de communauté suivront ces directives d'application
+sur l'impact communautaire afin de déterminer les conséquences de toute action
+qu'ils jugent contraire au présent code de conduite :
+
+### 1. Correction
+
+**Impact communautaire** : utilisation d'un langage inapproprié ou
+tout autre comportement jugé non professionnel ou indésirable dans la communauté.
+
+**Conséquence** : un avertissement écrit et privé de la part des
+dirigeant·e·s de la communauté, clarifiant la nature du non-respect et expliquant pourquoi
+le comportement était inapproprié. Des excuses publiques peuvent être demandées.
+
+### 2. Avertissement
+
+**Impact communautaire** : un non-respect par un seul incident ou une série d'actions.
+
+**Conséquence** : un avertissement avec des conséquences dû à la poursuite du comportement.
+Aucune interaction avec les personnes concernées,
+y compris l'interaction non sollicitée avec celles et ceux qui sont
+chargé·e·s de l'application de ce code de conduite, pendant une période déterminée.
+Cela comprend le fait d'éviter les interactions dans les espaces communautaires
+ainsi que sur les canaux externes comme les médias sociaux.
+Le non-respect de ces conditions peut entraîner un bannissement temporaire ou permanent.
+
+### 3. Bannissement temporaire
+
+**Impact communautaire** : un non-respect grave des normes communautaires,
+notamment un comportement inapproprié soutenu.
+
+**Conséquence** : un bannissement temporaire de toutes formes d'interactions
+ou de communications avec la communauté pendant une période déterminée.
+Aucune interaction publique ou privée avec les personnes concernées,
+y compris les interactions non sollicitées avec celles et ceux qui appliquent
+ce code de conduite, n'est autorisée pendant cette période.
+Le non-respect de ces conditions peut entraîner un bannissement permanent.
+
+### 4. Bannissement permanent
+
+**Impact communautaire** : démontrer un schéma récurrent de non-respect
+des normes de la communauté y compris un comportement inapproprié soutenu,
+le harcèlement d'un individu ainsi que l'agression ou le dénigrement de catégories d'individus.
+
+**Conséquence** : un bannissement permanent
+de toutes formes d'interactions publiques au sein de la communauté.
+
+## Attributions
+
+Ce code de conduite est adapté du
+[Contributor Covenant][homepage], [version 2.0][v2.0].
+
+Les Directives d'application ont été inspirées par le
+[Code of conduct enforcement ladder][Mozilla CoC] de Mozilla.
+
+Pour obtenir des réponses aux questions courantes sur ce code de conduite, consultez la [FAQ][FAQ].
+Des [traductions][translations] sont disponibles.
+
+[homepage]: https://www.contributor-covenant.org
+[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000..000334982f
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,202 @@
+# Contributing to Esup-Pod
+
+:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:
+
+The following is a set of guidelines for contributing to Pod, which is hosted
+in the [Esup Organization](https://github.com/EsupPortail) on GitHub.
+These are mostly guidelines, not rules.
+Use your best judgment, and feel free to propose changes to this document in a pull request.
+
+## Table of contents
+
+* [Code of Conduct](#code-of-conduct)
+
+* [How Can I Contribute?](#how-can-i-contribute)
+ * [Reporting Bugs](#reporting-bugs)
+ * [Suggesting Enhancements](#suggesting-enhancements)
+ * [Pull Requests](#pull-requests)
+
+* [Styleguides](#styleguides)
+ * [Git Commit Messages](#git-commit-messages)
+
+* [Coding conventions](#coding-conventions)
+ * [JavaScript Styleguide](#javascript-styleguide)
+ * [Python Styleguide](#python-styleguide)
+
+## Code of Conduct
+
+This project and everyone participating in it is governed by the [Pod Code of Conduct](CODE_OF_CONDUCT.md).
+By participating, you are expected to uphold this code.
+Please report unacceptable behavior to us.
+
+## I don’t want to read this whole thing I just have a question
+
+If chat is more your speed, you can [join the Pod team on Rocket chat](https://rocket.esup-portail.org/channel/esup_-_pod).
+
+## How Can I Contribute?
+
+### Reporting Bugs
+
+This section guides you through submitting a bug report.
+Following these guidelines helps maintainers and the
+community understand your report :pencil:, reproduce the behavior :computer: :computer:,
+and find related reports :mag_right:.
+
+When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report).
+
+> **Note:** If you find a **Closed** issue that seems like it is the same thing
+that you’re experiencing, open a new issue and include a link
+to the original issue in the body of your new one.
+
+#### How Do I Submit A (Good) Bug Report?
+
+Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/).
+Create an issue and explain the problem and include additional details
+to help maintainers reproduce the problem:
+
+* **Use a clear and descriptive title** for the issue to identify the problem.
+* **Describe the exact steps which reproduce the problem** in as many details as possible.
+* **Provide specific examples to demonstrate the steps**. Include links to files
+or GitHub projects, or copy/pasteable snippets, which you use in those examples.
+* **Describe the behavior you observed after following the steps** and point out
+what exactly is the problem with that behavior.
+* **Explain which behavior you expected to see instead and why.**
+* **Include screenshots and animated GIFs** which show you following the described steps
+and clearly demonstrate the problem.
+You can use [this tool](https://www.cockos.com/licecap/)
+to record GIFs on macOS and Windows,
+and [this tool](https://github.com/colinkeenan/silentcast)
+or [this tool](https://github.com/GNOME/byzanz) on Linux.
+* **If the problem wasn’t triggered by a specific action**, describe what you were doing
+before the problem happened and share more information using the guidelines below.
+* **Can you reliably reproduce the issue?** If not, provide details about
+how often the problem happens and under which conditions it normally happens.
+
+Include details about your configuration and environment:
+
+* **Which version of Pod are you using?**
+* **What’s the name and version of the browser you’re using**?
+
+### Suggesting Enhancements
+
+This section guides you through submitting an enhancement suggestion for Pod,
+including completely new features and minor improvements to existing functionality.
+Following these guidelines helps maintainers and the community understand
+your suggestion :pencil: and find related suggestions :mag_right:.
+
+#### How Do I Submit A (Good) Enhancement Suggestion?
+
+Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/).
+Create an issue and provide the following information:
+
+* **Use a clear and descriptive title** for the issue to identify the suggestion.
+* **Provide a step-by-step description of the suggested enhancement** as many detailed as possible.
+* **Provide specific examples to demonstrate the steps**.
+Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
+* **Describe the current behavior**
+ and **explain which behavior you expected to see instead** and why.
+* **Include screenshots and animated GIFs** which help you demonstrate the steps
+or point out the part which the suggestion is related to.
+You can use [this tool](https://www.cockos.com/licecap/)
+to record GIFs on macOS and Windows,
+and [this tool](https://github.com/colinkeenan/silentcast)
+or [this tool](https://github.com/GNOME/byzanz) on Linux.
+* **Specify which version of Pod you’re using.**
+* **Specify the name and version of the browser you’re using.**
+
+### Pull Requests
+
+The process described here has several goals:
+
+* Maintain quality
+* Fix problems that are important to users
+* Engage the community in working toward the best possible Pod
+* Enable a sustainable system for maintainers to review contributions
+
+Please follow these steps to have your contribution considered by the maintainers:
+
+0. Follow the [styleguides](#styleguides) below.
+1. Make sure that your pull request targets the `dev_v5` branch.
+2. Your PR status is in `draft` while it’s still a work in progress.
+3. After you submit your pull request, verify that
+all [status checks](https://help.github.com/articles/about-status-checks/) are passing
+
+
+What if the status checks are failing?
+If a status check is failing,
+and you believe that the failure is unrelated to your change,
+please leave a comment on the pull request explaining
+why you believe the failure is unrelated.
+A maintainer will re-run the status check for you.
+If we conclude that the failure was a false positive,
+then we will open an issue to track that problem with our status check suite.
+
+While the prerequisites above must be satisfied prior to having your pull request reviewed,
+the reviewer(s) may ask you to complete additional design work, tests,
+or other changes before your pull request can be ultimately accepted.
+
+## Styleguides
+
+### Git config
+
+Warning about the configuration of line ending: [configuring-git-to-handle-line-endings](https://docs.github.com/fr/get-started/getting-started-with-git/configuring-git-to-handle-line-endings)
+We add a .gitattributes file at the root of repository
+
+### Git Commit Messages
+
+* Use the present tense ("Add feature" not "Added feature")
+* Use the imperative mood ("Move cursor to…" not "Moves cursor to…")
+* Limit the first line to 72 characters or less
+* Reference issues and pull requests liberally after the first line
+* When only changing documentation, include `[ci skip]` in the commit title
+* Consider starting the commit message with an applicable emoji:
+ * :art: `:art:` when improving the format/structure of the code
+ * :racehorse: `:racehorse:` when improving performance
+ * :non-potable_water: `:non-potable_water:` when plugging memory leaks
+ * :memo: `:memo:` when writing docs
+ * :bug: `:bug:` when fixing a bug
+ * :fire: `:fire:` when removing code or files
+ * :green_heart: `:green_heart:` when fixing the CI build
+ * :white_check_mark: `:white_check_mark:` when adding tests
+ * :lock: `:lock:` when dealing with security
+ * :arrow_up: `:arrow_up:` when upgrading dependencies
+ * :arrow_down: `:arrow_down:` when downgrading dependencies
+ * :shirt: `:shirt:` when removing linter warnings
+
+## Coding conventions
+
+Start reading our code and you’ll get the hang of it. We optimize for readability:
+
+* Configuration variables are uppercase and can be called
+in all modules keeping the same name.
+For example, `MAVAR = getattr(settings, "MAVAR", default value)`
+* Global variables to a module are also in uppercase but are considered private
+to the module and therefore must be prefixed and suffixed with a double underscore
+* All .py files must be indented using **4 spaces**,
+and all other files (.css, .html, .js) with **2 spaces** (soft tabs)
+* This is open source software.
+Consider the people who will read your code, and make it look nice for them.
+It’s sort of like driving a car: Perhaps you love doing donuts when you’re alone,
+but with passengers the goal is to make the ride as smooth as possible.
+
+### JavaScript Styleguide
+
+All JavaScript code is linted with [eslint](https://eslint.org/).
+
+### Python Styleguide
+
+All python code is linted with [flake8](https://flake8.pycqa.org/en/latest/)
+
+### Typography
+
+Please use these typographic characters in all displayed strings:
+
+* Use Apostrophe (’) instead of single quote (')
+ * English samples: don’t, it’s
+ * French samples: J’aime, l’histoire
+* Use the ellipsis (…) instead of 3 dots (...)
+ * English sample: Loading…
+ * French sample: Chargement…
+* Use typographic quotes (“ ”) instead of neutral quotes (" ")
+ * English sample: You can use the “Description” field below.
+ * French sample: Utilisez le champ « Description » ci-dessous
diff --git a/COPYING.LESSER b/COPYING.LESSER
new file mode 100644
index 0000000000..0a041280bd
--- /dev/null
+++ b/COPYING.LESSER
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/COPYING.txt b/COPYING.txt
new file mode 100644
index 0000000000..f288702d2f
--- /dev/null
+++ b/COPYING.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000000..35cb254b83
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,63 @@
+# Load the .env
+ifneq (,$(wildcard ./.env))
+ include .env
+ export
+endif
+
+DOCKER_COMPOSE_FILE=deployment/dev/docker-compose.yml
+DOCKER_COMPOSE_CMD=docker compose -f $(DOCKER_COMPOSE_FILE)
+DOCKER_SERVICE_NAME=api
+
+.PHONY: help start logs shell enter build stop clean runserver test check-django-env
+
+help:
+ @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
+ awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
+
+# ==========================================
+# COMMANDS (Docker Only)
+# ==========================================
+
+start: check-django-env ## Start the full project (auto-setup via entrypoint)
+ @echo "Starting Docker environment..."
+ $(DOCKER_COMPOSE_CMD) up --build -d
+ @echo "Server running in background. Use 'make logs' to follow output."
+
+logs: ## Show real-time logs (see automatic migrations)
+ $(DOCKER_COMPOSE_CMD) logs -f $(DOCKER_SERVICE_NAME)
+
+shell: ## Launch a temporary container in shell mode (isolated)
+ @echo "Opening an isolated shell..."
+ $(DOCKER_COMPOSE_CMD) run --rm --service-ports $(DOCKER_SERVICE_NAME) shell-mode
+
+enter: ## Enter an already running container (for debugging)
+ @echo "Entering active container..."
+ $(DOCKER_COMPOSE_CMD) exec $(DOCKER_SERVICE_NAME) /bin/bash
+
+build: ## Force rebuild of Docker images
+ $(DOCKER_COMPOSE_CMD) build
+
+stop: ## Stop the containers
+ $(DOCKER_COMPOSE_CMD) stop
+
+clean: ## Stop and remove everything (containers, orphaned networks, volumes)
+ $(DOCKER_COMPOSE_CMD) down --remove-orphans --volumes
+
+runserver: ## Start the server when you using shell mode
+ @echo "Use 'make shell' to enter the container, then run 'run-server' or 'python manage.py runserver 0.0.0.0:8000'"
+ @echo "This command is deprecated in favor of 'make start' or 'make shell'."
+
+test: ## Run tests inside the container
+ @echo "Running tests in Docker..."
+ $(DOCKER_COMPOSE_CMD) exec -e DJANGO_SETTINGS_MODULE=config.django.test.docker $(DOCKER_SERVICE_NAME) pytest --cov=src --cov-report=term-missing --cov-fail-under=60
+
+check-django-env:
+ @# Verify the .env configuration for the Docker context
+ @if [ "$${DJANGO_SETTINGS_MODULE##*.}" != "docker" ]; then \
+ echo "Environment configuration ERROR:"; \
+ echo " To use Docker, you must correctly configure your .env file."; \
+ echo " Please refer to the deployment documentation."; \
+ echo " Current DJANGO_SETTINGS_MODULE: '$${DJANGO_SETTINGS_MODULE}'"; \
+ echo " Expected: must end with '.docker'"; \
+ exit 1; \
+ fi
diff --git a/README.md b/README.md
index e797990830..341d274d1e 100644
--- a/README.md
+++ b/README.md
@@ -23,14 +23,25 @@ Le projet et la plateforme qui porte le même nom ont pour but de faciliter
la mise à disposition de vidéos et de ce fait, d’encourager
l’utilisation de celles-ci dans le cadre de l’enseignement et la recherche.
-#### Documentation technique
+**Esup-Pod V5** est l’API backend de la plateforme de gestion vidéo Pod.
+Conçue pour l’Enseignement Supérieur et la Recherche, elle permet la publication, l’enrichissement et la diffusion de vidéos.
+
+> [!NOTE]
+> Ce dépôt contient le backend **V5 (Python/Django)**.
+> Retrouvez la documentation ici [ESUP-POD V5 Documentation](./docs/README.md)
+> Pour la version V4 ou la documentation institutionnelle, voir le [ESUP-Portail Wiki](https://www.esup-portail.org/wiki/display/ES/esup-pod).
-* [Documentation générale (installation, paramétrage etc.)](https://www.esup-portail.org/wiki/display/ES/esup-pod)
-* [Conteneurisation (installation, paramétrage, lancement etc.)](./dockerfile-dev-with-volumes/README.adoc)
-* [Configuration (paramétrage, personnalisation etc.)](./CONFIGURATION_FR.md)
## [EN]
+**Esup-Pod V5** is the backend API for the Pod video management platform.
+Ideally suited for Higher Education and Research institutions, it facilitates video publishing, enrichment, and dissemination.
+
+> [!NOTE]
+> This repository contains the **V5 (Python/Django)** backend.
+> Find the documentation here [ESUP-POD V5 Documentation](./docs/README.md)
+> For the legacy V4 version or specific institutional documentation, please refer to the [ESUP-Portail Wiki](https://www.esup-portail.org/wiki/display/ES/esup-pod).
+
### Video file management platform
Created in 2014 at the university of [Lille](https://www.univ-lille.fr/),
@@ -44,6 +55,19 @@ by allowing the publication of videos in the fields of research
(promotion of platforms, etc.), training (tutorials, distance training, student reports, etc.),
institutional life (video of events), offering several days of content.
+## Quick Start
+
+For developers, a **Makefile** is available to simplify common tasks.
+
+```bash
+make help # List all available commands
+make start # Start the project with Docker
+make test # Run tests inside Docker
+```
+
+For detailed instructions, see:
+* [Development Guide](docs/deployment/dev/dev.md)
+
### Technical documentation
* The documentation (to install, customize, etc…) is on the
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000000..d37467500d
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,10 @@
+# Security Policy
+
+## Supported Versions
+
+If you want most up to date secured version of Esup-Pod,
+we encourage you to upgrade to the last release.
+
+## Reporting a Vulnerability
+
+As soon as you found a vulnerability issue in Esup-Pod, let us know by posting a github issue.
diff --git a/TODO.md b/TODO.md
new file mode 100644
index 0000000000..9bbbb08e44
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,54 @@
+# TODO
+
+## Authentification
+
+- [ ] Auditer **l’authentification complète** (backend, permissions, refresh, erreurs, sécurité)
+- [ ] Corriger tous les écarts (logique, sécurité, cohérence)
+- [ ] Rédiger la **documentation technique de l’authentification**
+ - flux
+ - endpoints
+ - modèles
+ - schémas
+ - cas d’erreur
+
+## Qualité / Tests / CI
+
+- [ ] Écrire les **tests unitaires des modèles**
+- [ ] Écrire les **tests d’intégration liés à l’auth**
+- [ ] Mettre en place / corriger la **CI** (lint, tests, coverage, build)
+
+## Git / Livraison
+
+- [ ] Nettoyer la branche (commits atomiques, messages propres)
+- [ ] Rebase sur `main`
+- [ ] Ouvrir une **première PR propre et lisible**
+
+## API REST
+
+- [ ] Répertorier **tous les endpoints existants**
+- [ ] Identifier les endpoints :
+ - manquants
+ - incohérents
+ - non documentés
+- [ ] Produire une **liste claire + statut**
+
+## Modélisation de l'object vidéo
+
+- [ ] Analyser l’objet **Video**
+- [ ] Définir :
+ - responsabilités
+ - champs
+ - relations
+ - règles métier
+- [ ] Proposer un **schéma propre + évolutif**
+
+
+Table vidéo :
+- Titre *
+- id *
+- description
+- miniature
+- #proprio *
+- #proprios-add
+- etat *
+- flux video
\ No newline at end of file
diff --git a/deployment/dev/Dockerfile b/deployment/dev/Dockerfile
new file mode 100644
index 0000000000..45f4bb2b65
--- /dev/null
+++ b/deployment/dev/Dockerfile
@@ -0,0 +1,37 @@
+FROM python:3.12-slim
+
+ENV PYTHONDONTWRITEBYTECODE=1
+ENV PYTHONUNBUFFERED=1
+ENV DEBIAN_FRONTEND=noninteractive
+
+WORKDIR /app
+
+RUN apt-get update && apt-get install -y \
+ pkg-config \
+ python3-dev \
+ default-libmysqlclient-dev \
+ build-essential \
+ netcat-openbsd \
+ git \
+ dos2unix \
+ && rm -rf /var/lib/apt/lists/*
+
+COPY requirements.txt /app/requirements.base.txt
+COPY deployment/dev/requirements.txt /app/requirements.dev.txt
+
+RUN pip install --upgrade pip && \
+ pip install --no-cache-dir -r requirements.base.txt -r requirements.dev.txt
+
+ENV PYTHONPATH=/app/src
+ENV DJANGO_SETTINGS_MODULE=${DJANGO_SETTINGS_MODULE}
+
+EXPOSE 8000
+
+COPY src /app/src
+COPY manage.py /app/manage.py
+
+COPY deployment/dev/entrypoint.sh /usr/local/bin/entrypoint.sh
+
+RUN dos2unix /usr/local/bin/entrypoint.sh && chmod +x /usr/local/bin/entrypoint.sh
+
+ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
diff --git a/deployment/dev/docker-compose.yml b/deployment/dev/docker-compose.yml
new file mode 100644
index 0000000000..24858b5e00
--- /dev/null
+++ b/deployment/dev/docker-compose.yml
@@ -0,0 +1,44 @@
+services:
+ db:
+ image: mariadb:10.11
+ container_name: pod_mariadb_dev
+ env_file:
+ - ../../.env
+ environment:
+ MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root_password}
+ ports:
+ - "${MYSQL_PORT:-3307}:3306"
+ volumes:
+ - pod_db_data_dev:/var/lib/mysql
+ - ./init_test_db.sql:/docker-entrypoint-initdb.d/init_test_db.sql
+ healthcheck:
+ test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
+ interval: 10s
+ timeout: 5s
+ retries: 5
+
+ api:
+ build:
+ context: ../../
+ dockerfile: deployment/dev/Dockerfile
+ container_name: "pod_api_dev${VERSION}"
+ volumes:
+ - ../../:/app
+ - pod_media_dev:/app/media
+ ports:
+ - "${EXPOSITION_PORT:-8000}:8000"
+ depends_on:
+ db:
+ condition: service_started
+ env_file:
+ - ../../.env
+ environment:
+ MYSQL_HOST: db
+ MYSQL_PORT: 3306
+ DJANGO_SETTINGS_MODULE: ${DJANGO_SETTINGS_MODULE}
+ ALLOWED_HOSTS: "*"
+ command: ["run-server"]
+
+volumes:
+ pod_db_data_dev:
+ pod_media_dev:
diff --git a/deployment/dev/entrypoint.sh b/deployment/dev/entrypoint.sh
new file mode 100644
index 0000000000..432d63133a
--- /dev/null
+++ b/deployment/dev/entrypoint.sh
@@ -0,0 +1,79 @@
+#!/bin/bash
+set -e
+
+export EXPOSITION_PORT=${EXPOSITION_PORT:-8000}
+export DJANGO_SUPERUSER_USERNAME=${DJANGO_SUPERUSER_USERNAME:-admin}
+export DJANGO_SUPERUSER_EMAIL=${DJANGO_SUPERUSER_EMAIL:-admin@example.com}
+export DJANGO_SUPERUSER_PASSWORD=${DJANGO_SUPERUSER_PASSWORD:-admin}
+
+
+wait_for_db() {
+ echo "[Docker] Checking database availability..."
+
+ python3 << END
+import sys
+import time
+import os
+from django.db import connections
+from django.db.utils import OperationalError
+
+connected = False
+while not connected:
+ try:
+ connections['default'].cursor()
+ connected = True
+ except OperationalError:
+ print("[Docker] DB not ready yet, retrying in 1s...")
+ time.sleep(1)
+
+sys.exit(0)
+END
+ echo "[Docker] Successfully connected to the database."
+}
+
+manage_setup() {
+ echo "[Docker] Starting automatic setup..."
+
+ echo "[Docker] Generating migrations for all apps if necessary..."
+ python manage.py makemigrations --no-input || true
+
+ echo "[Docker] Applying migrations..."
+ python manage.py migrate --noinput
+
+ echo "[Docker] Collecting static files..."
+ python manage.py collectstatic --noinput --clear
+
+ echo "[Docker] Checking superuser..."
+ python manage.py shell << END
+import os
+from django.contrib.auth import get_user_model
+
+User = get_user_model()
+username = os.environ.get('DJANGO_SUPERUSER_USERNAME')
+email = os.environ.get('DJANGO_SUPERUSER_EMAIL')
+password = os.environ.get('DJANGO_SUPERUSER_PASSWORD')
+
+if not username or not password:
+ print(f"[Django] ERROR: Missing environment variables for the superuser.")
+elif not User.objects.filter(username=username).exists():
+ print(f"[Django] Creating superuser: {username}")
+ User.objects.create_superuser(username=username, email=email, password=password)
+else:
+ print(f"[Django] Superuser '{username}' already exists. No action taken.")
+END
+}
+
+wait_for_db
+
+if [ "$1" = "run-server" ]; then
+ manage_setup
+ echo "[Docker] Starting Django server on port $EXPOSITION_PORT..."
+ exec python manage.py runserver 0.0.0.0:"$EXPOSITION_PORT"
+
+elif [ "$1" = "shell-mode" ]; then
+ echo "[Docker] Interactive shell mode."
+ exec /bin/bash
+
+else
+ exec "$@"
+fi
diff --git a/deployment/dev/healthcheck.sh b/deployment/dev/healthcheck.sh
new file mode 100644
index 0000000000..b22fe4cd11
--- /dev/null
+++ b/deployment/dev/healthcheck.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+# Healthcheck for MariaDB
+mysqladmin ping -h 127.0.0.1 -uroot -p"${MYSQL_ROOT_PASSWORD:-root_password}" >/dev/null 2>&1 || exit 1
diff --git a/deployment/dev/init_test_db.sql b/deployment/dev/init_test_db.sql
new file mode 100644
index 0000000000..0d23596477
--- /dev/null
+++ b/deployment/dev/init_test_db.sql
@@ -0,0 +1,11 @@
+-- Create the test database if it doesn't exist
+CREATE DATABASE IF NOT EXISTS test_pod_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
+
+-- Grant all privileges on the test database to the pod user
+GRANT ALL PRIVILEGES ON test_pod_db.* TO 'pod_user'@'%';
+
+-- Grant CREATE and DROP globally so the test runner can create/destroy the test DB if needed
+-- (Though we usually prefer reusing the existing one, Django's test runner might try to create one)
+GRANT CREATE, DROP ON *.* TO 'pod_user'@'%';
+
+FLUSH PRIVILEGES;
diff --git a/deployment/dev/requirements.txt b/deployment/dev/requirements.txt
new file mode 100644
index 0000000000..5264996f28
--- /dev/null
+++ b/deployment/dev/requirements.txt
@@ -0,0 +1,3 @@
+pytest>=7.0.0
+pytest-django>=4.0.0
+pytest-cov>=4.0.0
diff --git a/docs/CI_CD.md b/docs/CI_CD.md
new file mode 100644
index 0000000000..b75854652c
--- /dev/null
+++ b/docs/CI_CD.md
@@ -0,0 +1,50 @@
+# CI/CD Documentation
+
+This document describes the Continuous Integration (CI) and Continuous Deployment (CD) pipelines for the Pod project.
+The pipelines are built using **GitHub Actions** and rely on **Docker** for environment consistency.
+
+## Overview
+
+The CI/CD process is streamlined to use a **Single Source of Truth**: the Docker environment.
+
+### Workflows
+
+#### 1. Continuous Integration (`ci.yml`)
+
+This workflow runs on every `push` and `pull_request`.
+
+**Jobs:**
+* **`quality-check`**: Checks code style using `flake8`.
+* **`test-docker-full`**: The authoritative test suite.
+ * Builds the stack using `make build` and `make start`.
+ * Runs the full Python test suite with `make test` (inside Docker).
+ * Runs E2E scenarios against the running API.
+ * **Coverage Enforced**: The job fails if test coverage is below **60%**.
+
+## Running Tests Locally
+
+To reproduce the CI environment exactly:
+
+### Using Make (Recommended)
+
+Simply run:
+
+```bash
+make test
+```
+
+This will run `pytest` inside the running Docker container, using the dedicated test settings (`config.django.test.docker`).
+
+### Manual Docker Command
+
+If you do not have `make` or want to run the raw command:
+
+```bash
+docker compose -f deployment/dev/docker-compose.yml exec -e DJANGO_SETTINGS_MODULE=config.django.test.docker api pytest --cov=src
+```
+
+### Test Environment Details
+
+* **Database**: Uses a separate `test_pod_db` MySQL database.
+* **Authentication**: explicitely enables `USE_LDAP`, `USE_CAS`, `USE_SHIB`, `USE_OIDC` to verify auth flows.
+* **Settings**: Uses `src/config/django/test/docker.py`.
diff --git a/docs/LLM_HELPERS.md b/docs/LLM_HELPERS.md
new file mode 100644
index 0000000000..034b5fc291
--- /dev/null
+++ b/docs/LLM_HELPERS.md
@@ -0,0 +1,8 @@
+# AI & LLM Integration
+
+This project is configured to work seamlessly with AI coding assistants (like Antigravity, GitHub Copilot, etc.) and Large Language Models.
+
+## 1. Documentation Context (`llms.txt`)
+
+The file [`llms.txt`](../llms.txt) at the root of the project follows the [llmstxt.org](https://llmstxt.org/) specification.
+It serves as a vetted map for LLMs, pointing them to the most relevant documentation files to understand the project architecture, API, and deployment procedures.
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000000..712b01ac2a
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,53 @@
+# Pod V5 Documentation
+
+Welcome to the Pod V5 Project Documentation. This guide is intended for developers, administrators, and contributors.
+
+## Table of Contents
+
+### [Authentication](authentication/README.md)
+Understand and configure security.
+* [Overview](authentication/README.md): Supported methods (Local, CAS, LDAP).
+* [Technical Details](authentication/details.md): Advanced configuration, attribute mapping, and internal workings.
+
+### [API & Swagger](api/README.md)
+Interact with the backend via the REST API.
+* [Swagger Access](api/README.md): Links to interactive documentation.
+* [Developer Guide](api/guide.md): How to document new endpoints.
+
+### [Deployment & CI/CD](deployment/README.md)
+Architecture, production setup, and automation.
+* [Deployment Overview](deployment/README.md): System architecture.
+* [Development Guide](deployment/dev/dev.md): How to setup local environment (Docker/Make).
+* [CI/CD Pipelines](CI_CD.md): Understanding the GitHub Actions workflows.
+
+### [AI & LLM Helpers](LLM_HELPERS.md)
+Tools and configurations for AI agents.
+* [Overview](LLM_HELPERS.md): `llms.txt` documentation context.
+
+### [Configuration](configuration.md)
+* [Environment Variables](configuration.md): Complete list of .env variables.
+* [Customization](configuration.md#3-how-to-customize-settings): How to add settings or apps.
+
+## Project Structure
+
+```bash
+Pod_V5/
+├── src/
+│ ├── apps/ # Django Apps (Business Logic)
+│ └── config/ # Configuration & Settings
+│ ├── django/ # Django Settings (Base, Dev, Test, Prod)
+│ └── settings/ # Feature-specific settings (Auth, API, etc.)
+├── deployment/ # Docker Configuration
+├── docs/ # Documentation (You are here)
+└── manage.py # Django CLI
+```
+
+## Configuration Hierarchy
+
+The project uses a **Environment Variable Driven** configuration:
+
+1. **Docker / System**: Environment variables are set in `.env` (or CI secrets).
+2. **`src/config/env.py`**: Loads variables using `django-environ`.
+3. **`src/config/django/*.py`**: Settings files consume these variables.
+ * **Features Flags**: `USE_LDAP`, `USE_CAS`, etc. are toggled via env vars.
+ * **No `settings_local.py`**: We do not use local python override files. Use `.env` for everything.
diff --git a/docs/api-docs.yaml b/docs/api-docs.yaml
new file mode 100644
index 0000000000..fe4b3363c6
--- /dev/null
+++ b/docs/api-docs.yaml
@@ -0,0 +1,1519 @@
+openapi: 3.0.3
+info:
+ title: Pod REST API
+ version: 5.0.0-DEV
+ description: Video management API (Local Authentication)
+paths:
+ /api/auth/access-groups/:
+ get:
+ operationId: auth_access_groups_list
+ description: |-
+ ViewSet for managing Access Groups.
+ Includes actions to add/remove users by code name.
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/AccessGroup'
+ description: ''
+ post:
+ operationId: auth_access_groups_create
+ description: |-
+ ViewSet for managing Access Groups.
+ Includes actions to add/remove users by code name.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '201':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroup'
+ description: ''
+ /api/auth/access-groups/{id}/:
+ get:
+ operationId: auth_access_groups_retrieve
+ description: |-
+ ViewSet for managing Access Groups.
+ Includes actions to add/remove users by code name.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this Access Group.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroup'
+ description: ''
+ put:
+ operationId: auth_access_groups_update
+ description: |-
+ ViewSet for managing Access Groups.
+ Includes actions to add/remove users by code name.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this Access Group.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroup'
+ description: ''
+ patch:
+ operationId: auth_access_groups_partial_update
+ description: |-
+ ViewSet for managing Access Groups.
+ Includes actions to add/remove users by code name.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this Access Group.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PatchedAccessGroupRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/PatchedAccessGroupRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/PatchedAccessGroupRequest'
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroup'
+ description: ''
+ delete:
+ operationId: auth_access_groups_destroy
+ description: |-
+ ViewSet for managing Access Groups.
+ Includes actions to add/remove users by code name.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this Access Group.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '204':
+ description: No response body
+ /api/auth/access-groups/remove-users-by-name/:
+ post:
+ operationId: auth_access_groups_remove_users_by_name_create
+ description: |-
+ Equivalent of accessgroups_remove_users_by_name.
+ Removes a list of users (by username) from an AccessGroup (by code_name).
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroup'
+ description: ''
+ /api/auth/access-groups/set-users-by-name/:
+ post:
+ operationId: auth_access_groups_set_users_by_name_create
+ description: |-
+ Equivalent of accessgroups_set_users_by_name.
+ Adds a list of users (by username) to an AccessGroup (by code_name).
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/AccessGroupRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AccessGroup'
+ description: ''
+ /api/auth/groups/:
+ get:
+ operationId: auth_groups_list
+ description: ViewSet for managing Django Groups (Permissions).
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Group'
+ description: ''
+ post:
+ operationId: auth_groups_create
+ description: ViewSet for managing Django Groups (Permissions).
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GroupRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/GroupRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/GroupRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '201':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Group'
+ description: ''
+ /api/auth/groups/{id}/:
+ get:
+ operationId: auth_groups_retrieve
+ description: ViewSet for managing Django Groups (Permissions).
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this group.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Group'
+ description: ''
+ put:
+ operationId: auth_groups_update
+ description: ViewSet for managing Django Groups (Permissions).
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this group.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/GroupRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/GroupRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/GroupRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Group'
+ description: ''
+ patch:
+ operationId: auth_groups_partial_update
+ description: ViewSet for managing Django Groups (Permissions).
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this group.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PatchedGroupRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/PatchedGroupRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/PatchedGroupRequest'
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Group'
+ description: ''
+ delete:
+ operationId: auth_groups_destroy
+ description: ViewSet for managing Django Groups (Permissions).
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this group.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '204':
+ description: No response body
+ /api/auth/config/:
+ get:
+ operationId: auth_login_config_retrieve
+ description: |-
+ Returns the configuration of active authentication methods.
+ Allows the frontend to know which login buttons to display.
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ - {}
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LoginConfigResponse'
+ description: ''
+ /api/auth/logout-info/:
+ get:
+ operationId: auth_logout_info_retrieve
+ description: |-
+ Returns the logout URLs for external providers.
+ The frontend must call this endpoint to know where
+ to redirect the user after deleting the local JWT token.
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ - {}
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LogoutInfoResponse'
+ description: ''
+ /api/auth/owners/:
+ get:
+ operationId: auth_owners_list
+ description: |-
+ ViewSet for managing Owner profiles.
+ Includes actions to manage access groups for a user.
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Owner'
+ description: ''
+ post:
+ operationId: auth_owners_create
+ description: |-
+ ViewSet for managing Owner profiles.
+ Includes actions to manage access groups for a user.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '201':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Owner'
+ description: ''
+ /api/auth/owners/{id}/:
+ get:
+ operationId: auth_owners_retrieve
+ description: |-
+ ViewSet for managing Owner profiles.
+ Includes actions to manage access groups for a user.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this Owner.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Owner'
+ description: ''
+ put:
+ operationId: auth_owners_update
+ description: |-
+ ViewSet for managing Owner profiles.
+ Includes actions to manage access groups for a user.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this Owner.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Owner'
+ description: ''
+ patch:
+ operationId: auth_owners_partial_update
+ description: |-
+ ViewSet for managing Owner profiles.
+ Includes actions to manage access groups for a user.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this Owner.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PatchedOwnerRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/PatchedOwnerRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/PatchedOwnerRequest'
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Owner'
+ description: ''
+ delete:
+ operationId: auth_owners_destroy
+ description: |-
+ ViewSet for managing Owner profiles.
+ Includes actions to manage access groups for a user.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this Owner.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '204':
+ description: No response body
+ /api/auth/owners/remove-user-accessgroup/:
+ post:
+ operationId: auth_owners_remove_user_accessgroup_create
+ description: |-
+ Equivalent of accessgroups_remove_user_accessgroup.
+ Removes AccessGroups from a user via their username.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Owner'
+ description: ''
+ /api/auth/owners/set-user-accessgroup/:
+ post:
+ operationId: auth_owners_set_user_accessgroup_create
+ description: |-
+ Equivalent of accessgroups_set_user_accessgroup.
+ Assigns AccessGroups to a user via their username.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/OwnerRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Owner'
+ description: ''
+ /api/auth/sites/:
+ get:
+ operationId: auth_sites_list
+ description: ViewSet for managing Sites.
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/Site'
+ description: ''
+ post:
+ operationId: auth_sites_create
+ description: ViewSet for managing Sites.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SiteRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/SiteRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/SiteRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '201':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Site'
+ description: ''
+ /api/auth/sites/{id}/:
+ get:
+ operationId: auth_sites_retrieve
+ description: ViewSet for managing Sites.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this site.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Site'
+ description: ''
+ put:
+ operationId: auth_sites_update
+ description: ViewSet for managing Sites.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this site.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SiteRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/SiteRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/SiteRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Site'
+ description: ''
+ patch:
+ operationId: auth_sites_partial_update
+ description: ViewSet for managing Sites.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this site.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PatchedSiteRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/PatchedSiteRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/PatchedSiteRequest'
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Site'
+ description: ''
+ delete:
+ operationId: auth_sites_destroy
+ description: ViewSet for managing Sites.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this site.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '204':
+ description: No response body
+ /api/auth/token/:
+ post:
+ operationId: auth_token_create
+ description: |-
+ **Authentication Endpoint**
+ Accepts a username and password and returns a pair of JWT tokens.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CustomTokenObtainPairRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/CustomTokenObtainPairRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/CustomTokenObtainPairRequest'
+ required: true
+ responses:
+ '200':
+ description: No response body
+ /api/auth/token/refresh/:
+ post:
+ operationId: auth_token_refresh_create
+ description: |-
+ Takes a refresh type JSON web token and returns an access type JSON web
+ token if the refresh token is valid.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TokenRefreshRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/TokenRefreshRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/TokenRefreshRequest'
+ required: true
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TokenRefresh'
+ description: ''
+ /api/auth/token/verify/:
+ post:
+ operationId: auth_token_verify_create
+ description: |-
+ Takes a token and indicates if it is valid. This view provides no
+ information about a token's fitness for a particular use.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TokenVerifyRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/TokenVerifyRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/TokenVerifyRequest'
+ required: true
+ responses:
+ '200':
+ description: No response body
+ /api/auth/users/:
+ get:
+ operationId: auth_users_list
+ description: ViewSet for managing standard Django Users.
+ parameters:
+ - name: search
+ required: false
+ in: query
+ description: A search term.
+ schema:
+ type: string
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/User'
+ description: ''
+ post:
+ operationId: auth_users_create
+ description: ViewSet for managing standard Django Users.
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UserRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/UserRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/UserRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '201':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ description: ''
+ /api/auth/users/{id}/:
+ get:
+ operationId: auth_users_retrieve
+ description: ViewSet for managing standard Django Users.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this user.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ description: ''
+ put:
+ operationId: auth_users_update
+ description: ViewSet for managing standard Django Users.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this user.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UserRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/UserRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/UserRequest'
+ required: true
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ description: ''
+ patch:
+ operationId: auth_users_partial_update
+ description: ViewSet for managing standard Django Users.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this user.
+ required: true
+ tags:
+ - auth
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PatchedUserRequest'
+ application/x-www-form-urlencoded:
+ schema:
+ $ref: '#/components/schemas/PatchedUserRequest'
+ multipart/form-data:
+ schema:
+ $ref: '#/components/schemas/PatchedUserRequest'
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ description: ''
+ delete:
+ operationId: auth_users_destroy
+ description: ViewSet for managing standard Django Users.
+ parameters:
+ - in: path
+ name: id
+ schema:
+ type: integer
+ description: A unique integer value identifying this user.
+ required: true
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '204':
+ description: No response body
+ /api/auth/users/me/:
+ get:
+ operationId: auth_users_me_retrieve
+ description: |-
+ **Current User Profile**
+ Returns the profile information of the currently authenticated user.
+ tags:
+ - auth
+ security:
+ - jwtAuth: []
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/User'
+ description: ''
+ /api/info/:
+ get:
+ operationId: info_retrieve
+ description: Returns the project name and current version
+ summary: System Information
+ tags:
+ - info
+ security:
+ - jwtAuth: []
+ - {}
+ responses:
+ '200':
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ project:
+ type: string
+ example: POD V5
+ version:
+ type: string
+ example: 5.0.0
+ description: ''
+components:
+ schemas:
+ AccessGroup:
+ type: object
+ properties:
+ id:
+ type: integer
+ readOnly: true
+ display_name:
+ type: string
+ description: Readable name of the group.
+ maxLength: 128
+ code_name:
+ type: string
+ description: Unique identifier code (e.g., LDAP group name).
+ maxLength: 250
+ sites:
+ type: array
+ items:
+ type: integer
+ description: Sites accessible by this group.
+ users:
+ type: array
+ items:
+ type: integer
+ readOnly: true
+ auto_sync:
+ type: boolean
+ title: Auto synchronize
+ description: If True, this group is automatically managed via external auth
+ (CAS/LDAP).
+ required:
+ - code_name
+ - id
+ - sites
+ - users
+ AccessGroupRequest:
+ type: object
+ properties:
+ display_name:
+ type: string
+ description: Readable name of the group.
+ maxLength: 128
+ code_name:
+ type: string
+ minLength: 1
+ description: Unique identifier code (e.g., LDAP group name).
+ maxLength: 250
+ sites:
+ type: array
+ items:
+ type: integer
+ description: Sites accessible by this group.
+ auto_sync:
+ type: boolean
+ title: Auto synchronize
+ description: If True, this group is automatically managed via external auth
+ (CAS/LDAP).
+ required:
+ - code_name
+ - sites
+ AffiliationEnum:
+ enum:
+ - student
+ - faculty
+ - staff
+ - employee
+ - member
+ - affiliate
+ - alum
+ - library-walk-in
+ - researcher
+ - retired
+ - emeritus
+ - teacher
+ - registered-reader
+ type: string
+ description: |-
+ * `student` - student
+ * `faculty` - faculty
+ * `staff` - staff
+ * `employee` - employee
+ * `member` - member
+ * `affiliate` - affiliate
+ * `alum` - alum
+ * `library-walk-in` - library-walk-in
+ * `researcher` - researcher
+ * `retired` - retired
+ * `emeritus` - emeritus
+ * `teacher` - teacher
+ * `registered-reader` - registered-reader
+ AuthTypeEnum:
+ enum:
+ - local
+ - CAS
+ - OIDC
+ - Shibboleth
+ type: string
+ description: |-
+ * `local` - local
+ * `CAS` - CAS
+ * `OIDC` - OIDC
+ * `Shibboleth` - Shibboleth
+ CustomTokenObtainPairRequest:
+ type: object
+ description: |-
+ Custom JWT Token Serializer.
+
+ Extends the default SimpleJWT serializer to include custom claims
+ in the encrypted token payload (username, staff status, affiliation).
+ properties:
+ username:
+ type: string
+ writeOnly: true
+ minLength: 1
+ password:
+ type: string
+ writeOnly: true
+ minLength: 1
+ required:
+ - password
+ - username
+ Group:
+ type: object
+ properties:
+ id:
+ type: integer
+ readOnly: true
+ name:
+ type: string
+ maxLength: 150
+ required:
+ - id
+ - name
+ GroupRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 150
+ required:
+ - name
+ LoginConfigResponse:
+ type: object
+ properties:
+ use_local:
+ type: boolean
+ use_cas:
+ type: boolean
+ use_shibboleth:
+ type: boolean
+ use_oidc:
+ type: boolean
+ shibboleth_name:
+ type: string
+ oidc_name:
+ type: string
+ required:
+ - oidc_name
+ - shibboleth_name
+ - use_cas
+ - use_local
+ - use_oidc
+ - use_shibboleth
+ LogoutInfoResponse:
+ type: object
+ properties:
+ local:
+ type: string
+ nullable: true
+ cas:
+ type: string
+ nullable: true
+ shibboleth:
+ type: string
+ nullable: true
+ oidc:
+ type: string
+ nullable: true
+ required:
+ - cas
+ - local
+ - oidc
+ - shibboleth
+ Owner:
+ type: object
+ properties:
+ id:
+ type: integer
+ readOnly: true
+ user:
+ type: integer
+ auth_type:
+ allOf:
+ - $ref: '#/components/schemas/AuthTypeEnum'
+ title: Authentication Type
+ affiliation:
+ $ref: '#/components/schemas/AffiliationEnum'
+ commentaire:
+ type: string
+ title: Comment
+ hashkey:
+ type: string
+ description: Unique hash generated from username and secret key.
+ maxLength: 64
+ userpicture:
+ type: integer
+ nullable: true
+ title: Picture
+ sites:
+ type: array
+ items:
+ type: integer
+ required:
+ - id
+ - sites
+ - user
+ OwnerRequest:
+ type: object
+ properties:
+ user:
+ type: integer
+ auth_type:
+ allOf:
+ - $ref: '#/components/schemas/AuthTypeEnum'
+ title: Authentication Type
+ affiliation:
+ $ref: '#/components/schemas/AffiliationEnum'
+ commentaire:
+ type: string
+ title: Comment
+ hashkey:
+ type: string
+ description: Unique hash generated from username and secret key.
+ maxLength: 64
+ userpicture:
+ type: integer
+ nullable: true
+ title: Picture
+ sites:
+ type: array
+ items:
+ type: integer
+ required:
+ - sites
+ - user
+ PatchedAccessGroupRequest:
+ type: object
+ properties:
+ display_name:
+ type: string
+ description: Readable name of the group.
+ maxLength: 128
+ code_name:
+ type: string
+ minLength: 1
+ description: Unique identifier code (e.g., LDAP group name).
+ maxLength: 250
+ sites:
+ type: array
+ items:
+ type: integer
+ description: Sites accessible by this group.
+ auto_sync:
+ type: boolean
+ title: Auto synchronize
+ description: If True, this group is automatically managed via external auth
+ (CAS/LDAP).
+ PatchedGroupRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 150
+ PatchedOwnerRequest:
+ type: object
+ properties:
+ user:
+ type: integer
+ auth_type:
+ allOf:
+ - $ref: '#/components/schemas/AuthTypeEnum'
+ title: Authentication Type
+ affiliation:
+ $ref: '#/components/schemas/AffiliationEnum'
+ commentaire:
+ type: string
+ title: Comment
+ hashkey:
+ type: string
+ description: Unique hash generated from username and secret key.
+ maxLength: 64
+ userpicture:
+ type: integer
+ nullable: true
+ title: Picture
+ sites:
+ type: array
+ items:
+ type: integer
+ PatchedSiteRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ minLength: 1
+ title: Display name
+ maxLength: 50
+ domain:
+ type: string
+ minLength: 1
+ title: Domain name
+ maxLength: 100
+ PatchedUserRequest:
+ type: object
+ description: Serializer for the User model, enriched with Owner profile data.
+ properties:
+ username:
+ type: string
+ minLength: 1
+ description: Required. 150 characters or fewer. Letters, digits and @/./+/-/_
+ only.
+ pattern: ^[\w.@+-]+$
+ maxLength: 150
+ email:
+ type: string
+ format: email
+ title: Email address
+ maxLength: 254
+ first_name:
+ type: string
+ maxLength: 150
+ last_name:
+ type: string
+ maxLength: 150
+ is_staff:
+ type: boolean
+ title: Staff status
+ description: Designates whether the user can log into this admin site.
+ Site:
+ type: object
+ properties:
+ id:
+ type: integer
+ readOnly: true
+ name:
+ type: string
+ title: Display name
+ maxLength: 50
+ domain:
+ type: string
+ title: Domain name
+ maxLength: 100
+ required:
+ - domain
+ - id
+ - name
+ SiteRequest:
+ type: object
+ properties:
+ name:
+ type: string
+ minLength: 1
+ title: Display name
+ maxLength: 50
+ domain:
+ type: string
+ minLength: 1
+ title: Domain name
+ maxLength: 100
+ required:
+ - domain
+ - name
+ TokenRefresh:
+ type: object
+ properties:
+ access:
+ type: string
+ readOnly: true
+ required:
+ - access
+ TokenRefreshRequest:
+ type: object
+ properties:
+ refresh:
+ type: string
+ writeOnly: true
+ minLength: 1
+ required:
+ - refresh
+ TokenVerifyRequest:
+ type: object
+ properties:
+ token:
+ type: string
+ writeOnly: true
+ minLength: 1
+ required:
+ - token
+ User:
+ type: object
+ description: Serializer for the User model, enriched with Owner profile data.
+ properties:
+ id:
+ type: integer
+ readOnly: true
+ username:
+ type: string
+ description: Required. 150 characters or fewer. Letters, digits and @/./+/-/_
+ only.
+ pattern: ^[\w.@+-]+$
+ maxLength: 150
+ email:
+ type: string
+ format: email
+ title: Email address
+ maxLength: 254
+ first_name:
+ type: string
+ maxLength: 150
+ last_name:
+ type: string
+ maxLength: 150
+ is_staff:
+ type: boolean
+ title: Staff status
+ description: Designates whether the user can log into this admin site.
+ affiliation:
+ type: string
+ nullable: true
+ readOnly: true
+ establishment:
+ type: string
+ nullable: true
+ readOnly: true
+ userpicture:
+ type: string
+ nullable: true
+ readOnly: true
+ required:
+ - affiliation
+ - establishment
+ - id
+ - username
+ - userpicture
+ UserRequest:
+ type: object
+ description: Serializer for the User model, enriched with Owner profile data.
+ properties:
+ username:
+ type: string
+ minLength: 1
+ description: Required. 150 characters or fewer. Letters, digits and @/./+/-/_
+ only.
+ pattern: ^[\w.@+-]+$
+ maxLength: 150
+ email:
+ type: string
+ format: email
+ title: Email address
+ maxLength: 254
+ first_name:
+ type: string
+ maxLength: 150
+ last_name:
+ type: string
+ maxLength: 150
+ is_staff:
+ type: boolean
+ title: Staff status
+ description: Designates whether the user can log into this admin site.
+ required:
+ - username
+ securitySchemes:
+ jwtAuth:
+ type: http
+ scheme: bearer
+ bearerFormat: JWT
diff --git a/docs/api/README.md b/docs/api/README.md
new file mode 100644
index 0000000000..b0ebaf7154
--- /dev/null
+++ b/docs/api/README.md
@@ -0,0 +1,21 @@
+# 🛠 API & Swagger
+
+The Pod V5 API is automatically documented according to the **OpenAPI 3.0** specification using the `drf-spectacular` library.
+
+## Interactive Documentation
+
+We provide two interfaces to explore the API:
+
+* **[Swagger UI](http://localhost:8000/api/docs/)** (`/api/docs/`): Intended for developers. Allows you to test requests (GET, POST, etc.) directly from the browser.
+* **[ReDoc](http://localhost:8000/api/redoc/)** (`/api/redoc/`): Intended for reading. A modern and clean interface listing all endpoints hierarchically.
+
+## Raw Schema
+
+For automation needs (API client generation, etc.), the raw schema is available:
+* YAML format: `/api/schema/`
+* JSON format: `/api/schema/?format=json`
+
+## Further Reading
+
+* ➡️ **[Technical Details & Configuration](guide.md)**: How to document your code so it appears in Swagger.
+* ⬅️ **[Back to Index](../README.md)**
diff --git a/docs/api/guide.md b/docs/api/guide.md
new file mode 100644
index 0000000000..136580caba
--- /dev/null
+++ b/docs/api/guide.md
@@ -0,0 +1,45 @@
+# 👨API Developer Guide
+
+How to document your code so it appears in Swagger.
+
+## Principle
+Documentation lives in the code. By using `drf-spectacular` decorators, you keep the documentation synchronized with the implementation.
+
+## Documenting a View
+
+Use the `@extend_schema` decorator.
+
+### 1. Grouping Endpoints (Tags)
+
+Add this above the ViewSet class to group its methods.
+
+```python
+from drf_spectacular.utils import extend_schema
+
+@extend_schema(tags=['Video Management']) # Creates a "Video Management" group
+class VideoViewSet(viewsets.ModelViewSet):
+ ...
+```
+
+### 2. Detailing a Method
+
+Add this to the specific method (create, list, etc.).
+
+```python
+@extend_schema(
+ summary="Create a video",
+ description="Uploads a video file and creates the associated metadata entry.",
+ responses={
+ 201: VideoSerializer, # Success
+ 400: OpenApiTypes.OBJECT, # Validation error
+ },
+ examples=[
+ OpenApiExample(
+ 'Valid Example',
+ value={'title': 'My Holiday Video'}
+ )
+ ]
+)
+def create(self, request):
+ ...
+```
diff --git a/docs/authentication/README.md b/docs/authentication/README.md
new file mode 100644
index 0000000000..32d6c59840
--- /dev/null
+++ b/docs/authentication/README.md
@@ -0,0 +1,28 @@
+# Authentication: Overview
+
+The Pod application authentication module secures access to the API and manages users. It is designed to work in a hybrid mode, accepting both local logins and those from external Identity Providers (SSO).
+
+## Supported Methods
+
+The choice of authentication method is configured via the project settings (`settings.py`).
+
+| Method | Type | Description |
+| :--- | :--- | :--- |
+| **Local** | Internal | Uses the standard Django database. Ideal for superusers and development. |
+| **CAS** | External | **Central Authentication Service**. Commonly used in universities (e.g., University of Lille). |
+| **LDAP** | Directory | Direct connection to an LDAP directory to retrieve user attributes. |
+| **Shibboleth** | Federation | Authentication based on HTTP headers (REMOTE_USER), managed by the web server (Apache/Nginx). |
+| **OIDC** | Federation | **OpenID Connect**. The modern standard for delegated authentication. |
+
+## How it Works
+
+Regardless of the method used to log in, the backend always eventually:
+
+1. **Validates** credentials with the source (Local DB, CAS, LDAP...).
+2. **Synchronizes** user information (First Name, Last Name, Affiliation) in the local `Owner` table.
+3. **Issues** a pair of **JWT** tokens (Access + Refresh) that the frontend will use for its requests.
+
+## Further Reading
+
+* ➡️ **[Technical Details & Configuration](details.md)**: Environment variables, detailed flows, and attribute mapping.
+* ⬅️ **[Back to Index](../README.md)**
diff --git a/docs/authentication/details.md b/docs/authentication/details.md
new file mode 100644
index 0000000000..bf2d373a7b
--- /dev/null
+++ b/docs/authentication/details.md
@@ -0,0 +1,68 @@
+# ⚙️ Authentication: Technical Details
+
+This document details the configuration and internal workings of the authentication system.
+
+## 1. Authentication Flows
+
+### A. CAS (SSO)
+
+1. The Frontend redirects the user to the CAS server (e.g., `https://cas.univ-lille.fr`).
+2. Once authenticated, the user returns with a `ticket`.
+3. The Frontend sends this ticket to the Backend via **POST** `/api/auth/token/cas/`.
+4. The Backend validates the ticket, retrieves attributes (and optionally completes via LDAP), updates the local user, and returns a JWT.
+
+### B. Local
+
+1. The Frontend sends `username` and `password` via **POST** `/api/auth/token/`.
+2. Django verifies the password hash.
+3. If valid, a JWT is returned.
+
+## 2. Configuration (`settings.py`)
+
+The following variables in `src/config/settings/authentication.py` control behavior:
+
+### Module Activation
+* `USE_CAS = True/False`
+* `USE_LDAP = True/False`
+* `USE_SHIB = True/False`
+* `USE_OIDC = True/False`
+* `USE_LOCAL_AUTH = True` (Default)
+
+### CAS Configuration
+* `CAS_SERVER_URL`: Server URL (e.g., `https://cas.univ-lille.fr`)
+* `CAS_VERSION`: Protocol version (e.g., `'3'`)
+* `CAS_APPLY_ATTRIBUTES_TO_USER`: If `True`, updates local data with data from CAS.
+
+### LDAP Configuration
+Used if `USE_LDAP = True`.
+* `LDAP_SERVER`: Dictionary containing `url` (e.g., `ldap://ldap.univ.fr`) and `port`.
+* `AUTH_LDAP_BIND_DN`: Connection user (Bind DN).
+* `USER_LDAP_MAPPING_ATTRIBUTES`: Maps LDAP fields to Django.
+ * `uid` -> `username`
+ * `mail` -> `email`
+ * `sn` -> `last_name`
+ * `givenname` -> `first_name`
+ * `eduPersonPrimaryAffiliation` -> `affiliation`
+
+### JWT Configuration (`SIMPLE_JWT`)
+* `ACCESS_TOKEN_LIFETIME`: **60 minutes**.
+* `REFRESH_TOKEN_LIFETIME`: **1 day**.
+
+## 3. Models & Services
+
+### UserPopulator
+This is the central service (`src.apps.authentication.services`). It is responsible for:
+* Creating or updating the `User` and their `Owner` profile.
+* Synchronizing **AccessGroups** based on affiliations or LDAP groups (`memberOf`).
+* Determining Staff status (`is_staff`) if the user belongs to a privileged affiliation (`faculty`, `employee`, `staff`).
+
+## 4. API Endpoints
+
+| Method | Endpoint | Description |
+| :--- | :--- | :--- |
+| **POST** | `/api/auth/token/` | Local login (username/password). |
+| **POST** | `/api/auth/token/refresh/` | Refresh expired token. |
+| **POST** | `/api/auth/token/cas/` | CAS ticket exchange. |
+| **GET** | `/api/auth/token/shibboleth/` | Auth via headers (REMOTE_USER). |
+| **POST** | `/api/auth/token/oidc/` | OpenID Connect auth (Code exchange). |
+| **GET** | `/api/auth/users/me/` | Connected user info. |
diff --git a/docs/configuration.md b/docs/configuration.md
new file mode 100644
index 0000000000..4686f3efc5
--- /dev/null
+++ b/docs/configuration.md
@@ -0,0 +1,110 @@
+# Configuration Guide
+
+This guide describes how to configure **Esup-Pod V5**.
+The project adheres to the [Twelve-Factor App](https://12factor.net/config) methodology, storing configuration in the **environment**.
+
+## Configuration Hierarchy
+
+1. **Environment Variables (`.env`)**: The source of truth.
+2. **`src/config/env.py`**: Loads the `.env` file using the `django-environ` library.
+3. **Django Settings (`src/config/django/`)**:
+ * `base.py`: Core settings shared by all environments.
+ * `dev/docker.py`: Development overrides (consumes `.env` defaults).
+ * `test/docker.py`: Test-specific overrides (forces feature flags).
+
+---
+
+## 2. Environment Variables Reference
+
+Create a `.env` file in the project root to set these variables.
+
+### Core Settings
+
+| Variable | Required | Default | Description |
+| :--- | :---: | :--- | :--- |
+| **`DJANGO_SETTINGS_MODULE`** | ✅ | `config.django.base` | Python path to settings module. (e.g. `config.django.dev.docker`) |
+| **`SECRET_KEY`** | ✅ | *(None)* | Django security key. **Must be secret in production.** |
+| **`VERSION`** | ❌ | `5.0.0-DEV` | Application version tag. |
+| **`EXPOSITION_PORT`** | ❌ | `8000` | Port exposed by Docker to the host. |
+
+### Database (MySQL/MariaDB)
+
+| Variable | Required | Default | Description |
+| :--- | :---: | :--- | :--- |
+| **`MYSQL_DATABASE`** | ❌ | `pod_db` | Database name. |
+| **`MYSQL_USER`** | ❌ | `pod` | Database user. |
+| **`MYSQL_PASSWORD`** | ❌ | `pod` | Database password. |
+| **`MYSQL_ROOT_PASSWORD`** | ❌ | *(None)* | Root password for DB container initialization. |
+| **`MYSQL_HOST`** | ❌ | `db` | Hostname of the DB service (Docker service name). |
+| **`MYSQL_PORT`** | ❌ | `3306` | Port of the DB service. |
+
+### Authentication Feature Flags
+Modules can be enabled/disabled without changing code.
+
+| Variable | Default | Description |
+| :--- | :--- | :--- |
+| **`USE_LOCAL_AUTH`** | `True` | Enable standard Django Database authentication. |
+| **`USE_LDAP`** | `False` | Enable LDAP authentication backend. |
+| **`USE_CAS`** | `False` | Enable CAS authentication backend. |
+| **`USE_SHIB`** | `False` | Enable Shibboleth authentication. |
+| **`USE_OIDC`** | `False` | Enable OpenID Connect authentication. |
+
+### CAS Configuration (If enabled)
+| Variable | Default | Description |
+| :--- | :--- | :--- |
+| **`CAS_SERVER_URL`** | `https://cas.univ-lille.fr` | URL of your CAS server. |
+| **`CAS_VERSION`** | `3` | CAS protocol version. |
+
+### LDAP Configuration (If enabled)
+| Variable | Default | Description |
+| :--- | :--- | :--- |
+| **`LDAP_SERVER_URL`** | `ldap://ldap.univ.fr` | LDAP server URL. |
+| **`LDAP_SERVER_PORT`** | `389` | LDAP server port. |
+| **`LDAP_SERVER_USE_SSL`** | `False` | Use SSL for LDAP connection. |
+| **`AUTH_LDAP_BIND_PASSWORD`** | *(None)* | Password for the Bind DN user. |
+
+---
+
+## 3. Configuration Scenarios
+
+### Scenario: University Instance (CAS Only)
+To configure Pod for a University where users only log in via CAS and local accounts are disabled:
+1. **Modify `.env`**:
+ ```bash
+ USE_LOCAL_AUTH=False
+ USE_CAS=True
+ CAS_SERVER_URL=https://cas.votre-univ.fr
+ ```
+2. **Restart**: `make start`
+
+### Scenario: Local Development (Default)
+1. **Modify `.env`**:
+ ```bash
+ USE_LOCAL_AUTH=True
+ USE_CAS=False
+ USE_LDAP=False
+ ```
+2. **Restart**: `make start`
+
+---
+
+## 4. How to Customize Settings
+
+### Adding a new setting
+1. Define the variable in your `.env` file.
+2. Read it in the appropriate settings file using `env()`:
+
+ ```python
+ from config.env import env
+
+ MY_CUSTOM_SETTING = env("MY_CUSTOM_SETTING", default="default_value")
+ ```
+
+### Overriding for Local Development
+Do **not** create a `settings_local.py`. Instead:
+1. Add the override to your `.env` file.
+2. Restart the container (`make start`).
+
+### Adding a new App
+1. Create the app in `src/apps/`.
+2. Add it to `INSTALLED_APPS` in `src/config/django/base.py`.
diff --git a/docs/deployment/README.md b/docs/deployment/README.md
new file mode 100644
index 0000000000..bfa80e2fe3
--- /dev/null
+++ b/docs/deployment/README.md
@@ -0,0 +1,66 @@
+# Project Overview & Architecture
+
+## Introduction
+
+This documentation outlines the architecture, development workflow, and production deployment strategies for the Pod_V5_Back Django API. The project is designed for scalability and maintainability, utilizing Docker for containerization and a split-settings approach for environment management.
+
+## System Architecture
+
+The application is built on a robust stack designed to ensure separation of concerns between the development and production environments.
+
+* **Backend Framework:** Django with Django Rest Framework (DRF).
+* **Database:** MySql (Containerized).
+ * **Local Dev (Lite):** SQLite (Auto-configured if no MySQL config found).
+* **Containerization:** Docker & Docker Compose.
+
+## Directory Structure
+
+The project follows a modular structure to separate configuration, source code, and deployment logic:
+
+```
+Pod_V5_Back/
+├── deployment/ # Docker configurations
+│ ├── dev/ # Development specific Docker setup
+│ └── prod/ # Production specific Docker setup
+├── src/ # Application Source Code
+│ ├── apps/ # Domain-specific Django apps
+│ └── config/ # Project configuration (settings, urls, wsgi)
+│ └── settings/ # Split settings (base.py, dev.py)
+├── docs/ # Documentation
+├── manage.py # Django entry point
+├── Makefile # Command shortcuts
+└── requirements.txt # Python dependencies
+```
+
+## Environment Strategy
+
+To ensure stability, the project maintains strict isolation between environments:
+
+| Feature | Development (Docker) | Development (Local) | Production |
+|-----------------|-------------------------------------------|-------------------------------|---------------------------------------------|
+| Docker Compose | deployment/dev/docker-compose.yml | N/A | deployment/prod/docker-compose.yml |
+| Settings File | src.config.settings.dev | src.config.settings.dev | src.config.settings.prod (ou base + env) |
+| Database | MariaDB (Service: db) | SQLite (db.sqlite3) | TODO |
+| Debug Mode | True | True | TODO |
+| Web Server | runserver | runserver | TODO |
+
+
+### Environment Selection
+
+Make sure to **choose the correct `.env` file** depending on how you run the project:
+
+* **Using Docker → use the Docker `.env.docker` file** (MariaDB, container services)
+* **Using local setup → use the local `.env.local` file** (SQLite and local-only defaults)
+
+Selecting the wrong `.env` will load the wrong database configuration and cause the application to fail.
+
+
+
+## Getting Started
+
+* ➡️ **[Development Guide](dev/dev.md)**: Local setup instructions and development environment.
+* ➡️ **[Production Guide (WIP)](prod/notes.md)**: Current notes on production deployment.
+* ➡️ **[Help](help.md)**: Maintenance, troubleshooting, and operational support.
+
+* ⬅️ **[Back to Index](../README.md)**
+
diff --git a/docs/deployment/dev/dev.md b/docs/deployment/dev/dev.md
new file mode 100644
index 0000000000..76ddbc9f61
--- /dev/null
+++ b/docs/deployment/dev/dev.md
@@ -0,0 +1,100 @@
+# Development Environment & Workflow
+
+## Introduction
+
+This guide describes how to set up the development environment for contributing to **Esup-Pod V5**.
+We use **Docker** to replicate production services while providing a flexible debugging setup, managed via a **Makefile** for convenience.
+
+## 1. Prerequisites (Choose your OS)
+
+### 🐧 Linux & macOS
+* **Docker** & **Docker Compose** installed.
+* **Make** installed (`sudo apt install make` on Linux or XCode Command Line Tools on macOS).
+
+### 🪟 Windows
+* Install **Docker Desktop**.
+* (Recommended) Enable **WSL2** backend for Docker.
+* Install **Chocolatey** (required to use `choco`): https://chocolatey.org/install
+* Install **Make**:
+ ```powershell
+ choco install make
+ ```
+* **Note**: Run commands from PowerShell or Git Bash.
+
+---
+
+## 2. Quick Start
+
+If you are familiar with Docker:
+
+```bash
+git clone
+cd Pod_V5_Back
+
+cp .env.docker .env # Copy template
+make start # Start project
+make logs # Watch logs
+```
+
+The app will be available at `http://localhost:8000`.
+
+---
+
+## 3. Development Guide
+
+### Configuration (.env)
+
+The project uses environment variables for configuration.
+Copy the included template and customize it if necessary:
+
+```bash
+cp .env.docker .env
+```
+
+**Key Variables in `.env`:**
+
+* `MYSQL_PASSWORD`, `SECRET_KEY`: Change these for security.
+* `DJANGO_SUPERUSER_PASSWORD`: Default admin password.
+* **Feature Flags**: Toggle authentication methods as needed:
+ ```bash
+ # --- Authentication Features ---
+ USE_LOCAL_AUTH=True
+ USE_CAS=False
+ USE_LDAP=False
+ USE_OIDC=False
+ ```
+
+### Managing the App (Make Commands)
+
+We provide a `Makefile` to simplify Docker commands.
+
+| Command | Description |
+| :--- | :--- |
+| **`make start`** | **Start the full stack** (Builds images, starts DB+API, runs migrations, creates superuser). |
+| **`make stop`** | Stop containers (preserves data). |
+| **`make logs`** | View real-time logs from containers. |
+| **`make shell`** | Launch an isolated temporary shell for debugging. |
+| **`make enter`** | Enter the *running* API container (bash). |
+| **`make clean`** | **Destructive**: Removes containers and volumes (database is lost). |
+| **`make build`** | Force rebuild of Docker images. |
+
+### Running Tests
+
+Tests are executed **inside the Docker container** against a dedicated ephemeral database (`test_pod_db`).
+This ensures your development data (`pod_db`) remains untouched and the environment matches CI.
+
+```bash
+make test
+```
+
+This command will:
+1. Run `pytest` in the container.
+2. Enable **ALL** authentication providers (CAS, LDAP, etc.) to ensure full coverage.
+3. Report code coverage.
+
+### Database Access
+
+* **From Host Machine**: Connect to `localhost:3307`
+ * User: `pod_user` / Password: `pod_password` (or as set in `.env`)
+ * Database: `pod_db`
+* **From Docker**: Connect to host `db` port `3306`.
diff --git a/docs/deployment/prod/prod.md b/docs/deployment/prod/prod.md
new file mode 100644
index 0000000000..0bd12e89b6
--- /dev/null
+++ b/docs/deployment/prod/prod.md
@@ -0,0 +1,20 @@
+TODO
+
+.env.prod :
+
+```bash
+# Django will load the production settings module
+DJANGO_SETTINGS_MODULE=config.django.prod.prod
+
+# Add only the exact production domains.
+ALLOWED_HOSTS=api.your-domain.com
+
+# CORS: required ONLY if your frontend is hosted on a different origin
+# (different domain, subdomain, port, or protocol)
+# If your frontend is on another domain, uncomment and set:
+# CORS_ALLOWED_ORIGINS=https://front.your-domain.com
+
+# If frontend and API share the same origin (same domain + protocol + port),
+# you do NOT need CORS_ALLOWED_ORIGINS.
+
+```
\ No newline at end of file
diff --git a/llms.txt b/llms.txt
new file mode 100644
index 0000000000..ab9f9951a5
--- /dev/null
+++ b/llms.txt
@@ -0,0 +1,23 @@
+# Pod V5 Backend
+
+> Esup-Pod V5 Backend is a Django-based video management platform. This project handles video storage, encoding, and streaming processing (download/streaming).
+
+## Documentation
+
+- [Project README](README.md): Main overview, features, and quickstart.
+- [Contributing Guide](CONTRIBUTING.md): Guidelines for contributing to the project.
+- [CI/CD Pipeline](docs/CI_CD.md): Details on the Continuous Integration and Deployment workflows.
+- [TODO List](TODO.md): Roadmap and pending tasks.
+
+## API & Authentication
+
+- [API Reference](docs/api/README.md): Overview of the REST API endpoints.
+- [API Guide](docs/api/guide.md): Usage guide for the API.
+- [Authentication](docs/authentication/README.md): Authentication mechanisms (CAS, JWT, Local).
+- [Auth Details](docs/authentication/details.md): Deep dive into authentication flows.
+
+## Deployment
+
+- [Deployment Overview](docs/deployment/README.md): General deployment information.
+- [Development deployment](docs/deployment/dev/dev.md): Setup guide for developers.
+- [Production deployment](docs/deployment/prod/prod.md): Guide for deploying to production environments.
diff --git a/manage.py b/manage.py
new file mode 100755
index 0000000000..0971466b89
--- /dev/null
+++ b/manage.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+"""Django's command-line utility for administrative tasks."""
+
+import os
+import sys
+from pathlib import Path
+from environ import ImproperlyConfigured
+
+
+def main():
+ """Run administrative tasks."""
+ base_path = Path(__file__).resolve().parent
+ sys.path.append(str(base_path / "src"))
+
+ # Import env after adding `src` to sys.path so package resolution is unambiguous
+ try:
+ # Prefer the package-style import used by settings: `config.env`
+ from config.env import env
+ except Exception:
+ # Fall back to `src.config.env` if needed
+ from src.config.env import env
+
+ try:
+ settings_module = env.str("DJANGO_SETTINGS_MODULE", default="config.django.base")
+
+ if settings_module:
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
+
+ from django.core.management import execute_from_command_line
+
+ execute_from_command_line(sys.argv)
+
+ except (ImportError, ImproperlyConfigured) as exc:
+ if "django" in str(exc) or isinstance(exc, ImproperlyConfigured):
+ msg = (
+ "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? "
+ f"Also check if DJANGO_SETTINGS_MODULE ('{settings_module}') is correctly defined. "
+ f"Details: {exc}"
+ )
+ print(f"FATAL ERROR: {msg}", file=sys.stderr)
+ sys.exit(1)
+ raise
+ except Exception as e:
+ import traceback
+
+ traceback.print_exc()
+ print(f"FATAL ERROR during manage.py execution: {e}", file=sys.stderr)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000000..1709906262
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,9 @@
+[tool.isort]
+profile = "black"
+line_length = 90
+multi_line_output = 3
+include_trailing_comma = true
+force_grid_wrap = 0
+use_parentheses = true
+ensure_newline_before_comments = true
+skip_glob = ["**/migrations/*.py"]
diff --git a/pytest.ini b/pytest.ini
new file mode 100644
index 0000000000..832c1238a6
--- /dev/null
+++ b/pytest.ini
@@ -0,0 +1,4 @@
+[pytest]
+DJANGO_SETTINGS_MODULE = config.django.test.docker
+python_files = tests.py test_*.py *_tests.py
+addopts = --nomigrations --reuse-db
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000..31c1238942
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,12 @@
+Django==5.2.8
+django-cas-ng>=5.0.0
+django-cors-headers==4.3.1
+django-environ==0.12.0
+djangorestframework==3.15.2
+djangorestframework-simplejwt>=5.3.0
+drf-spectacular==0.29.0
+ldap3>=2.9.0
+mysqlclient==2.2.4
+Pillow>=10.0.0
+python-dotenv==1.0.1
+requests>=2.31.0
diff --git a/scripts/update_schema.sh b/scripts/update_schema.sh
new file mode 100755
index 0000000000..e82ff2b2ec
--- /dev/null
+++ b/scripts/update_schema.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+set -e
+
+echo "Generating OpenAPI schema..."
+python manage.py spectacular --file docs/api-docs.yaml
+echo "Schema updated at docs/api-docs.yaml"
diff --git a/src/__init__.py b/src/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/apps/__init__.py b/src/apps/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/apps/authentication/IPRestrictionMiddleware.py b/src/apps/authentication/IPRestrictionMiddleware.py
new file mode 100644
index 0000000000..e454e462e4
--- /dev/null
+++ b/src/apps/authentication/IPRestrictionMiddleware.py
@@ -0,0 +1,63 @@
+"""
+Esup-Pod IP Restriction middleware.
+
+Ensure that only allowed IPs can access superuser privileges.
+"""
+
+import ipaddress
+
+from django.utils.translation import gettext_lazy as _
+
+
+def ip_in_allowed_range(ip) -> bool:
+ """Make sure the IP is one of the authorized ones."""
+ from django.conf import settings
+
+ ALLOWED_SUPERUSER_IPS = getattr(settings, "ALLOWED_SUPERUSER_IPS", [])
+
+ try:
+ ip_obj = ipaddress.ip_address(ip)
+ except ValueError:
+ return False
+
+ if not ALLOWED_SUPERUSER_IPS:
+ # Allow every clients
+ return True
+
+ for allowed in ALLOWED_SUPERUSER_IPS:
+ try:
+ if is_allowed(ip_obj, allowed):
+ return True
+ except ValueError:
+ continue
+ return False
+
+
+def is_allowed(ip_obj, allowed):
+ """Check if ip object is included in allowed list."""
+ if "/" in allowed:
+ net = ipaddress.ip_network(allowed, strict=False)
+ if ip_obj in net:
+ return True
+ else:
+ if ip_obj == ipaddress.ip_address(allowed):
+ return True
+ return False
+
+
+class IPRestrictionMiddleware:
+ def __init__(self, get_response) -> None:
+ self.get_response = get_response
+
+ def __call__(self, request):
+ ip = request.META.get("REMOTE_ADDR")
+ user = request.user
+
+ if user.is_authenticated and user.is_superuser:
+ if not ip_in_allowed_range(ip):
+ user.is_superuser = False
+ user.last_name = _(
+ "%(last_name)s (Restricted - IP %(ip)s not allowed)"
+ ) % {"last_name": user.last_name, "ip": ip}
+
+ return self.get_response(request)
diff --git a/src/apps/authentication/__init__.py b/src/apps/authentication/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/apps/authentication/admin.py b/src/apps/authentication/admin.py
new file mode 100644
index 0000000000..2b1c277108
--- /dev/null
+++ b/src/apps/authentication/admin.py
@@ -0,0 +1,224 @@
+from django.conf import settings
+from django.contrib import admin
+from django.contrib.admin import widgets
+from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
+from django.contrib.auth.models import Group, User
+from django.contrib.sites.models import Site
+from django.contrib.sites.shortcuts import get_current_site
+from django.utils.html import format_html
+from django.utils.translation import gettext_lazy as _
+
+from .forms import GroupAdminForm, GroupSiteAdminForm, OwnerAdminForm
+from .models import AccessGroup, GroupSite, Owner
+
+# Define an inline admin descriptor for Owner model
+# which acts a bit like a singleton
+
+USE_ESTABLISHMENT_FIELD = getattr(settings, "USE_ESTABLISHMENT_FIELD", False)
+
+
+class GroupSiteInline(admin.StackedInline):
+ model = GroupSite
+ form = GroupSiteAdminForm
+ can_delete = False
+ verbose_name_plural = "groupssite"
+
+ def get_fields(self, request, obj=None):
+ if not request.user.is_superuser:
+ exclude = ()
+ exclude += ("sites",)
+ self.exclude = exclude
+ return list(super(GroupSiteInline, self).get_fields(request, obj))
+
+ class Media:
+ css = {
+ "all": (
+ # "bootstrap/dist/css/bootstrap.min.css",
+ # "bootstrap/css/bootstrap-grid.min.css",
+ # "css/pod.css",
+ )
+ }
+ js = (
+ # "podfile/js/filewidget.js",
+ # "js/main.js",
+ # "bootstrap/dist/js/bootstrap.min.js",
+ )
+
+
+class OwnerInline(admin.StackedInline):
+ model = Owner
+ form = OwnerAdminForm
+ can_delete = False
+ verbose_name_plural = "owners"
+ readonly_fields = ("hashkey",)
+
+ def get_fields(self, request, obj=None):
+ fields = list(super(OwnerInline, self).get_fields(request, obj))
+ exclude_set = set()
+ # obj will be None on the add page, and something on change pages
+ if not obj:
+ exclude_set.add("hashkey")
+ exclude_set.add("auth_type")
+ exclude_set.add("affiliation")
+ exclude_set.add("commentaire")
+ if not request.user.is_superuser:
+ exclude_set.add("sites")
+ return [f for f in fields if f not in exclude_set]
+
+ class Media:
+ css = {
+ "all": (
+ # "bootstrap/dist/css/bootstrap.min.css",
+ # "bootstrap/dist/css/bootstrap-grid.min.css",
+ # "css/pod.css",
+ )
+ }
+ js = (
+ "podfile/js/filewidget.js",
+ "js/main.js",
+ "bootstrap/dist/js/bootstrap.min.js",
+ )
+
+
+class UserAdmin(BaseUserAdmin):
+ @admin.display(description=_("Email"))
+ def clickable_email(self, obj):
+ email = obj.email
+ return format_html('{}', email, email)
+
+ list_display = (
+ "username",
+ "last_name",
+ "first_name",
+ "clickable_email",
+ "date_joined",
+ "last_login",
+ "is_active",
+ "is_staff",
+ "is_superuser",
+ "owner_hashkey",
+ )
+
+ list_filter = (
+ "is_staff",
+ "is_superuser",
+ "is_active",
+ ("groups", admin.RelatedOnlyFieldListFilter),
+ )
+ if USE_ESTABLISHMENT_FIELD:
+ list_display = list_display + ("owner_establishment",)
+
+ # readonly_fields=('is_superuser',)
+ def get_readonly_fields(self, request, obj=None):
+ if request.user.is_superuser:
+ return []
+ self.readonly_fields += ("is_superuser",)
+ return self.readonly_fields
+
+ def owner_hashkey(self, obj) -> str:
+ return "%s" % Owner.objects.get(user=obj).hashkey
+
+ def formfield_for_manytomany(self, db_field, request, **kwargs):
+ if (db_field.name) == "groups":
+ kwargs["queryset"] = Group.objects.filter(
+ groupsite__sites=Site.objects.get_current()
+ )
+ kwargs["widget"] = widgets.FilteredSelectMultiple(db_field.verbose_name, False)
+ return super().formfield_for_foreignkey(db_field, request, **kwargs)
+
+ @admin.display(description=_("Establishment"))
+ def owner_establishment(self, obj) -> str:
+ return "%s" % Owner.objects.get(user=obj).establishment
+
+ ordering = (
+ "-is_superuser",
+ "username",
+ )
+
+ def get_queryset(self, request):
+ qs = super().get_queryset(request)
+ if not request.user.is_superuser:
+ qs = qs.filter(owner__sites=get_current_site(request))
+ return qs
+
+ def save_model(self, request, obj, form, change) -> None:
+ super().save_model(request, obj, form, change)
+ if not change:
+ obj.owner.sites.add(get_current_site(request))
+ obj.owner.save()
+
+ def get_inline_instances(self, request, obj=None):
+ _inlines = super().get_inline_instances(request, obj=None)
+ if obj is not None:
+ custom_inline = OwnerInline(self.model, self.admin_site)
+ _inlines.append(custom_inline)
+ return _inlines
+
+
+# Create a new Group admin.
+class GroupAdmin(admin.ModelAdmin):
+ # Use our custom form.
+ form = GroupAdminForm
+ # Filter permissions horizontal as well.
+ filter_horizontal = ["permissions"]
+ search_fields = ["name"]
+
+ def get_queryset(self, request):
+ qs = super().get_queryset(request)
+ if not request.user.is_superuser:
+ qs = qs.filter(groupsite__sites=get_current_site(request))
+ return qs
+
+ def save_model(self, request, obj, form, change) -> None:
+ super().save_model(request, obj, form, change)
+ if not change:
+ obj.groupsite.sites.add(get_current_site(request))
+ obj.save()
+
+ def get_inline_instances(self, request, obj=None):
+ _inlines = super().get_inline_instances(request, obj=None)
+ if obj is not None:
+ custom_inline = GroupSiteInline(self.model, self.admin_site)
+ _inlines.append(custom_inline)
+ return _inlines
+
+
+@admin.register(AccessGroup)
+class AccessGroupAdmin(admin.ModelAdmin):
+ # form = AccessGroupAdminForm
+ # search_fields = ["user__username__icontains", "user__email__icontains"]
+ autocomplete_fields = ["users"]
+ search_fields = ["id", "code_name", "display_name"]
+ list_display = (
+ "id",
+ "code_name",
+ "display_name",
+ )
+
+
+@admin.register(Owner)
+class OwnerAdmin(admin.ModelAdmin):
+ # form = AdminOwnerForm
+ autocomplete_fields = ["user", "accessgroups"]
+ search_fields = ["user__username__icontains", "user__email__icontains"]
+
+ def get_queryset(self, request):
+ qs = super().get_queryset(request)
+ if not request.user.is_superuser:
+ qs = qs.filter(groupsite__sites=get_current_site(request))
+ return qs
+
+ def has_module_permission(self, request):
+ return False
+
+ class Meta:
+ verbose_name = "Access group owner"
+
+
+# Re-register UserAdmin
+admin.site.unregister(User)
+admin.site.register(User, UserAdmin)
+
+# Register the new Group ModelAdmin instead of the original one.
+admin.site.unregister(Group)
+admin.site.register(Group, GroupAdmin)
diff --git a/src/apps/authentication/apps.py b/src/apps/authentication/apps.py
new file mode 100644
index 0000000000..c7a395f54f
--- /dev/null
+++ b/src/apps/authentication/apps.py
@@ -0,0 +1,8 @@
+from django.apps import AppConfig
+
+
+class AuthenticationConfig(AppConfig):
+ name = "src.apps.authentication"
+ label = "authentication"
+ verbose_name = "Authentication"
+ default_auto_field = "django.db.models.AutoField"
diff --git a/src/apps/authentication/forms.py b/src/apps/authentication/forms.py
new file mode 100644
index 0000000000..43ea2174d4
--- /dev/null
+++ b/src/apps/authentication/forms.py
@@ -0,0 +1,105 @@
+from django import forms
+from django.conf import settings
+from django.contrib.admin.widgets import FilteredSelectMultiple
+from django.contrib.auth import get_user_model
+from django.contrib.auth.models import Group
+from django.contrib.sites.models import Site
+from django.utils.translation import gettext_lazy as _
+
+from .models import GroupSite, Owner
+
+__FILEPICKER__ = False
+if getattr(settings, "USE_PODFILE", False):
+ from pod.podfile.widgets import ( # TODO : change import path when files will be implamented
+ CustomFileWidget,
+ )
+
+ __FILEPICKER__ = True
+
+
+class OwnerAdminForm(forms.ModelForm):
+ def __init__(self, *args, **kwargs) -> None:
+ super(OwnerAdminForm, self).__init__(*args, **kwargs)
+ if __FILEPICKER__:
+ self.fields["userpicture"].widget = CustomFileWidget(type="image")
+
+ class Meta(object):
+ model = Owner
+ fields = "__all__"
+
+
+class GroupSiteAdminForm(forms.ModelForm):
+ def __init__(self, *args, **kwargs) -> None:
+ super(GroupSiteAdminForm, self).__init__(*args, **kwargs)
+
+ class Meta(object):
+ model = GroupSite
+ fields = "__all__"
+
+
+class FrontOwnerForm(OwnerAdminForm):
+ class Meta(object):
+ model = Owner
+ fields = ("userpicture",)
+
+
+class AdminOwnerForm(forms.ModelForm):
+ def __init__(self, *args, **kwargs) -> None:
+ super(AdminOwnerForm, self).__init__(*args, **kwargs)
+
+ class Meta(object):
+ model = Owner
+ fields = []
+
+
+class SetNotificationForm(forms.ModelForm):
+ """Push notification preferences form."""
+
+ def __init__(self, *args, **kwargs) -> None:
+ super(SetNotificationForm, self).__init__(*args, **kwargs)
+
+ class Meta(object):
+ model = Owner
+ fields = ["accepts_notifications"]
+
+
+User = get_user_model()
+
+
+# Create ModelForm based on the Group model.
+class GroupAdminForm(forms.ModelForm):
+ # Add the users field.
+ users = forms.ModelMultipleChoiceField(
+ queryset=User.objects.all(),
+ required=False,
+ # Use the pretty 'filter_horizontal widget'.
+ widget=FilteredSelectMultiple(_("Users"), False),
+ label=_("Users"),
+ )
+
+ class Meta:
+ model = Group
+ fields = "__all__"
+ exclude = []
+
+ def __init__(self, *args, **kwargs) -> None:
+ # Do the normal form initialisation.
+ super(GroupAdminForm, self).__init__(*args, **kwargs)
+ # If it is an existing group (saved objects have a pk).
+ if self.instance.pk:
+ # Populate the users field with the current Group users.
+ self.fields["users"].initial = self.instance.user_set.all()
+ self.fields["users"].queryset = self.fields["users"].queryset.filter(
+ owner__sites=Site.objects.get_current()
+ )
+
+ def save_m2m(self) -> None:
+ # Add the users to the Group.
+ self.instance.user_set.set(self.cleaned_data["users"])
+
+ def save(self, *args, **kwargs):
+ # Default save
+ instance = super(GroupAdminForm, self).save()
+ # Save many-to-many data
+ self.save_m2m()
+ return instance
diff --git a/src/apps/authentication/models/AccessGroup.py b/src/apps/authentication/models/AccessGroup.py
new file mode 100644
index 0000000000..40826e16ef
--- /dev/null
+++ b/src/apps/authentication/models/AccessGroup.py
@@ -0,0 +1,38 @@
+from django.contrib.sites.models import Site
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+class AccessGroup(models.Model):
+ """
+ Represents a group of users with specific access rights to sites.
+ Used to map external authentication groups (LDAP/CAS) to internal permissions.
+ """
+
+ display_name = models.CharField(
+ max_length=128,
+ blank=True,
+ default="",
+ help_text=_("Readable name of the group."),
+ )
+ code_name = models.CharField(
+ max_length=250,
+ unique=True,
+ help_text=_("Unique identifier code (e.g., LDAP group name)."),
+ )
+ sites = models.ManyToManyField(Site, help_text=_("Sites accessible by this group."))
+ auto_sync = models.BooleanField(
+ _("Auto synchronize"),
+ default=False,
+ help_text=_(
+ "If True, this group is automatically managed via external auth (CAS/LDAP)."
+ ),
+ )
+
+ class Meta:
+ verbose_name = _("Access Group")
+ verbose_name_plural = _("Access Groups")
+ ordering = ["display_name"]
+
+ def __str__(self) -> str:
+ return self.display_name or self.code_name
diff --git a/src/apps/authentication/models/GroupSite.py b/src/apps/authentication/models/GroupSite.py
new file mode 100644
index 0000000000..38020f0b1e
--- /dev/null
+++ b/src/apps/authentication/models/GroupSite.py
@@ -0,0 +1,51 @@
+import logging
+import traceback
+
+from django.contrib.auth.models import Group
+from django.contrib.sites.models import Site
+from django.db import models
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+from django.utils.translation import gettext_lazy as _
+
+logger = logging.getLogger(__name__)
+
+
+class GroupSite(models.Model):
+ """
+ Model linking a Group to one or more Sites.
+ Extends the default Group model to allow site-specific group associations.
+ """
+
+ group = models.OneToOneField(Group, on_delete=models.CASCADE)
+ sites = models.ManyToManyField(Site)
+
+ class Meta:
+ verbose_name = _("Group site")
+ verbose_name_plural = _("Groups site")
+ ordering = ["group"]
+
+
+@receiver(post_save, sender=GroupSite)
+def default_site_groupsite(sender, instance, created: bool, **kwargs) -> None:
+ """
+ Signal receiver to assign the current site to a GroupSite instance if no site is set.
+ Triggered after a GroupSite is saved.
+ """
+ if instance.pk and instance.sites.count() == 0:
+ instance.sites.add(Site.objects.get_current())
+
+
+@receiver(post_save, sender=Group)
+def create_groupsite_profile(sender, instance, created: bool, **kwargs) -> None:
+ """
+ Signal receiver to automatically create a GroupSite profile when a new Group is created.
+ """
+ if created:
+ try:
+ GroupSite.objects.get_or_create(group=instance)
+ except Exception as e:
+ msg = "\n Create groupsite profile ***** Error:%r" % e
+ msg += "\n%s" % traceback.format_exc()
+ logger.error(msg)
+ print(msg)
diff --git a/src/apps/authentication/models/Owner.py b/src/apps/authentication/models/Owner.py
new file mode 100644
index 0000000000..30e5a73c77
--- /dev/null
+++ b/src/apps/authentication/models/Owner.py
@@ -0,0 +1,140 @@
+import hashlib
+import logging
+
+from django.contrib.auth.models import Permission, User
+from django.contrib.sites.models import Site
+from django.db import models
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+from django.utils.translation import gettext_lazy as _
+
+from src.apps.utils.models.CustomImageModel import CustomImageModel
+
+from .utils import (
+ AFFILIATION,
+ AUTH_TYPE,
+ DEFAULT_AFFILIATION,
+ ESTABLISHMENTS,
+ HIDE_USERNAME,
+ SECRET_KEY,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class Owner(models.Model):
+ """
+ Extends the default Django User model to add specific attributes
+ for the POD application (affiliation, establishment, auth type, etc.).
+ """
+
+ user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="owner")
+ auth_type = models.CharField(
+ _("Authentication Type"),
+ max_length=20,
+ choices=AUTH_TYPE,
+ default=AUTH_TYPE[0][0],
+ )
+ affiliation = models.CharField(
+ _("Affiliation"),
+ max_length=50,
+ choices=AFFILIATION,
+ default=DEFAULT_AFFILIATION,
+ )
+ commentaire = models.TextField(_("Comment"), blank=True, default="")
+ hashkey = models.CharField(
+ max_length=64,
+ unique=True,
+ blank=True,
+ default="",
+ help_text=_("Unique hash generated from username and secret key."),
+ )
+ userpicture = models.ForeignKey(
+ CustomImageModel,
+ blank=True,
+ null=True,
+ on_delete=models.CASCADE,
+ verbose_name=_("Picture"),
+ )
+ establishment = models.CharField(
+ _("Establishment"),
+ max_length=10,
+ blank=True,
+ choices=ESTABLISHMENTS,
+ default=ESTABLISHMENTS[0][0],
+ )
+
+ accessgroups = models.ManyToManyField(
+ "authentication.AccessGroup",
+ blank=True,
+ related_name="users",
+ verbose_name=_("Access Groups"),
+ )
+ sites = models.ManyToManyField(Site, related_name="owners")
+ accepts_notifications = models.BooleanField(
+ verbose_name=_("Accept notifications"),
+ default=None,
+ null=True,
+ help_text=_("Receive push notifications on your devices."),
+ )
+
+ class Meta:
+ verbose_name = _("Owner")
+ verbose_name_plural = _("Owners")
+ ordering = ["user"]
+
+ def __str__(self) -> str:
+ if HIDE_USERNAME:
+ return f"{self.user.first_name} {self.user.last_name}"
+ return f"{self.user.first_name} {self.user.last_name} ({self.user.username})"
+
+ def save(self, *args, **kwargs) -> None:
+ """
+ Overridden save method to ensure hashkey generation.
+ """
+ if self.user and self.user.username and not self.hashkey:
+ self.hashkey = hashlib.sha256(
+ (SECRET_KEY + self.user.username).encode("utf-8")
+ ).hexdigest()
+ super().save(*args, **kwargs)
+
+ def is_manager(self) -> bool:
+ """
+ Check if the user has management permissions on the current site.
+ """
+ if not self.user.groups.exists():
+ return False
+ group_ids = (
+ self.user.groups.all()
+ .filter(groupsite__sites=Site.objects.get_current())
+ .values_list("id", flat=True)
+ )
+
+ return (
+ self.user.is_staff
+ and Permission.objects.filter(group__id__in=group_ids).count() > 0
+ )
+
+ @property
+ def email(self) -> str:
+ return self.user.email
+
+
+@receiver(post_save, sender=Owner)
+def default_site_owner(sender, instance: Owner, created: bool, **kwargs) -> None:
+ """Assigns the current site to the owner upon creation/update if none exists."""
+ if instance.pk and instance.sites.count() == 0:
+ instance.sites.add(Site.objects.get_current())
+
+
+@receiver(post_save, sender=User)
+def create_owner_profile(sender, instance: User, created: bool, **kwargs) -> None:
+ """Automatically creates an Owner profile when a Django User is created."""
+ if created:
+ try:
+ Owner.objects.get_or_create(user=instance)
+ except Exception as e:
+ logger.error(
+ f"Error creating owner profile for user {instance.username}: {e}",
+ exc_info=True,
+ )
diff --git a/src/apps/authentication/models/__init__.py b/src/apps/authentication/models/__init__.py
new file mode 100644
index 0000000000..efda7ca92d
--- /dev/null
+++ b/src/apps/authentication/models/__init__.py
@@ -0,0 +1,42 @@
+from django.contrib.auth.models import User
+
+from .AccessGroup import AccessGroup
+from .GroupSite import GroupSite
+from .Owner import Owner
+from .utils import (
+ AFFILIATION,
+ AFFILIATION_STAFF,
+ AUTH_TYPE,
+ DEFAULT_AFFILIATION,
+ ESTABLISHMENTS,
+ HIDE_USERNAME,
+)
+
+
+def get_name(self: User) -> str:
+ """
+ Returns the user's full name, including the username if it is not hidden.
+ Overrides Django's default __str__ method.
+ """
+ if HIDE_USERNAME or not self.is_authenticated:
+ name = self.get_full_name().strip()
+ return name if name else self.get_username()
+
+ full_name = self.get_full_name().strip()
+ if full_name:
+ return f"{full_name} ({self.get_username()})"
+ return self.get_username()
+
+
+User.add_to_class("__str__", get_name)
+
+__all__ = [
+ "AFFILIATION",
+ "AFFILIATION_STAFF",
+ "DEFAULT_AFFILIATION",
+ "AUTH_TYPE",
+ "ESTABLISHMENTS",
+ "Owner",
+ "AccessGroup",
+ "GroupSite",
+]
diff --git a/src/apps/authentication/models/utils.py b/src/apps/authentication/models/utils.py
new file mode 100644
index 0000000000..4b2e9c6cd6
--- /dev/null
+++ b/src/apps/authentication/models/utils.py
@@ -0,0 +1,68 @@
+from django.conf import settings
+from django.contrib.auth.models import User
+from django.utils.translation import gettext_lazy as _
+
+if getattr(settings, "USE_PODFILE", False):
+ pass # TODO : change import path when files will be implamented
+else:
+ pass
+
+HIDE_USERNAME = getattr(settings, "HIDE_USERNAME", False)
+
+AUTH_TYPE = getattr(
+ settings,
+ "AUTH_TYPE",
+ (
+ ("local", _("local")),
+ ("CAS", "CAS"),
+ ("OIDC", "OIDC"),
+ ("Shibboleth", "Shibboleth"),
+ ),
+)
+AFFILIATION = getattr(
+ settings,
+ "AFFILIATION",
+ (
+ ("student", _("student")),
+ ("faculty", _("faculty")),
+ ("staff", _("staff")),
+ ("employee", _("employee")),
+ ("member", _("member")),
+ ("affiliate", _("affiliate")),
+ ("alum", _("alum")),
+ ("library-walk-in", _("library-walk-in")),
+ ("researcher", _("researcher")),
+ ("retired", _("retired")),
+ ("emeritus", _("emeritus")),
+ ("teacher", _("teacher")),
+ ("registered-reader", _("registered-reader")),
+ ),
+)
+DEFAULT_AFFILIATION = AFFILIATION[0][0]
+AFFILIATION_STAFF = getattr(
+ settings, "AFFILIATION_STAFF", ("faculty", "employee", "staff")
+)
+ESTABLISHMENTS = getattr(
+ settings,
+ "ESTABLISHMENTS",
+ (
+ ("Etab_1", "Etab_1"),
+ ("Etab_2", "Etab_2"),
+ ),
+)
+SECRET_KEY = getattr(settings, "SECRET_KEY", "")
+
+
+def get_name(self: User) -> str:
+ """
+ Return the user's full name, including the username if not hidden.
+
+ Returns:
+ str: The user's full name and username if not hidden.
+ """
+ if HIDE_USERNAME or not self.is_authenticated:
+ return self.get_full_name().strip()
+ return f"{self.get_full_name()} ({self.get_username()})".strip()
+
+
+User.add_to_class("__str__", get_name)
diff --git a/src/apps/authentication/serializers/AccessGroupSerializer.py b/src/apps/authentication/serializers/AccessGroupSerializer.py
new file mode 100644
index 0000000000..ad761c9d5e
--- /dev/null
+++ b/src/apps/authentication/serializers/AccessGroupSerializer.py
@@ -0,0 +1,12 @@
+from rest_framework import serializers
+
+from ..models.AccessGroup import AccessGroup
+
+
+class AccessGroupSerializer(serializers.ModelSerializer):
+ users = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
+
+ class Meta:
+ model = AccessGroup
+ fields = ("id", "display_name", "code_name", "sites", "users", "auto_sync")
+ read_only_fields = ["users"]
diff --git a/src/apps/authentication/serializers/CASTokenObtainPairSerializer.py b/src/apps/authentication/serializers/CASTokenObtainPairSerializer.py
new file mode 100644
index 0000000000..fa465afb84
--- /dev/null
+++ b/src/apps/authentication/serializers/CASTokenObtainPairSerializer.py
@@ -0,0 +1,44 @@
+from django.utils.translation import gettext_lazy as _
+from rest_framework import serializers
+from rest_framework_simplejwt.tokens import RefreshToken
+
+from ..services import verify_cas_ticket
+
+
+class CASTokenObtainPairSerializer(serializers.Serializer):
+ ticket = serializers.CharField()
+ service = serializers.CharField()
+
+ def validate(self, attrs):
+ ticket = attrs.get("ticket")
+ service = attrs.get("service")
+ user = verify_cas_ticket(ticket, service)
+
+ if user is None:
+ raise serializers.ValidationError(
+ _("Authentication failed: Invalid CAS ticket or user creation error.")
+ )
+
+ if not user.is_active:
+ raise serializers.ValidationError(_("User account is disabled."))
+
+ refresh = RefreshToken.for_user(user)
+
+ refresh["username"] = user.username
+ refresh["is_staff"] = user.is_staff
+ if hasattr(user, "owner"):
+ refresh["affiliation"] = user.owner.affiliation
+
+ return {
+ "refresh": str(refresh),
+ "access": str(refresh.access_token),
+ "user": {
+ "username": user.username,
+ "email": user.email,
+ "first_name": user.first_name,
+ "last_name": user.last_name,
+ "affiliation": (
+ user.owner.affiliation if hasattr(user, "owner") else None
+ ),
+ },
+ }
diff --git a/src/apps/authentication/serializers/CustomTokenObtainPairSerializer.py b/src/apps/authentication/serializers/CustomTokenObtainPairSerializer.py
new file mode 100644
index 0000000000..060f37c54c
--- /dev/null
+++ b/src/apps/authentication/serializers/CustomTokenObtainPairSerializer.py
@@ -0,0 +1,36 @@
+from typing import Any, Dict
+
+from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
+
+
+class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
+ """
+ Custom JWT Token Serializer.
+
+ Extends the default SimpleJWT serializer to include custom claims
+ in the encrypted token payload (username, staff status, affiliation).
+ """
+
+ @classmethod
+ def get_token(cls, user) -> Any:
+ token = super().get_token(user)
+ token["username"] = user.username
+ token["is_staff"] = user.is_staff
+ if hasattr(user, "owner"):
+ token["affiliation"] = user.owner.affiliation
+
+ return token
+
+ def validate(self, attrs: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Adds extra responses to the JSON response body (not just inside the token).
+ """
+ data = super().validate(attrs)
+
+ data["username"] = self.user.username
+ data["email"] = self.user.email
+ data["is_staff"] = self.user.is_staff
+
+ if hasattr(self.user, "owner"):
+ data["affiliation"] = self.user.owner.affiliation
+ return data
diff --git a/src/apps/authentication/serializers/ExternalAuthSerializers.py b/src/apps/authentication/serializers/ExternalAuthSerializers.py
new file mode 100644
index 0000000000..013dd89d4d
--- /dev/null
+++ b/src/apps/authentication/serializers/ExternalAuthSerializers.py
@@ -0,0 +1,21 @@
+from rest_framework import serializers
+
+
+class OIDCTokenObtainSerializer(serializers.Serializer):
+ """
+ Serializer for OIDC code exchange. The frontend returns the 'code' received after redirection.
+ """
+
+ code = serializers.CharField(required=True)
+ redirect_uri = serializers.CharField(
+ required=True,
+ help_text="L'URI de redirection utilisée lors de la demande initiale.",
+ )
+
+
+class ShibbolethTokenObtainSerializer(serializers.Serializer):
+ """
+ Empty serializer because Shibboleth uses HTTP headers. Used primarily for API documentation (Swagger).
+ """
+
+ pass
diff --git a/src/apps/authentication/serializers/GroupSerializer.py b/src/apps/authentication/serializers/GroupSerializer.py
new file mode 100644
index 0000000000..963db34dea
--- /dev/null
+++ b/src/apps/authentication/serializers/GroupSerializer.py
@@ -0,0 +1,8 @@
+from django.contrib.auth.models import Group
+from rest_framework import serializers
+
+
+class GroupSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Group
+ fields = ("id", "name")
diff --git a/src/apps/authentication/serializers/OwnerSerializer.py b/src/apps/authentication/serializers/OwnerSerializer.py
new file mode 100644
index 0000000000..1d4d65b091
--- /dev/null
+++ b/src/apps/authentication/serializers/OwnerSerializer.py
@@ -0,0 +1,45 @@
+from django.contrib.auth import get_user_model
+from rest_framework import serializers
+
+from ..models.Owner import Owner
+
+User = get_user_model()
+
+
+class OwnerSerializer(serializers.ModelSerializer):
+ user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
+
+ class Meta:
+ model = Owner
+ fields = (
+ "id",
+ "user",
+ "auth_type",
+ "affiliation",
+ "commentaire",
+ "hashkey",
+ "userpicture",
+ "sites",
+ )
+
+
+class OwnerWithGroupsSerializer(serializers.ModelSerializer):
+ """
+ Specific serializer including AccessGroups.
+ Used in particular when modifying a user's permissions.
+ """
+
+ user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
+
+ class Meta:
+ model = Owner
+ fields = (
+ "id",
+ "user",
+ "auth_type",
+ "affiliation",
+ "commentaire",
+ "hashkey",
+ "userpicture",
+ "accessgroups",
+ )
diff --git a/src/apps/authentication/serializers/SiteSerializer.py b/src/apps/authentication/serializers/SiteSerializer.py
new file mode 100644
index 0000000000..52d7faf389
--- /dev/null
+++ b/src/apps/authentication/serializers/SiteSerializer.py
@@ -0,0 +1,8 @@
+from django.contrib.sites.models import Site
+from rest_framework import serializers
+
+
+class SiteSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Site
+ fields = ("id", "name", "domain")
diff --git a/src/apps/authentication/serializers/UserSerializer.py b/src/apps/authentication/serializers/UserSerializer.py
new file mode 100644
index 0000000000..1299c6a2dd
--- /dev/null
+++ b/src/apps/authentication/serializers/UserSerializer.py
@@ -0,0 +1,48 @@
+from django.contrib.auth import get_user_model
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+User = get_user_model()
+
+
+class UserSerializer(serializers.ModelSerializer):
+ """
+ Serializer for the User model, enriched with Owner profile data.
+ """
+
+ affiliation = serializers.SerializerMethodField(method_name="get_affiliation")
+ establishment = serializers.SerializerMethodField(method_name="get_establishment")
+ userpicture = serializers.SerializerMethodField(method_name="get_userpicture")
+
+ class Meta:
+ model = User
+ fields = [
+ "id",
+ "username",
+ "email",
+ "first_name",
+ "last_name",
+ "is_staff",
+ "affiliation",
+ "establishment",
+ "userpicture",
+ ]
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_affiliation(self, obj) -> str | None:
+ """Returns the user's affiliation from the Owner profile."""
+ if hasattr(obj, "owner"):
+ return obj.owner.affiliation
+ return None
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_establishment(self, obj) -> str | None:
+ """Returns the user's establishment from the Owner profile."""
+ if hasattr(obj, "owner"):
+ return obj.owner.establishment
+ return None
+
+ def get_userpicture(self, obj) -> str | None:
+ if hasattr(obj, "owner") and obj.owner.userpicture:
+ return obj.owner.userpicture.image.url
+ return None
diff --git a/src/apps/authentication/services/__init__.py b/src/apps/authentication/services/__init__.py
new file mode 100644
index 0000000000..1298df577d
--- /dev/null
+++ b/src/apps/authentication/services/__init__.py
@@ -0,0 +1,22 @@
+from .core import (
+ GROUP_STAFF,
+ REMOTE_USER_HEADER,
+ SHIBBOLETH_ATTRIBUTE_MAP,
+ is_staff_affiliation,
+)
+from .providers import OIDCService, ShibbolethService, verify_cas_ticket
+from .tokens import get_tokens_for_user
+from .users import AccessGroupService, UserPopulator
+
+__all__ = [
+ "is_staff_affiliation",
+ "GROUP_STAFF",
+ "REMOTE_USER_HEADER",
+ "SHIBBOLETH_ATTRIBUTE_MAP",
+ "get_tokens_for_user",
+ "AccessGroupService",
+ "UserPopulator",
+ "verify_cas_ticket",
+ "ShibbolethService",
+ "OIDCService",
+]
diff --git a/src/apps/authentication/services/core.py b/src/apps/authentication/services/core.py
new file mode 100644
index 0000000000..0c5e33739c
--- /dev/null
+++ b/src/apps/authentication/services/core.py
@@ -0,0 +1,62 @@
+from django.conf import settings
+
+from ..models.utils import AFFILIATION_STAFF, DEFAULT_AFFILIATION
+
+GROUP_STAFF = AFFILIATION_STAFF
+
+CREATE_GROUP_FROM_AFFILIATION = getattr(settings, "CREATE_GROUP_FROM_AFFILIATION", False)
+
+REMOTE_USER_HEADER = getattr(settings, "REMOTE_USER_HEADER", "REMOTE_USER")
+SHIBBOLETH_ATTRIBUTE_MAP = getattr(
+ settings,
+ "SHIBBOLETH_ATTRIBUTE_MAP",
+ {
+ "REMOTE_USER": (True, "username"),
+ "Shibboleth-givenName": (True, "first_name"),
+ "Shibboleth-sn": (False, "last_name"),
+ "Shibboleth-mail": (False, "email"),
+ "Shibboleth-primary-affiliation": (False, "affiliation"),
+ "Shibboleth-unscoped-affiliation": (False, "affiliations"),
+ },
+)
+SHIBBOLETH_STAFF_ALLOWED_DOMAINS = getattr(
+ settings, "SHIBBOLETH_STAFF_ALLOWED_DOMAINS", None
+)
+
+OIDC_CLAIM_GIVEN_NAME = getattr(settings, "OIDC_CLAIM_GIVEN_NAME", "given_name")
+OIDC_CLAIM_FAMILY_NAME = getattr(settings, "OIDC_CLAIM_FAMILY_NAME", "family_name")
+OIDC_CLAIM_PREFERRED_USERNAME = getattr(
+ settings, "OIDC_CLAIM_PREFERRED_USERNAME", "preferred_username"
+)
+OIDC_DEFAULT_AFFILIATION = getattr(
+ settings, "OIDC_DEFAULT_AFFILIATION", DEFAULT_AFFILIATION
+)
+OIDC_DEFAULT_ACCESS_GROUP_CODE_NAMES = getattr(
+ settings, "OIDC_DEFAULT_ACCESS_GROUP_CODE_NAMES", []
+)
+
+USER_LDAP_MAPPING_ATTRIBUTES = getattr(
+ settings,
+ "USER_LDAP_MAPPING_ATTRIBUTES",
+ {
+ "uid": "uid",
+ "mail": "mail",
+ "last_name": "sn",
+ "first_name": "givenname",
+ "primaryAffiliation": "eduPersonPrimaryAffiliation",
+ "affiliations": "eduPersonAffiliation",
+ "groups": "memberOf",
+ "establishment": "establishment",
+ },
+)
+
+AUTH_LDAP_USER_SEARCH = getattr(
+ settings,
+ "AUTH_LDAP_USER_SEARCH",
+ ("ou=people,dc=univ,dc=fr", "(uid=%(uid)s)"),
+)
+
+
+def is_staff_affiliation(affiliation) -> bool:
+ """Check if user affiliation correspond to AFFILIATION_STAFF."""
+ return affiliation in AFFILIATION_STAFF
diff --git a/src/apps/authentication/services/ldap_client.py b/src/apps/authentication/services/ldap_client.py
new file mode 100644
index 0000000000..6bab07e0bb
--- /dev/null
+++ b/src/apps/authentication/services/ldap_client.py
@@ -0,0 +1,66 @@
+import logging
+from typing import Any, Optional
+
+from django.conf import settings
+from ldap3 import ALL, SUBTREE, Connection, Server
+from ldap3.core.exceptions import LDAPBindError, LDAPSocketOpenError
+
+from .core import AUTH_LDAP_USER_SEARCH, USER_LDAP_MAPPING_ATTRIBUTES
+
+logger = logging.getLogger(__name__)
+
+
+def get_ldap_conn():
+ """Open and get LDAP connexion."""
+ ldap_server_conf = getattr(settings, "LDAP_SERVER", {})
+ auth_bind_dn = getattr(settings, "AUTH_LDAP_BIND_DN", "")
+ auth_bind_pwd = getattr(settings, "AUTH_LDAP_BIND_PASSWORD", "")
+
+ url = ldap_server_conf.get("url")
+ if not url:
+ return None
+
+ try:
+ server = None
+ if isinstance(url, str):
+ server = Server(
+ url,
+ port=ldap_server_conf.get("port", 389),
+ use_ssl=ldap_server_conf.get("use_ssl", False),
+ get_info=ALL,
+ )
+ elif isinstance(url, tuple) or isinstance(url, list):
+ server = Server(
+ url[0],
+ port=ldap_server_conf.get("port", 389),
+ use_ssl=ldap_server_conf.get("use_ssl", False),
+ get_info=ALL,
+ )
+
+ if server:
+ return Connection(server, auth_bind_dn, auth_bind_pwd, auto_bind=True)
+
+ except (LDAPBindError, LDAPSocketOpenError) as err:
+ logger.error(f"LDAP Connection Error: {err}")
+ return None
+ return None
+
+
+def get_ldap_entry(conn: Connection, username: str) -> Optional[Any]:
+ """Get LDAP entry for a specific username."""
+ # Build list of attributes to fetch
+ attributes_to_fetch = list(USER_LDAP_MAPPING_ATTRIBUTES.values())
+
+ try:
+ search_filter = AUTH_LDAP_USER_SEARCH[1] % {"uid": username}
+ conn.search(
+ AUTH_LDAP_USER_SEARCH[0],
+ search_filter,
+ search_scope=SUBTREE,
+ attributes=attributes_to_fetch,
+ size_limit=1,
+ )
+ return conn.entries[0] if len(conn.entries) > 0 else None
+ except Exception as err:
+ logger.error(f"LDAP Search Error: {err}")
+ return None
diff --git a/src/apps/authentication/services/providers/__init__.py b/src/apps/authentication/services/providers/__init__.py
new file mode 100644
index 0000000000..2c05f5c217
--- /dev/null
+++ b/src/apps/authentication/services/providers/__init__.py
@@ -0,0 +1,5 @@
+from .cas import verify_cas_ticket
+from .oidc import OIDCService
+from .shibboleth import ShibbolethService
+
+__all__ = ["verify_cas_ticket", "ShibbolethService", "OIDCService"]
diff --git a/src/apps/authentication/services/providers/cas.py b/src/apps/authentication/services/providers/cas.py
new file mode 100644
index 0000000000..8b7e325de2
--- /dev/null
+++ b/src/apps/authentication/services/providers/cas.py
@@ -0,0 +1,48 @@
+import logging
+from typing import Any, Optional
+
+from django.conf import settings
+from django.contrib.auth import get_user_model
+from django_cas_ng.utils import get_cas_client
+
+from ..users import UserPopulator
+
+UserModel = get_user_model()
+logger = logging.getLogger(__name__)
+
+
+def verify_cas_ticket(ticket: str, service_url: str) -> Optional[Any]:
+ """
+ Verifies the CAS service ticket using django-cas-ng utils.
+ Then populates user using UserPopulator.
+ """
+ client = get_cas_client(service_url=service_url)
+ username, attributes, _ = client.verify_ticket(ticket)
+
+ if not username:
+ logger.warning("CAS ticket validation failed")
+ return None
+
+ if getattr(settings, "CAS_FORCE_CHANGE_USERNAME_CASE", "lower") == "lower":
+ username = username.lower()
+
+ user, created = UserModel.objects.get_or_create(username=username)
+
+ if created:
+ user.set_unusable_password()
+ user.save()
+
+ # Determine usage strategy
+ populate_strategy = getattr(settings, "POPULATE_USER", None)
+
+ populator = UserPopulator(user)
+
+ if populate_strategy == "CAS":
+ populator.run("CAS", attributes)
+ elif populate_strategy == "LDAP":
+ populator.run("LDAP")
+ else:
+ # Minimal init if no external source strategy selected
+ pass
+
+ return user
diff --git a/src/apps/authentication/services/providers/oidc.py b/src/apps/authentication/services/providers/oidc.py
new file mode 100644
index 0000000000..4859101f93
--- /dev/null
+++ b/src/apps/authentication/services/providers/oidc.py
@@ -0,0 +1,67 @@
+import logging
+from typing import Any, Dict
+
+import requests
+from django.conf import settings
+from django.contrib.auth import get_user_model
+
+from ..core import OIDC_CLAIM_PREFERRED_USERNAME
+from ..tokens import get_tokens_for_user
+from ..users import UserPopulator
+
+UserModel = get_user_model()
+logger = logging.getLogger(__name__)
+
+
+class OIDCService:
+ def process_code(self, code: str, redirect_uri: str) -> Dict[str, Any]:
+ """Exchange OIDC code for tokens and populate user."""
+ token_url = getattr(settings, "OIDC_OP_TOKEN_ENDPOINT", "")
+ client_id = getattr(settings, "OIDC_RP_CLIENT_ID", "")
+ client_secret = getattr(settings, "OIDC_RP_CLIENT_SECRET", "")
+
+ if not token_url:
+ raise EnvironmentError("OIDC not configured (missing OIDC_OP_TOKEN_ENDPOINT)")
+
+ payload = {
+ "grant_type": "authorization_code",
+ "code": code,
+ "redirect_uri": redirect_uri,
+ "client_id": client_id,
+ "client_secret": client_secret,
+ }
+
+ try:
+ r_token = requests.post(token_url, data=payload)
+ r_token.raise_for_status()
+ tokens_oidc = r_token.json()
+ access_token = tokens_oidc.get("access_token")
+ except Exception as e:
+ logger.error(f"OIDC Token Exchange failed: {e}")
+ raise ConnectionError("Failed to exchange OIDC code")
+
+ userinfo_url = getattr(settings, "OIDC_OP_USER_ENDPOINT", "")
+ try:
+ headers = {"Authorization": f"Bearer {access_token}"}
+ r_user = requests.get(userinfo_url, headers=headers)
+ r_user.raise_for_status()
+ claims = r_user.json()
+ except Exception as e:
+ logger.error(f"OIDC UserInfo failed: {e}")
+
+ # Additional logging for debugging
+ logger.error(f"OIDC UserInfo Endpoint: {userinfo_url}")
+
+ raise ConnectionError("Failed to fetch OIDC user info")
+
+ username = claims.get(OIDC_CLAIM_PREFERRED_USERNAME)
+ if not username:
+ raise ValueError("Missing username in OIDC claims")
+
+ user, created = UserModel.objects.get_or_create(username=username)
+
+ # Populate user using centralized logic
+ populator = UserPopulator(user)
+ populator.run("OIDC", claims)
+
+ return get_tokens_for_user(user)
diff --git a/src/apps/authentication/services/providers/shibboleth.py b/src/apps/authentication/services/providers/shibboleth.py
new file mode 100644
index 0000000000..c81cf3397f
--- /dev/null
+++ b/src/apps/authentication/services/providers/shibboleth.py
@@ -0,0 +1,52 @@
+from typing import Any, Dict
+
+from django.conf import settings
+from django.contrib.auth import get_user_model
+
+from ..core import REMOTE_USER_HEADER, SHIBBOLETH_ATTRIBUTE_MAP
+from ..tokens import get_tokens_for_user
+from ..users import UserPopulator
+
+UserModel = get_user_model()
+
+
+class ShibbolethService:
+ def check_security(self, request) -> bool:
+ """Verify request comes from a trusted source (SP) if configured."""
+ secure_header = getattr(settings, "SHIB_SECURE_HEADER", None)
+ if secure_header:
+ return request.META.get(secure_header) == getattr(
+ settings, "SHIB_SECURE_VALUE", "secure"
+ )
+ return True
+
+ def get_header_value(self, request, header_name):
+ return request.META.get(header_name, "")
+
+ def process_request(self, request) -> Dict[str, Any]:
+ """Process Shibboleth headers and return user tokens."""
+ if not self.check_security(request):
+ raise PermissionError("Insecure request. Missing security header.")
+
+ username = self.get_header_value(request, REMOTE_USER_HEADER)
+ if not username:
+ raise ValueError(f"Missing {REMOTE_USER_HEADER} header.")
+
+ user, created = UserModel.objects.get_or_create(username=username)
+
+ # Extract attributes
+ shib_meta = {}
+ for header, (required, field) in SHIBBOLETH_ATTRIBUTE_MAP.items():
+ value = self.get_header_value(request, header)
+ if value:
+ shib_meta[field] = value
+ # Update basic user fields immediately if present
+ if field in ["first_name", "last_name", "email"]:
+ setattr(user, field, value)
+
+ user.save()
+ # Use UserPopulator logic which seems more complete/centralized
+ populator = UserPopulator(user)
+ populator.run("Shibboleth", shib_meta)
+
+ return get_tokens_for_user(user)
diff --git a/src/apps/authentication/services/tokens.py b/src/apps/authentication/services/tokens.py
new file mode 100644
index 0000000000..2fcc7fba00
--- /dev/null
+++ b/src/apps/authentication/services/tokens.py
@@ -0,0 +1,23 @@
+from typing import Any, Dict
+
+
+def get_tokens_for_user(user) -> Dict[str, Any]:
+ from rest_framework_simplejwt.tokens import RefreshToken
+
+ refresh = RefreshToken.for_user(user)
+ refresh["username"] = user.username
+ refresh["is_staff"] = user.is_staff
+ if hasattr(user, "owner"):
+ refresh["affiliation"] = user.owner.affiliation
+
+ return {
+ "refresh": str(refresh),
+ "access": str(refresh.access_token),
+ "user": {
+ "username": user.username,
+ "email": user.email,
+ "first_name": user.first_name,
+ "last_name": user.last_name,
+ "affiliation": user.owner.affiliation if hasattr(user, "owner") else None,
+ },
+ }
diff --git a/src/apps/authentication/services/users/__init__.py b/src/apps/authentication/services/users/__init__.py
new file mode 100644
index 0000000000..9a593706cb
--- /dev/null
+++ b/src/apps/authentication/services/users/__init__.py
@@ -0,0 +1,4 @@
+from .access_groups import AccessGroupService
+from .populator import UserPopulator
+
+__all__ = ["AccessGroupService", "UserPopulator"]
diff --git a/src/apps/authentication/services/users/access_groups.py b/src/apps/authentication/services/users/access_groups.py
new file mode 100644
index 0000000000..493e84ce02
--- /dev/null
+++ b/src/apps/authentication/services/users/access_groups.py
@@ -0,0 +1,56 @@
+from typing import Any, List
+
+from ...models.AccessGroup import AccessGroup
+from ...models.Owner import Owner
+
+
+class AccessGroupService:
+ @staticmethod
+ def set_user_accessgroup(username: str, groups: List[str]) -> Any:
+ owner = Owner.objects.get(user__username=username) # Will raise DoesNotExist
+
+ for group_code in groups:
+ try:
+ accessgroup = AccessGroup.objects.get(code_name=group_code)
+ owner.accessgroups.add(accessgroup)
+ except AccessGroup.DoesNotExist:
+ pass
+ return owner
+
+ @staticmethod
+ def remove_user_accessgroup(username: str, groups: List[str]) -> Any:
+ owner = Owner.objects.get(user__username=username)
+
+ for group_code in groups:
+ try:
+ accessgroup = AccessGroup.objects.get(code_name=group_code)
+ if accessgroup in owner.accessgroups.all():
+ owner.accessgroups.remove(accessgroup)
+ except AccessGroup.DoesNotExist:
+ pass
+ return owner
+
+ @staticmethod
+ def set_users_by_name(code_name: str, users: List[str]) -> Any:
+ accessgroup = AccessGroup.objects.get(code_name=code_name)
+
+ for username in users:
+ try:
+ owner = Owner.objects.get(user__username=username)
+ accessgroup.users.add(owner)
+ except Owner.DoesNotExist:
+ pass
+ return accessgroup
+
+ @staticmethod
+ def remove_users_by_name(code_name: str, users: List[str]) -> Any:
+ accessgroup = AccessGroup.objects.get(code_name=code_name)
+
+ for username in users:
+ try:
+ owner = Owner.objects.get(user__username=username)
+ if owner in accessgroup.users.all():
+ accessgroup.users.remove(owner)
+ except Owner.DoesNotExist:
+ pass
+ return accessgroup
diff --git a/src/apps/authentication/services/users/populator.py b/src/apps/authentication/services/users/populator.py
new file mode 100644
index 0000000000..bdc00134fb
--- /dev/null
+++ b/src/apps/authentication/services/users/populator.py
@@ -0,0 +1,213 @@
+from typing import Any, Dict, List, Optional
+
+from django.conf import settings
+from django.contrib.sites.models import Site
+from django.core.exceptions import ObjectDoesNotExist
+
+from ...models import AccessGroup, Owner
+from ...models.utils import AFFILIATION_STAFF, DEFAULT_AFFILIATION
+from ..core import USER_LDAP_MAPPING_ATTRIBUTES
+from ..ldap_client import get_ldap_conn, get_ldap_entry
+
+
+class UserPopulator:
+ """
+ Handles the population of User and Owner models from external sources (CAS, LDAP).
+ """
+
+ def __init__(self, user: Any):
+ self.user = user
+ # Ensure owner exists
+ if not hasattr(self.user, "owner"):
+ Owner.objects.create(user=self.user)
+ self.owner = self.user.owner
+
+ def run(self, source: str, attributes: Optional[Dict[str, Any]] = None) -> None:
+ """
+ Main entry point to populate user data.
+ :param source: 'CAS', 'LDAP', 'Shibboleth', or 'OIDC'
+ :param attributes: Dictionary of attributes (from CAS, Shibboleth headers, or OIDC claims)
+ """
+ self.owner.auth_type = source
+ self._delete_synchronized_access_groups()
+
+ if source == "CAS" and attributes:
+ self._populate_from_cas(attributes)
+ elif source == "LDAP":
+ self._populate_from_ldap()
+ elif source == "Shibboleth" and attributes:
+ self._populate_from_shibboleth(attributes)
+ elif source == "OIDC" and attributes:
+ self._populate_from_oidc(attributes)
+
+ self.owner.save()
+ self.user.save()
+
+ def _delete_synchronized_access_groups(self) -> None:
+ """Remove groups that are marked for auto-sync."""
+ groups_to_sync = self.owner.accessgroups.filter(auto_sync=True)
+ if groups_to_sync.exists():
+ self.owner.accessgroups.remove(*groups_to_sync)
+
+ def _populate_from_cas(self, attributes: Dict[str, Any]) -> None:
+ """Map CAS attributes to User/Owner."""
+ self.owner.affiliation = attributes.get("primaryAffiliation", DEFAULT_AFFILIATION)
+
+ # Handle affiliations list for group creation/staff status
+ affiliations = attributes.get("affiliation", [])
+ if isinstance(affiliations, str):
+ affiliations = [affiliations]
+
+ self._process_affiliations(affiliations)
+
+ # Handle explicit groups
+ groups = attributes.get("groups", [])
+ if isinstance(groups, str):
+ groups = [groups]
+ self._assign_access_groups(groups)
+
+ def _populate_from_shibboleth(self, attributes: Dict[str, Any]) -> None:
+ """Map Shibboleth attributes to User/Owner."""
+ # attributes keys are our internal field names (e.g. 'affiliation', 'first_name')
+ # because the view maps headers to these names before calling this.
+
+ if "first_name" in attributes:
+ self.user.first_name = attributes["first_name"]
+ if "last_name" in attributes:
+ self.user.last_name = attributes["last_name"]
+ if "email" in attributes:
+ self.user.email = attributes["email"]
+
+ self.owner.affiliation = attributes.get("affiliation", DEFAULT_AFFILIATION)
+
+ affiliations = attributes.get("affiliations", [])
+ if isinstance(affiliations, str):
+ if ";" in affiliations:
+ affiliations = affiliations.split(";")
+ else:
+ affiliations = [affiliations]
+
+ self._process_affiliations(affiliations)
+
+ def _populate_from_oidc(self, attributes: Dict[str, Any]) -> None:
+ """Map OIDC claims to User/Owner."""
+ given_name_claim = getattr(settings, "OIDC_CLAIM_GIVEN_NAME", "given_name")
+ family_name_claim = getattr(settings, "OIDC_CLAIM_FAMILY_NAME", "family_name")
+
+ self.user.first_name = attributes.get(given_name_claim, self.user.first_name)
+ self.user.last_name = attributes.get(family_name_claim, self.user.last_name)
+ self.user.email = attributes.get("email", self.user.email)
+
+ self.owner.affiliation = getattr(
+ settings, "OIDC_DEFAULT_AFFILIATION", DEFAULT_AFFILIATION
+ )
+
+ # OIDC default access groups
+ oidc_groups = getattr(settings, "OIDC_DEFAULT_ACCESS_GROUP_CODE_NAMES", [])
+ self._assign_access_groups(oidc_groups)
+
+ # Is user staff?
+ if self.owner.affiliation in AFFILIATION_STAFF:
+ self.user.is_staff = True
+
+ def _populate_from_ldap(self) -> None:
+ """Fetch and map LDAP attributes to User/Owner."""
+ if not self._is_ldap_configured():
+ return
+
+ conn = get_ldap_conn()
+ if not conn:
+ return
+
+ entry = get_ldap_entry(conn, self.user.username)
+ if entry:
+ self._apply_ldap_entry(entry)
+
+ def _apply_ldap_entry(self, entry: Any) -> None:
+ self.user.email = self._get_ldap_value(entry, "mail", "")
+ self.user.first_name = self._get_ldap_value(entry, "first_name", "")
+ self.user.last_name = self._get_ldap_value(entry, "last_name", "")
+ self.user.save()
+
+ self.owner.affiliation = self._get_ldap_value(
+ entry, "primaryAffiliation", DEFAULT_AFFILIATION
+ )
+ self.owner.establishment = self._get_ldap_value(entry, "establishment", "")
+ self.owner.save()
+
+ affiliations = self._get_ldap_value(entry, "affiliations", [])
+ if isinstance(affiliations, str):
+ affiliations = [affiliations]
+ self._process_affiliations(affiliations)
+
+ # Groups from LDAP
+ ldap_group_attr = USER_LDAP_MAPPING_ATTRIBUTES.get("groups")
+ groups_element = []
+ if ldap_group_attr and entry[ldap_group_attr]:
+ groups_element = entry[ldap_group_attr].values
+
+ self._assign_access_groups(groups_element)
+
+ def _process_affiliations(self, affiliations: List[str]) -> None:
+ """Process list of affiliations to set staff status and create AccessGroups."""
+ create_group_from_aff = getattr(settings, "CREATE_GROUP_FROM_AFFILIATION", False)
+ current_site = Site.objects.get_current()
+
+ for affiliation in affiliations:
+ if affiliation in AFFILIATION_STAFF:
+ self.user.is_staff = True
+
+ if create_group_from_aff:
+ accessgroup, created = AccessGroup.objects.get_or_create(
+ code_name=affiliation
+ )
+ if created:
+ accessgroup.display_name = affiliation
+ accessgroup.auto_sync = True
+ accessgroup.save()
+
+ accessgroup.sites.add(current_site)
+ self.owner.accessgroups.add(accessgroup)
+
+ def _assign_access_groups(self, groups: List[str]) -> None:
+ """Assign AccessGroups based on group codes."""
+ create_group_from_groups = getattr(settings, "CREATE_GROUP_FROM_GROUPS", False)
+ current_site = Site.objects.get_current()
+
+ for group_code in groups:
+ # We assume GROUP_STAFF is same as AFFILIATION_STAFF
+ if group_code in AFFILIATION_STAFF:
+ self.user.is_staff = True
+
+ if create_group_from_groups:
+ accessgroup, created = AccessGroup.objects.get_or_create(
+ code_name=group_code
+ )
+ if created:
+ accessgroup.display_name = group_code
+ accessgroup.auto_sync = True
+ accessgroup.save()
+ accessgroup.sites.add(current_site)
+ self.owner.accessgroups.add(accessgroup)
+ else:
+ try:
+ accessgroup = AccessGroup.objects.get(code_name=group_code)
+ self.owner.accessgroups.add(accessgroup)
+ except ObjectDoesNotExist:
+ pass
+
+ def _get_ldap_value(self, entry: Any, attribute: str, default: Any) -> Any:
+ mapping = USER_LDAP_MAPPING_ATTRIBUTES.get(attribute)
+ if mapping and entry[mapping]:
+ if attribute == "last_name" and isinstance(entry[mapping].value, list):
+ return entry[mapping].value[0]
+ elif attribute == "affiliations":
+ return entry[mapping].values
+ else:
+ return entry[mapping].value
+ return default
+
+ @staticmethod
+ def _is_ldap_configured() -> bool:
+ ldap_config = getattr(settings, "LDAP_SERVER", {})
+ return bool(ldap_config.get("url"))
diff --git a/src/apps/authentication/tests/__init__.py b/src/apps/authentication/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/apps/authentication/tests/test_models.py b/src/apps/authentication/tests/test_models.py
new file mode 100644
index 0000000000..36ba6413d5
--- /dev/null
+++ b/src/apps/authentication/tests/test_models.py
@@ -0,0 +1,32 @@
+from django.contrib.auth import get_user_model
+from django.test import TestCase
+
+
+class TestOwnerModel(TestCase):
+ def setUp(self):
+ self.User = get_user_model()
+
+ def test_owner_creation_signal(self):
+ user = self.User.objects.create(username="ownertest")
+ self.assertTrue(hasattr(user, "owner"))
+ self.assertEqual(user.owner.user, user)
+
+ def test_hashkey_generation(self):
+ user = self.User.objects.create(username="hashkeytest")
+ owner = user.owner
+ # hashkey is generated on save if empty
+ owner.save()
+ self.assertTrue(len(owner.hashkey) > 0)
+
+ old_hash = owner.hashkey
+ owner.save()
+ self.assertEqual(owner.hashkey, old_hash)
+
+ def test_str_representation(self):
+ user = self.User.objects.create(
+ username="strtest", first_name="John", last_name="Doe"
+ )
+ # Depending on HIDE_USERNAME settings, output changes.
+ # Default seems to be HIDE_USERNAME=False based on previous file read?
+ # Let's just check it contains the name
+ self.assertIn("John Doe", str(user.owner))
diff --git a/src/apps/authentication/tests/test_scenarios.py b/src/apps/authentication/tests/test_scenarios.py
new file mode 100644
index 0000000000..c39177d539
--- /dev/null
+++ b/src/apps/authentication/tests/test_scenarios.py
@@ -0,0 +1,69 @@
+import sys
+from importlib import reload
+
+from django.conf import settings
+from django.contrib.auth import views as auth_views
+from django.test import TestCase, override_settings
+from django.urls import clear_url_caches, resolve
+from django_cas_ng import views as cas_views
+
+
+def reload_urlconf():
+ clear_url_caches()
+ if settings.ROOT_URLCONF in sys.modules:
+ reload(sys.modules[settings.ROOT_URLCONF])
+
+
+class AuthenticationScenariosTests(TestCase):
+
+ def tearDown(self):
+ # Reset to default state after each test to avoid side effects
+ clear_url_caches()
+ reload_urlconf()
+
+ @override_settings(
+ USE_CAS=True,
+ USE_LOCAL_AUTH=False,
+ AUTHENTICATION_BACKENDS=["django_cas_ng.backends.CASBackend"],
+ CAS_SERVER_URL="https://cas.example.com",
+ )
+ def test_university_mode_cas_only(self):
+ """
+ Scenario: University / Production Mode
+ - CAS is Enabled
+ - Local Auth is Disabled
+
+ Expectation:
+ - /accounts/login resolves to CAS login view
+ """
+ reload_urlconf()
+
+ # 1. Verify URL resolution
+ resolver_match = resolve("/accounts/login")
+ self.assertEqual(resolver_match.func.view_class, cas_views.LoginView)
+
+ resolver_match_logout = resolve("/accounts/logout")
+ self.assertEqual(resolver_match_logout.func.view_class, cas_views.LogoutView)
+
+ @override_settings(
+ USE_CAS=False,
+ USE_LOCAL_AUTH=True,
+ AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.ModelBackend"],
+ )
+ def test_local_mode_default(self):
+ """
+ Scenario: Local Development Mode
+ - CAS is Disabled
+ - Local Auth is Enabled
+
+ Expectation:
+ - /accounts/login resolves to Django standard LoginView
+ """
+ reload_urlconf()
+
+ # 1. Verify URL resolution
+ resolver_match = resolve("/accounts/login")
+ self.assertEqual(resolver_match.func.view_class, auth_views.LoginView)
+
+ resolver_match_logout = resolve("/accounts/logout")
+ self.assertEqual(resolver_match_logout.func.view_class, auth_views.LogoutView)
diff --git a/src/apps/authentication/tests/test_services.py b/src/apps/authentication/tests/test_services.py
new file mode 100644
index 0000000000..1726631d6b
--- /dev/null
+++ b/src/apps/authentication/tests/test_services.py
@@ -0,0 +1,54 @@
+from unittest.mock import MagicMock, patch
+
+from django.contrib.auth import get_user_model
+from django.test import TestCase, override_settings
+
+from ..services import UserPopulator, verify_cas_ticket
+
+User = get_user_model()
+
+
+class TestUserPopulator(TestCase):
+ def setUp(self):
+ self.user = User.objects.create(username="testuser", email="test@example.com")
+ self.populator = UserPopulator(self.user)
+
+ def test_init_creates_owner(self):
+ user_no_owner = User.objects.create(username="noowner")
+ UserPopulator(user_no_owner)
+ self.assertTrue(hasattr(user_no_owner, "owner"))
+ self.assertIsNotNone(user_no_owner.owner)
+
+ def test_populate_from_cas_basic(self):
+ attributes = {
+ "primaryAffiliation": "student",
+ "affiliation": ["student"],
+ "groups": ["group1"],
+ "mail": "test@example.com",
+ }
+ self.populator.run("CAS", attributes)
+
+ self.user.refresh_from_db()
+ self.assertEqual(self.user.owner.auth_type, "CAS")
+ self.assertEqual(self.user.owner.affiliation, "student")
+
+ # Check groups - depends on create_group settings, but let's assume default behaviour
+ # or mock settings.
+ # By default CREATE_GROUP_FROM_GROUPS might be False.
+ # Let's verify owner attribute is updated.
+
+ @override_settings(POPULATE_USER="CAS")
+ @patch("src.apps.authentication.services.users.populator.UserPopulator.run")
+ def test_verify_cas_ticket_calls_populator(self, mock_run):
+ with patch(
+ "src.apps.authentication.services.providers.cas.get_cas_client"
+ ) as mock_client:
+ mock_cas = MagicMock()
+ mock_cas.verify_ticket.return_value = ("casuser", {"attr": "val"}, None)
+ mock_client.return_value = mock_cas
+
+ user = verify_cas_ticket("ticket", "service_url")
+
+ self.assertIsNotNone(user)
+ self.assertEqual(user.username, "casuser")
+ mock_run.assert_called_with("CAS", {"attr": "val"})
diff --git a/src/apps/authentication/tests/test_views.py b/src/apps/authentication/tests/test_views.py
new file mode 100644
index 0000000000..236cc341cf
--- /dev/null
+++ b/src/apps/authentication/tests/test_views.py
@@ -0,0 +1,105 @@
+from unittest.mock import MagicMock, patch
+
+from django.contrib.auth import get_user_model
+from django.urls import reverse
+from rest_framework import status
+from rest_framework.test import APITestCase
+
+from ..models import Owner
+
+User = get_user_model()
+
+
+class LoginViewTests(APITestCase):
+ def setUp(self):
+ self.username = "testuser"
+ self.password = "testpass123"
+ self.user = User.objects.create_user(
+ username=self.username, password=self.password
+ )
+ Owner.objects.get_or_create(user=self.user)
+ self.url = reverse("token_obtain_pair")
+
+ def test_login_success(self):
+ data = {"username": self.username, "password": self.password}
+ response = self.client.post(self.url, data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIn("access", response.data)
+ self.assertIn("refresh", response.data)
+
+ def test_login_failure(self):
+ data = {"username": self.username, "password": "wrongpassword"}
+ response = self.client.post(self.url, data)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
+
+class ShibbolethLoginViewTests(APITestCase):
+ def setUp(self):
+ self.url = reverse("token_obtain_pair_shibboleth")
+ self.remote_user_header = "REMOTE_USER" # Default setting
+
+ def test_shibboleth_success(self):
+ headers = {
+ "REMOTE_USER": "shibuser",
+ "HTTP_SHIBBOLETH_MAIL": "shib@example.com", # This might need adjustment based on how code reads it but let's try standard header simulation
+ }
+ # Assuming no security header required by default test settings or mocked
+
+ response = self.client.get(self.url, **headers)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ self.assertTrue(User.objects.filter(username="shibuser").exists())
+
+ def test_shibboleth_missing_header(self):
+ response = self.client.get(self.url)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
+ def test_shibboleth_security_check_fail(self):
+ with self.settings(
+ SHIB_SECURE_HEADER="HTTP_X_SECURE", SHIB_SECURE_VALUE="secret"
+ ):
+ headers = {
+ "HTTP_REMOTE_USER": "shibuser",
+ }
+ response = self.client.get(self.url, **headers)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+
+class OIDCLoginViewTests(APITestCase):
+ def setUp(self):
+ self.url = reverse("token_obtain_pair_oidc")
+
+ @patch("requests.post")
+ @patch("requests.get")
+ def test_oidc_success(self, mock_get, mock_post):
+ # Mock Token response
+ mock_token_resp = MagicMock()
+ mock_token_resp.json.return_value = {"access_token": "fake_access_token"}
+ mock_token_resp.status_code = 200
+ mock_post.return_value = mock_token_resp
+
+ # Mock UserInfo response
+ mock_user_resp = MagicMock()
+ mock_user_resp.json.return_value = {
+ "preferred_username": "oidcuser",
+ "email": "oidc@example.com",
+ "given_name": "OIDC",
+ "family_name": "User",
+ }
+ mock_user_resp.status_code = 200
+ mock_get.return_value = mock_user_resp
+
+ data = {"code": "auth_code", "redirect_uri": "http://localhost/callback"}
+
+ # We need to ensure OIDC settings are present
+ with self.settings(
+ OIDC_OP_TOKEN_ENDPOINT="http://oidc/token",
+ OIDC_OP_USER_ENDPOINT="http://oidc/userinfo",
+ OIDC_RP_CLIENT_ID="client",
+ OIDC_RP_CLIENT_SECRET="secret",
+ ):
+ response = self.client.post(self.url, data)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertTrue(User.objects.filter(username="oidcuser").exists())
diff --git a/src/apps/authentication/urls.py b/src/apps/authentication/urls.py
new file mode 100644
index 0000000000..66014efb38
--- /dev/null
+++ b/src/apps/authentication/urls.py
@@ -0,0 +1,75 @@
+import django_cas_ng.views
+from django.conf import settings
+from django.urls import include, path
+from rest_framework.routers import DefaultRouter
+from rest_framework_simplejwt.views import (
+ TokenRefreshView,
+ TokenVerifyView,
+)
+
+from .views import (
+ AccessGroupViewSet,
+ CASLoginView,
+ GroupViewSet,
+ LoginConfigView,
+ LoginView,
+ LogoutInfoView,
+ OIDCLoginView,
+ OwnerViewSet,
+ ShibbolethLoginView,
+ SiteViewSet,
+ UserMeView,
+ UserViewSet,
+)
+
+router = DefaultRouter()
+router.register(r"owners", OwnerViewSet)
+router.register(r"users", UserViewSet)
+router.register(r"groups", GroupViewSet)
+router.register(r"sites", SiteViewSet)
+router.register(r"access-groups", AccessGroupViewSet)
+
+urlpatterns = [
+ path("", include(router.urls)),
+ path("token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),
+ path("token/verify/", TokenVerifyView.as_view(), name="token_verify"),
+ path("users/me/", UserMeView.as_view(), name="user_me"),
+ path("logout-info/", LogoutInfoView.as_view(), name="api_logout_info"),
+ path("config/", LoginConfigView.as_view(), name="api_login_config"),
+]
+
+if settings.USE_LOCAL_AUTH:
+ urlpatterns.append(path("token/", LoginView.as_view(), name="token_obtain_pair"))
+
+if settings.USE_CAS:
+ urlpatterns.append(
+ path("token/cas/", CASLoginView.as_view(), name="token_obtain_pair_cas")
+ )
+ urlpatterns.append(
+ path(
+ "accounts/login",
+ django_cas_ng.views.LoginView.as_view(),
+ name="cas_ng_login",
+ )
+ )
+ urlpatterns.append(
+ path(
+ "accounts/logout",
+ django_cas_ng.views.LogoutView.as_view(),
+ name="cas_ng_logout",
+ )
+ )
+
+if settings.USE_SHIB:
+ urlpatterns.append(
+ path(
+ "token/shibboleth/",
+ ShibbolethLoginView.as_view(),
+ name="token_obtain_pair_shibboleth",
+ )
+ )
+
+if settings.USE_OIDC:
+ urlpatterns.append(
+ path("token/oidc/", OIDCLoginView.as_view(), name="token_obtain_pair_oidc")
+ )
diff --git a/src/apps/authentication/views/__init__.py b/src/apps/authentication/views/__init__.py
new file mode 100644
index 0000000000..d19d6db5a2
--- /dev/null
+++ b/src/apps/authentication/views/__init__.py
@@ -0,0 +1,25 @@
+from .config_views import LoginConfigView, LogoutInfoView
+from .login_views import CASLoginView, LoginView, OIDCLoginView, ShibbolethLoginView
+from .model_views import (
+ AccessGroupViewSet,
+ GroupViewSet,
+ OwnerViewSet,
+ SiteViewSet,
+ UserMeView,
+ UserViewSet,
+)
+
+__all__ = [
+ "LoginView",
+ "CASLoginView",
+ "ShibbolethLoginView",
+ "OIDCLoginView",
+ "UserMeView",
+ "OwnerViewSet",
+ "UserViewSet",
+ "GroupViewSet",
+ "SiteViewSet",
+ "AccessGroupViewSet",
+ "LogoutInfoView",
+ "LoginConfigView",
+]
diff --git a/src/apps/authentication/views/config_views.py b/src/apps/authentication/views/config_views.py
new file mode 100644
index 0000000000..92105edd50
--- /dev/null
+++ b/src/apps/authentication/views/config_views.py
@@ -0,0 +1,93 @@
+from django.conf import settings
+from drf_spectacular.utils import extend_schema, inline_serializer
+from rest_framework import serializers
+from rest_framework.permissions import AllowAny
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+try:
+ from django_cas_ng.utils import get_cas_client
+except ImportError:
+ get_cas_client = None
+
+
+class LogoutInfoView(APIView):
+ """
+ Returns the logout URLs for external providers.
+ The frontend must call this endpoint to know where
+ to redirect the user after deleting the local JWT token.
+ """
+
+ permission_classes = [AllowAny]
+
+ @extend_schema(
+ responses=inline_serializer(
+ name="LogoutInfoResponse",
+ fields={
+ "local": serializers.CharField(allow_null=True),
+ "cas": serializers.CharField(allow_null=True),
+ "shibboleth": serializers.CharField(allow_null=True),
+ "oidc": serializers.CharField(allow_null=True),
+ },
+ )
+ )
+ def get(self, request):
+ data = {"local": None, "cas": None, "shibboleth": None, "oidc": None}
+
+ if getattr(settings, "USE_CAS", False) and get_cas_client:
+ try:
+ client = get_cas_client(service_url=request.build_absolute_uri("/"))
+ data["cas"] = client.get_logout_url(
+ redirect_url=request.build_absolute_uri("/")
+ )
+ except Exception:
+ pass
+
+ if getattr(settings, "USE_SHIB", False):
+ shib_logout = getattr(settings, "SHIB_LOGOUT_URL", "")
+ if shib_logout:
+ return_url = request.build_absolute_uri("/")
+ data["shibboleth"] = f"{shib_logout}?return={return_url}"
+
+ if getattr(settings, "USE_OIDC", False):
+ oidc_logout = getattr(settings, "OIDC_OP_LOGOUT_ENDPOINT", "")
+ if oidc_logout:
+ data["oidc"] = oidc_logout
+
+ return Response(data)
+
+
+class LoginConfigView(APIView):
+ """
+ Returns the configuration of active authentication methods.
+ Allows the frontend to know which login buttons to display.
+ """
+
+ permission_classes = [AllowAny]
+
+ @extend_schema(
+ responses={
+ 200: inline_serializer(
+ name="LoginConfigResponse",
+ fields={
+ "use_local": serializers.BooleanField(),
+ "use_cas": serializers.BooleanField(),
+ "use_shibboleth": serializers.BooleanField(),
+ "use_oidc": serializers.BooleanField(),
+ "shibboleth_name": serializers.CharField(),
+ "oidc_name": serializers.CharField(),
+ },
+ )
+ }
+ )
+ def get(self, request):
+ return Response(
+ {
+ "use_local": getattr(settings, "USE_LOCAL_AUTH", True),
+ "use_cas": getattr(settings, "USE_CAS", False),
+ "use_shibboleth": getattr(settings, "USE_SHIB", False),
+ "use_oidc": getattr(settings, "USE_OIDC", False),
+ "shibboleth_name": getattr(settings, "SHIB_NAME", "Shibboleth"),
+ "oidc_name": getattr(settings, "OIDC_NAME", "OpenID Connect"),
+ }
+ )
diff --git a/src/apps/authentication/views/login_views.py b/src/apps/authentication/views/login_views.py
new file mode 100644
index 0000000000..e2764ef35f
--- /dev/null
+++ b/src/apps/authentication/views/login_views.py
@@ -0,0 +1,123 @@
+import logging
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import status
+from rest_framework.permissions import AllowAny
+from rest_framework.response import Response
+from rest_framework.views import APIView
+from rest_framework_simplejwt.views import TokenObtainPairView
+
+from ..serializers.CASTokenObtainPairSerializer import CASTokenObtainPairSerializer
+from ..serializers.CustomTokenObtainPairSerializer import (
+ CustomTokenObtainPairSerializer,
+)
+from ..serializers.ExternalAuthSerializers import (
+ OIDCTokenObtainSerializer,
+ ShibbolethTokenObtainSerializer,
+)
+from ..services import OIDCService, ShibbolethService
+
+logger = logging.getLogger(__name__)
+
+
+class LoginView(TokenObtainPairView):
+ """
+ **Authentication Endpoint**
+ Accepts a username and password and returns a pair of JWT tokens.
+ """
+
+ serializer_class = CustomTokenObtainPairSerializer
+
+
+class CASLoginView(APIView):
+ """
+ **CAS Authentication Endpoint**
+ Exchange a valid CAS ticket for a JWT token pair.
+ """
+
+ permission_classes = [AllowAny]
+ serializer_class = CASTokenObtainPairSerializer
+
+ @extend_schema(
+ request=CASTokenObtainPairSerializer, responses=CASTokenObtainPairSerializer
+ )
+ def post(self, request, *args, **kwargs):
+ serializer = self.serializer_class(data=request.data)
+ if serializer.is_valid():
+ return Response(serializer.validated_data, status=status.HTTP_200_OK)
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+
+
+class ShibbolethLoginView(APIView):
+ """
+ **Shibboleth Authentication Endpoint**
+
+ This view must be protected by the Shibboleth SP (Apache/Nginx)
+ which injects the headers.
+ It reads the headers (REMOTE_USER, etc.), creates or updates the user
+ locally according to the logic defined in the ShibbolethService and returns JWTs.
+ """
+
+ permission_classes = [AllowAny]
+ serializer_class = ShibbolethTokenObtainSerializer
+ service = ShibbolethService()
+
+ @extend_schema(request=ShibbolethTokenObtainSerializer)
+ def get(self, request, *args, **kwargs):
+ try:
+ tokens = self.service.process_request(request)
+ return Response(tokens, status=status.HTTP_200_OK)
+ except PermissionError as e:
+ return Response({"error": str(e)}, status=status.HTTP_403_FORBIDDEN)
+ except ValueError as e:
+ return Response(
+ {"error": f"{str(e)} Shibboleth misconfigured?"},
+ status=status.HTTP_401_UNAUTHORIZED,
+ )
+ except Exception as e:
+ logger.error(f"Shibboleth Login failed: {e}")
+ return Response(
+ {"error": "Internal Server Error during Shibboleth login."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+
+class OIDCLoginView(APIView):
+ """
+ **OIDC Authentication Endpoint**
+
+ Exchanges an 'authorization_code' for OIDC tokens via the Provider,
+ retrieves user information (UserInfo),
+ updates the local database, and returns JWTs.
+ """
+
+ permission_classes = [AllowAny]
+ serializer_class = OIDCTokenObtainSerializer
+ service = OIDCService()
+
+ @extend_schema(request=OIDCTokenObtainSerializer)
+ def post(self, request, *args, **kwargs):
+ serializer = self.serializer_class(data=request.data)
+ if not serializer.is_valid():
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+
+ code = serializer.validated_data["code"]
+ redirect_uri = serializer.validated_data["redirect_uri"]
+
+ try:
+ tokens = self.service.process_code(code, redirect_uri)
+ return Response(tokens, status=status.HTTP_200_OK)
+ except EnvironmentError as e:
+ return Response(
+ {"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
+ )
+ except ValueError as e:
+ return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
+ except ConnectionError as e:
+ return Response({"error": str(e)}, status=status.HTTP_401_UNAUTHORIZED)
+ except Exception as e:
+ logger.error(f"OIDC Login failed: {e}")
+ return Response(
+ {"error": "Internal Server Error during OIDC login."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
diff --git a/src/apps/authentication/views/model_views.py b/src/apps/authentication/views/model_views.py
new file mode 100644
index 0000000000..fe8d67e811
--- /dev/null
+++ b/src/apps/authentication/views/model_views.py
@@ -0,0 +1,196 @@
+from django.contrib.auth import get_user_model
+from django.contrib.auth.models import Group
+from django.contrib.sites.models import Site
+from drf_spectacular.utils import extend_schema
+from rest_framework import filters, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from ..models.AccessGroup import AccessGroup
+from ..models.Owner import Owner
+from ..serializers.AccessGroupSerializer import AccessGroupSerializer
+from ..serializers.GroupSerializer import GroupSerializer
+from ..serializers.OwnerSerializer import OwnerSerializer, OwnerWithGroupsSerializer
+from ..serializers.SiteSerializer import SiteSerializer
+from ..serializers.UserSerializer import UserSerializer
+from ..services import AccessGroupService
+
+User = get_user_model()
+
+
+class UserMeView(APIView):
+ """
+ **Current User Profile**
+ Returns the profile information of the currently authenticated user.
+ """
+
+ permission_classes = [IsAuthenticated]
+
+ @extend_schema(responses=UserSerializer)
+ def get(self, request):
+ serializer = UserSerializer(request.user)
+ data = serializer.data
+ if hasattr(request.user, "owner"):
+ data["affiliation"] = request.user.owner.affiliation
+ data["establishment"] = request.user.owner.establishment
+
+ return Response(data, status=status.HTTP_200_OK)
+
+
+class OwnerViewSet(viewsets.ModelViewSet):
+ """
+ ViewSet for managing Owner profiles.
+ Includes actions to manage access groups for a user.
+ """
+
+ queryset = Owner.objects.all().order_by("-user")
+ serializer_class = OwnerSerializer
+ permission_classes = [IsAuthenticated]
+
+ @action(detail=False, methods=["post"], url_path="set-user-accessgroup")
+ def set_user_accessgroup(self, request):
+ """
+ Equivalent of accessgroups_set_user_accessgroup.
+ Assigns AccessGroups to a user via their username.
+ """
+ username = request.data.get("username")
+ groups = request.data.get("groups")
+
+ if not username or groups is None:
+ return Response(
+ {"error": "Missing username or groups"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ try:
+ owner = AccessGroupService.set_user_accessgroup(username, groups)
+ serializer = OwnerWithGroupsSerializer(
+ instance=owner, context={"request": request}
+ )
+ return Response(serializer.data)
+ except Owner.DoesNotExist:
+ return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)
+
+ @action(detail=False, methods=["post"], url_path="remove-user-accessgroup")
+ def remove_user_accessgroup(self, request):
+ """
+ Equivalent of accessgroups_remove_user_accessgroup.
+ Removes AccessGroups from a user via their username.
+ """
+ username = request.data.get("username")
+ groups = request.data.get("groups")
+
+ if not username or groups is None:
+ return Response(
+ {"error": "Missing username or groups"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ try:
+ owner = AccessGroupService.remove_user_accessgroup(username, groups)
+ serializer = OwnerWithGroupsSerializer(
+ instance=owner, context={"request": request}
+ )
+ return Response(serializer.data)
+ except Owner.DoesNotExist:
+ return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)
+
+
+class UserViewSet(viewsets.ModelViewSet):
+ """
+ ViewSet for managing standard Django Users.
+ """
+
+ queryset = User.objects.all().order_by("-date_joined")
+ serializer_class = UserSerializer
+ filterset_fields = ["id", "username", "email"]
+ permission_classes = [IsAuthenticated]
+ filter_backends = [filters.SearchFilter] # Ajout du backend de recherche
+ search_fields = ["username", "first_name", "last_name", "email"]
+
+
+class GroupViewSet(viewsets.ModelViewSet):
+ """
+ ViewSet for managing Django Groups (Permissions).
+ """
+
+ queryset = Group.objects.all()
+ serializer_class = GroupSerializer
+ permission_classes = [IsAuthenticated]
+
+
+class SiteViewSet(viewsets.ModelViewSet):
+ """
+ ViewSet for managing Sites.
+ """
+
+ queryset = Site.objects.all()
+ serializer_class = SiteSerializer
+ permission_classes = [IsAuthenticated]
+
+
+class AccessGroupViewSet(viewsets.ModelViewSet):
+ """
+ ViewSet for managing Access Groups.
+ Includes actions to add/remove users by code name.
+ """
+
+ queryset = AccessGroup.objects.all()
+ serializer_class = AccessGroupSerializer
+ filterset_fields = ["id", "display_name", "code_name"]
+ permission_classes = [IsAuthenticated]
+
+ @action(detail=False, methods=["post"], url_path="set-users-by-name")
+ def set_users_by_name(self, request):
+ """
+ Equivalent of accessgroups_set_users_by_name.
+ Adds a list of users (by username) to an AccessGroup (by code_name).
+ """
+ code_name = request.data.get("code_name")
+ users = request.data.get("users")
+
+ if not code_name or users is None:
+ return Response(
+ {"error": "Missing code_name or users"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ try:
+ accessgroup = AccessGroupService.set_users_by_name(code_name, users)
+ return Response(
+ AccessGroupSerializer(
+ instance=accessgroup, context={"request": request}
+ ).data
+ )
+ except AccessGroup.DoesNotExist:
+ return Response(
+ {"error": "AccessGroup not found"}, status=status.HTTP_404_NOT_FOUND
+ )
+
+ @action(detail=False, methods=["post"], url_path="remove-users-by-name")
+ def remove_users_by_name(self, request):
+ """
+ Equivalent of accessgroups_remove_users_by_name.
+ Removes a list of users (by username) from an AccessGroup (by code_name).
+ """
+ code_name = request.data.get("code_name")
+ users = request.data.get("users")
+ if not code_name or users is None:
+ return Response(
+ {"error": "Missing code_name or users"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ try:
+ accessgroup = AccessGroupService.remove_users_by_name(code_name, users)
+ return Response(
+ AccessGroupSerializer(
+ instance=accessgroup, context={"request": request}
+ ).data
+ )
+ except AccessGroup.DoesNotExist:
+ return Response(
+ {"error": "AccessGroup not found"}, status=status.HTTP_404_NOT_FOUND
+ )
diff --git a/src/apps/info/urls.py b/src/apps/info/urls.py
new file mode 100644
index 0000000000..2c20694794
--- /dev/null
+++ b/src/apps/info/urls.py
@@ -0,0 +1,7 @@
+from django.urls import path
+
+from .views import SystemInfoView
+
+urlpatterns = [
+ path("", SystemInfoView.as_view(), name="system_info"),
+]
diff --git a/src/apps/info/views.py b/src/apps/info/views.py
new file mode 100644
index 0000000000..fdd742dc1c
--- /dev/null
+++ b/src/apps/info/views.py
@@ -0,0 +1,35 @@
+from django.conf import settings
+from drf_spectacular.utils import extend_schema
+from rest_framework.permissions import AllowAny
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+
+@extend_schema(
+ summary="System Information",
+ description="Returns the project name and current version",
+ responses={
+ 200: {
+ "type": "object",
+ "properties": {
+ "project": {"type": "string", "example": "POD V5"},
+ "version": {"type": "string", "example": "5.0.0"},
+ },
+ }
+ },
+)
+class SystemInfoView(APIView):
+ """
+ Simple view to return public system information,
+ including the current version.
+ """
+
+ permission_classes = [AllowAny]
+
+ def get(self, request):
+ return Response(
+ {
+ "project": "POD V5",
+ "version": settings.POD_VERSION,
+ }
+ )
diff --git a/src/apps/utils/models/CustomImageModel.py b/src/apps/utils/models/CustomImageModel.py
new file mode 100644
index 0000000000..2e12cb4f4d
--- /dev/null
+++ b/src/apps/utils/models/CustomImageModel.py
@@ -0,0 +1,66 @@
+import mimetypes
+import os
+
+from django.conf import settings
+from django.db import models
+from django.utils.text import slugify
+from django.utils.translation import gettext_lazy as _
+
+FILES_DIR = getattr(settings, "FILES_DIR", "files")
+
+
+def get_upload_path_files(instance, filename) -> str:
+ fname, dot, extension = filename.rpartition(".")
+ try:
+ fname.index("/")
+ return os.path.join(
+ FILES_DIR,
+ "%s/%s.%s"
+ % (
+ os.path.dirname(fname),
+ slugify(os.path.basename(fname)),
+ extension,
+ ),
+ )
+ except ValueError:
+ return os.path.join(FILES_DIR, "%s.%s" % (slugify(fname), extension))
+
+
+class CustomImageModel(models.Model):
+ """Esup-Pod custom image Model."""
+
+ file = models.ImageField(
+ _("Image"),
+ null=True,
+ upload_to=get_upload_path_files,
+ blank=True,
+ max_length=255,
+ )
+
+ @property
+ def file_type(self) -> str:
+ filetype = mimetypes.guess_type(self.file.path)[0]
+ if filetype is None:
+ fname, dot, extension = self.file.path.rpartition(".")
+ filetype = extension.lower()
+ return filetype
+
+ file_type.fget.short_description = _("Get the file type")
+
+ @property
+ def file_size(self) -> int:
+ return os.path.getsize(self.file.path)
+
+ file_size.fget.short_description = _("Get the file size")
+
+ @property
+ def name(self) -> str:
+ return os.path.basename(self.file.path)
+
+ name.fget.short_description = _("Get the file name")
+
+ def file_exist(self) -> bool:
+ return self.file and os.path.isfile(self.file.path)
+
+ def __str__(self) -> str:
+ return "%s (%s, %s)" % (self.name, self.file_type, self.file_size)
diff --git a/src/config/__init__.py b/src/config/__init__.py
new file mode 100644
index 0000000000..bff07e70a9
--- /dev/null
+++ b/src/config/__init__.py
@@ -0,0 +1,4 @@
+try:
+ from .django.settings_local import * # noqa: F401, F403
+except ImportError:
+ pass
diff --git a/src/config/asgi.py b/src/config/asgi.py
new file mode 100644
index 0000000000..304da6db4e
--- /dev/null
+++ b/src/config/asgi.py
@@ -0,0 +1,23 @@
+import os
+import sys
+
+from django.core.asgi import get_asgi_application
+
+from config.env import env
+
+try:
+ settings_module = env.str("DJANGO_SETTINGS_MODULE")
+
+ if not settings_module:
+ raise ValueError("DJANGO_SETTINGS_MODULE is set but empty.")
+
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
+ application = get_asgi_application()
+
+except Exception as e:
+ print(
+ f"FATAL ERROR: Failed to initialize the ASGI application. "
+ f"Check that DJANGO_SETTINGS_MODULE is set. Details: {e}",
+ file=sys.stderr,
+ )
+ sys.exit(1)
diff --git a/src/config/django/__init__.py b/src/config/django/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/config/django/base.py b/src/config/django/base.py
new file mode 100644
index 0000000000..7e0b5e16db
--- /dev/null
+++ b/src/config/django/base.py
@@ -0,0 +1,86 @@
+import os
+
+from config.env import BASE_DIR, env
+
+# Lire le fichier .env
+env.read_env(os.path.join(BASE_DIR, ".env"))
+
+# Variables d'environnement essentielles
+POD_VERSION = env("VERSION")
+SECRET_KEY = env("SECRET_KEY")
+
+INSTALLED_APPS = [
+ "django.contrib.admin",
+ "django.contrib.auth",
+ "django.contrib.contenttypes",
+ "django.contrib.sessions",
+ "django.contrib.messages",
+ "django.contrib.sites",
+ "django.contrib.staticfiles",
+ "rest_framework",
+ "rest_framework_simplejwt",
+ "corsheaders",
+ "drf_spectacular",
+ "django_cas_ng",
+ "src.apps.utils",
+ "src.apps.authentication",
+ "src.apps.info",
+]
+
+MIDDLEWARE = [
+ "corsheaders.middleware.CorsMiddleware",
+ "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",
+ "django_cas_ng.middleware.CASMiddleware",
+ "src.apps.authentication.IPRestrictionMiddleware.IPRestrictionMiddleware",
+]
+
+TEMPLATES = [
+ {
+ "BACKEND": "django.template.backends.django.DjangoTemplates",
+ "DIRS": [BASE_DIR / "templates"],
+ "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",
+ ],
+ },
+ },
+]
+
+ROOT_URLCONF = "config.urls"
+WSGI_APPLICATION = "config.wsgi.application"
+ASGI_APPLICATION = "config.asgi.application"
+
+REST_FRAMEWORK = {
+ "DEFAULT_AUTHENTICATION_CLASSES": (
+ "rest_framework_simplejwt.authentication.JWTAuthentication",
+ ),
+ "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
+ "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
+}
+
+STATIC_URL = "/static/"
+STATIC_ROOT = BASE_DIR / "staticfiles"
+
+MEDIA_URL = "/media/"
+MEDIA_ROOT = BASE_DIR / "media"
+
+LANGUAGE_CODE = "en-en"
+TIME_ZONE = "UTC"
+USE_I18N = True
+USE_TZ = True
+SITE_ID = 1
+
+DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
+
+from config.settings.authentication import * # noqa: E402, F401, F403
+from config.settings.swagger import * # noqa: E402, F401, F403
diff --git a/src/config/django/dev/dev.py b/src/config/django/dev/dev.py
new file mode 100644
index 0000000000..ca4612dab2
--- /dev/null
+++ b/src/config/django/dev/dev.py
@@ -0,0 +1,142 @@
+import logging
+import re
+
+import sqlparse
+
+from ..base import * # noqa: F401, F403
+
+DEBUG = True
+SHOW_SQL_QUERIES = False
+CORS_ALLOW_ALL_ORIGINS = True
+ALLOWED_HOSTS = ["*"]
+
+
+class ColoredFormatter(logging.Formatter):
+ grey = "\x1b[38;20m"
+ blue = "\x1b[34;20m"
+ green = "\x1b[32;20m"
+ yellow = "\x1b[33;20m"
+ red = "\x1b[31;20m"
+ bold_red = "\x1b[31;1m"
+ reset = "\x1b[0m"
+
+ LEVEL_COLORS = {
+ logging.DEBUG: blue,
+ logging.INFO: green,
+ logging.WARNING: yellow,
+ logging.ERROR: red,
+ logging.CRITICAL: bold_red,
+ }
+
+ def format(self, record):
+ color = self.LEVEL_COLORS.get(record.levelno, self.grey)
+ record.levelname = f"{color}{record.levelname:<8}{self.reset}"
+
+ if record.name == "django.server":
+ match = re.search(r'"\s(\d{3})\s', record.msg)
+ if match:
+ code = int(match.group(1))
+ code_color = (
+ self.green
+ if code < 400
+ else (self.yellow if code < 500 else self.red)
+ )
+ record.msg = record.msg.replace(
+ str(code), f"{code_color}{code}{self.reset}"
+ )
+
+ if record.name == "django.db.backends":
+ record.name = "[DB]"
+ elif record.name == "django.server":
+ record.name = "[HTTP]"
+ elif record.name.startswith("django"):
+ record.name = "[DJANGO]"
+ if record.name == "[DB]" and sqlparse and hasattr(record, "sql"):
+ pass
+
+ formatted_msg = super().format(record)
+
+ if record.name == "[DB]" and sqlparse and "SELECT" in formatted_msg:
+ formatted_msg = sqlparse.format(
+ formatted_msg, reindent=True, keyword_case="upper"
+ )
+ formatted_msg = f"{self.grey}{formatted_msg}{self.reset}"
+
+ return formatted_msg
+
+
+# --- FILTRES ---
+class SkipIgnorableRequests(logging.Filter):
+ """Filtre pour ignorer les bruits de fond du dev server."""
+
+ def filter(self, record):
+ msg = record.getMessage()
+ if "/static/" in msg or "/media/" in msg:
+ return False
+
+ ignored_patterns = [
+ "GET /serviceworker.js",
+ "GET /favicon.ico",
+ "GET /manifest.json",
+ "apple-touch-icon",
+ "/serviceworker.js",
+ ]
+ if any(pattern in msg for pattern in ignored_patterns):
+ return False
+
+ return True
+
+
+LOGGING = {
+ "version": 1,
+ "disable_existing_loggers": False,
+ "formatters": {
+ "colored": {
+ "()": ColoredFormatter,
+ "format": "%(levelname)s %(asctime)s %(name)-10s %(message)s",
+ "datefmt": "%H:%M:%S",
+ },
+ },
+ "filters": {
+ "skip_ignorable": {
+ "()": SkipIgnorableRequests,
+ },
+ },
+ "handlers": {
+ "console": {
+ "class": "logging.StreamHandler",
+ "formatter": "colored",
+ "level": "DEBUG",
+ "filters": ["skip_ignorable"],
+ },
+ },
+ "loggers": {
+ "django": {
+ "handlers": ["console"],
+ "level": "INFO",
+ "propagate": False,
+ },
+ "django.server": {
+ "handlers": ["console"],
+ "level": "INFO",
+ "propagate": False,
+ },
+ "django.utils.autoreload": {
+ "handlers": ["console"],
+ "level": "WARNING",
+ "propagate": False,
+ },
+ "pod": {
+ "handlers": ["console"],
+ "level": "DEBUG",
+ "propagate": False,
+ },
+ },
+}
+
+if SHOW_SQL_QUERIES:
+ LOGGING["loggers"]["django.db.backends"] = {
+ "handlers": ["console"],
+ "level": "DEBUG",
+ "propagate": False,
+ }
diff --git a/src/config/django/dev/docker.py b/src/config/django/dev/docker.py
new file mode 100644
index 0000000000..6e2fb99ca3
--- /dev/null
+++ b/src/config/django/dev/docker.py
@@ -0,0 +1,18 @@
+from config.env import env
+
+from .dev import * # noqa: F401, F403
+
+# DEFAULT CONFIG (Docker environment): MariaDB
+DATABASES = {
+ "default": {
+ "ENGINE": "django.db.backends.mysql",
+ "NAME": env("MYSQL_DATABASE", default="pod_db"),
+ "USER": env("MYSQL_USER", default="pod"),
+ "PASSWORD": env("MYSQL_PASSWORD", default="pod"),
+ "HOST": env("MYSQL_HOST", default="localhost"),
+ "PORT": env("MYSQL_PORT", default="3306"),
+ "OPTIONS": {
+ "charset": "utf8mb4",
+ },
+ }
+}
diff --git a/src/config/django/dev/local.py b/src/config/django/dev/local.py
new file mode 100644
index 0000000000..09bbf93532
--- /dev/null
+++ b/src/config/django/dev/local.py
@@ -0,0 +1,25 @@
+from config.env import BASE_DIR
+
+from .dev import * # noqa: F401, F403
+
+DATABASES = {
+ "default": {
+ "ENGINE": "django.db.backends.sqlite3",
+ "NAME": BASE_DIR / "db.sqlite3",
+ "TEST": {
+ "NAME": BASE_DIR / "db_test.sqlite3",
+ },
+ "OPTIONS": {
+ "timeout": 20,
+ },
+ }
+}
+
+CACHES = {
+ "default": {
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
+ "LOCATION": "local-cache",
+ }
+}
+
+EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
diff --git a/src/config/django/prod/prod.py b/src/config/django/prod/prod.py
new file mode 100644
index 0000000000..1e034c1d48
--- /dev/null
+++ b/src/config/django/prod/prod.py
@@ -0,0 +1,7 @@
+from config.env import env
+
+from ..base import * # noqa: F401, F403
+
+DEBUG = False
+CORS_ALLOW_ALL_ORIGINS = False
+ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=[])
diff --git a/src/config/django/test/docker.py b/src/config/django/test/docker.py
new file mode 100644
index 0000000000..925eb4acb9
--- /dev/null
+++ b/src/config/django/test/docker.py
@@ -0,0 +1,32 @@
+from config.django.test.init_env import * # noqa: F401, F403 # isort:skip
+from config.django.dev.docker import * # noqa: F401, F403
+from config.env import env
+
+DEBUG = False
+EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
+
+PASSWORD_HASHERS = [
+ "django.contrib.auth.hashers.MD5PasswordHasher",
+]
+
+CELERY_TASK_ALWAYS_EAGER = True
+
+# TEST DATABASES
+DATABASES = {
+ "default": {
+ "ENGINE": "django.db.backends.mysql",
+ "NAME": "pod_db",
+ "USER": env("MYSQL_USER", default="pod"),
+ "PASSWORD": env("MYSQL_PASSWORD", default="pod"),
+ "HOST": env("MYSQL_HOST", default="db"),
+ "PORT": env("MYSQL_PORT", default="3306"),
+ "OPTIONS": {
+ "charset": "utf8mb4",
+ },
+ "TEST": {
+ "NAME": "test_pod_db",
+ "CHARSET": "utf8mb4",
+ "COLLATION": "utf8mb4_general_ci",
+ },
+ }
+}
diff --git a/src/config/django/test/e2e_scenario.py b/src/config/django/test/e2e_scenario.py
new file mode 100644
index 0000000000..1472341245
--- /dev/null
+++ b/src/config/django/test/e2e_scenario.py
@@ -0,0 +1,109 @@
+"""
+End-to-End (E2E) Test Scenario Script.
+This script performs a series of automated checks to validate the availability
+and basic security configuration of the deployed application. It is used
+in the CI/CD pipeline to ensure the service is up and running correctly
+after deployment.
+
+Checks included:
+1. API Health: Verifies that the API documentation endpoint is reachable.
+2. Security Headers: Checks for the presence of essential security headers.
+3. Admin Access: Confirms that the authentication login page is accessible.
+"""
+
+import os
+import sys
+import time
+
+import requests
+
+API_URL = os.getenv("API_URL", "http://127.0.0.1:8000")
+ADMIN_USER = os.getenv("DJANGO_SUPERUSER_USERNAME", "admin")
+ADMIN_PASS = os.getenv("DJANGO_SUPERUSER_PASSWORD", "admin")
+
+DEFAULT_TIMEOUT = 10
+RETRY_DELAY = 5
+
+
+def log(message: str) -> None:
+ """Print formatted E2E log message."""
+ print(f"[E2E] {message}")
+
+
+def test_api_health(retries: int = 5) -> bool:
+ """
+ Check if the API documentation endpoint is reachable.
+ Retries several times before failing.
+ """
+ url = f"{API_URL}/api/docs/"
+
+ for attempt in range(1, retries + 1):
+ log(f"Checking API health at {url} (attempt {attempt}/{retries})")
+
+ try:
+ response = requests.get(url, timeout=DEFAULT_TIMEOUT)
+
+ if response.status_code == 200:
+ log("API is responding (200 OK)")
+ return True
+
+ log(f"Unexpected status code: {response.status_code}")
+
+ except requests.RequestException as exc:
+ log(f"Connection error: {exc}")
+
+ time.sleep(RETRY_DELAY)
+
+ log("API unreachable after multiple attempts")
+ return False
+
+
+def test_admin_login() -> None:
+ """
+ Check if the authentication endpoint is reachable.
+ This does not authenticate, only verifies that the login page exists.
+ """
+ url = f"{API_URL}/accounts/login"
+ log(f"Checking auth endpoint at {url}")
+
+ response = requests.get(url, allow_redirects=True, timeout=DEFAULT_TIMEOUT)
+
+ if response.status_code == 200:
+ log("Auth login page reachable")
+ else:
+ log(f"Auth page returned status {response.status_code}")
+
+
+def test_security_headers() -> None:
+ """
+ Check presence of basic security headers.
+ """
+ url = f"{API_URL}/api/docs/"
+ log("Checking security headers")
+
+ response = requests.get(url, timeout=DEFAULT_TIMEOUT)
+
+ if "X-Frame-Options" in response.headers:
+ log("X-Frame-Options header is present")
+ else:
+ log("Missing X-Frame-Options header")
+
+
+def run_tests() -> None:
+ """Run all E2E checks."""
+ log("Starting E2E tests")
+
+ # Warmup delay
+ time.sleep(2)
+
+ if not test_api_health():
+ sys.exit(1)
+
+ test_security_headers()
+ test_admin_login()
+
+ log("All checks completed")
+
+
+if __name__ == "__main__":
+ run_tests()
diff --git a/src/config/django/test/init_env.py b/src/config/django/test/init_env.py
new file mode 100644
index 0000000000..93669ea3f8
--- /dev/null
+++ b/src/config/django/test/init_env.py
@@ -0,0 +1,6 @@
+import os
+
+os.environ["USE_CAS"] = "True"
+os.environ["USE_LDAP"] = "True"
+os.environ["USE_SHIB"] = "True"
+os.environ["USE_OIDC"] = "True"
diff --git a/src/config/django/test/test.py b/src/config/django/test/test.py
new file mode 100644
index 0000000000..d748eef98a
--- /dev/null
+++ b/src/config/django/test/test.py
@@ -0,0 +1,14 @@
+import os
+
+from config.django.test.init_env import * # noqa: F401, F403
+
+from ..base import * # noqa: F401, F403
+
+DATABASES = {
+ "default": {
+ "ENGINE": "django.db.backends.sqlite3",
+ "NAME": os.getenv("TEST_DB_NAME", ":memory:"),
+ }
+}
+
+ALLOWED_HOSTS = ["*"]
diff --git a/src/config/env.py b/src/config/env.py
new file mode 100644
index 0000000000..d2499b2906
--- /dev/null
+++ b/src/config/env.py
@@ -0,0 +1,11 @@
+from pathlib import Path
+
+import environ
+
+env = environ.Env()
+
+BASE_DIR = Path(__file__).resolve().parents[2]
+DOTENV_FILE = BASE_DIR / ".env"
+
+if DOTENV_FILE.is_file():
+ env.read_env(str(DOTENV_FILE))
diff --git a/src/config/router.py b/src/config/router.py
new file mode 100644
index 0000000000..df349a503c
--- /dev/null
+++ b/src/config/router.py
@@ -0,0 +1,3 @@
+from rest_framework import routers
+
+router = routers.SimpleRouter()
diff --git a/src/config/settings/__init__.py b/src/config/settings/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/config/settings/authentication.py b/src/config/settings/authentication.py
new file mode 100644
index 0000000000..2fb04af44d
--- /dev/null
+++ b/src/config/settings/authentication.py
@@ -0,0 +1,105 @@
+import os
+from datetime import timedelta
+
+from ..django.base import SECRET_KEY
+from ..env import env
+
+# Retrieve Feature Flags from Environment (default: False for security)
+USE_LOCAL_AUTH = env.bool(
+ "USE_LOCAL_AUTH", default=True
+) # Default to True for dev/simple setups? Or env default?
+USE_CAS = env.bool("USE_CAS", default=False)
+USE_LDAP = env.bool("USE_LDAP", default=False)
+USE_SHIB = env.bool("USE_SHIB", default=False)
+USE_OIDC = env.bool("USE_OIDC", default=False)
+
+# Derived configuration
+POPULATE_USER = "CAS" if USE_CAS else "LDAP" if USE_LDAP else None
+
+SIMPLE_JWT = {
+ "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
+ "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
+ "ROTATE_REFRESH_TOKENS": False,
+ "BLACKLIST_AFTER_ROTATION": False,
+ "ALGORITHM": "HS256",
+ "SIGNING_KEY": SECRET_KEY,
+ "AUTH_HEADER_TYPES": ("Bearer",),
+ "USER_ID_FIELD": "id",
+ "USER_ID_CLAIM": "user_id",
+}
+
+AUTHENTICATION_BACKENDS = []
+
+if USE_LOCAL_AUTH:
+ AUTHENTICATION_BACKENDS.append("django.contrib.auth.backends.ModelBackend")
+
+if USE_CAS:
+ AUTHENTICATION_BACKENDS.append("django_cas_ng.backends.CASBackend")
+
+if USE_CAS:
+ CAS_SERVER_URL = env("CAS_SERVER_URL", default="https://cas.univ-lille.fr")
+ CAS_VERSION = env("CAS_VERSION", default="3")
+ CAS_FORCE_CHANGE_USERNAME_CASE = "lower"
+ CAS_APPLY_ATTRIBUTES_TO_USER = True
+
+if USE_LDAP:
+ LDAP_SERVER_URL = env("LDAP_SERVER_URL", default="ldap://ldap.univ.fr")
+ LDAP_SERVER_PORT = env.int("LDAP_SERVER_PORT", default=389)
+ LDAP_SERVER_USE_SSL = env.bool("LDAP_SERVER_USE_SSL", default=False)
+ LDAP_SERVER = {
+ "url": LDAP_SERVER_URL,
+ "port": LDAP_SERVER_PORT,
+ "use_ssl": LDAP_SERVER_USE_SSL,
+ }
+
+ AUTH_LDAP_BIND_DN = "cn=pod,ou=app,dc=univ,dc=fr"
+ AUTH_LDAP_BIND_PASSWORD = env("AUTH_LDAP_BIND_PASSWORD", default="")
+
+ AUTH_LDAP_USER_SEARCH = ("ou=people,dc=univ,dc=fr", "(uid=%(uid)s)")
+
+ USER_LDAP_MAPPING_ATTRIBUTES = {
+ "uid": "uid",
+ "mail": "mail",
+ "last_name": "sn",
+ "first_name": "givenname",
+ "primaryAffiliation": "eduPersonPrimaryAffiliation",
+ "affiliations": "eduPersonAffiliation",
+ "groups": "memberOf",
+ "establishment": "establishment",
+ }
+
+ALLOWED_SUPERUSER_IPS = ["127.0.0.1", "10.0.0.0/8"]
+AFFILIATION_STAFF = ("faculty", "employee", "staff")
+CREATE_GROUP_FROM_AFFILIATION = True
+CREATE_GROUP_FROM_GROUPS = True
+
+# TODO: Verifiy implementation
+if USE_CAS and USE_SHIB:
+ SHIBBOLETH_ATTRIBUTE_MAP = {
+ "REMOTE_USER": (True, "username"),
+ "Shibboleth-givenName": (True, "first_name"),
+ "Shibboleth-sn": (False, "last_name"),
+ "Shibboleth-mail": (False, "email"),
+ "Shibboleth-primary-affiliation": (False, "affiliation"),
+ "Shibboleth-unscoped-affiliation": (False, "affiliations"),
+ }
+
+ SHIBBOLETH_STAFF_ALLOWED_DOMAINS = []
+
+if USE_CAS and USE_OIDC:
+ OIDC_CLAIM_GIVEN_NAME = "given_name"
+ OIDC_CLAIM_FAMILY_NAME = "family_name"
+ OIDC_CLAIM_PREFERRED_USERNAME = "preferred_username"
+
+ OIDC_DEFAULT_AFFILIATION = "member"
+ OIDC_DEFAULT_ACCESS_GROUP_CODE_NAMES = []
+ OIDC_RP_CLIENT_ID = os.environ.get("OIDC_RP_CLIENT_ID", "mon-client-id")
+ OIDC_RP_CLIENT_SECRET = os.environ.get("OIDC_RP_CLIENT_SECRET", "mon-secret")
+
+ OIDC_OP_TOKEN_ENDPOINT = os.environ.get(
+ "OIDC_OP_TOKEN_ENDPOINT", "https://auth.example.com/oidc/token"
+ )
+
+ OIDC_OP_USER_ENDPOINT = os.environ.get(
+ "OIDC_OP_USER_ENDPOINT", "https://auth.example.com/oidc/userinfo"
+ )
diff --git a/src/config/settings/swagger.py b/src/config/settings/swagger.py
new file mode 100644
index 0000000000..5181a41c58
--- /dev/null
+++ b/src/config/settings/swagger.py
@@ -0,0 +1,9 @@
+from ..django.base import POD_VERSION
+
+SPECTACULAR_SETTINGS = {
+ "TITLE": "Pod REST API",
+ "DESCRIPTION": "Video management API (Local Authentication)",
+ "VERSION": POD_VERSION,
+ "SERVE_INCLUDE_SCHEMA": False,
+ "COMPONENT_SPLIT_REQUEST": True,
+}
diff --git a/src/config/urls.py b/src/config/urls.py
new file mode 100644
index 0000000000..76107a39c2
--- /dev/null
+++ b/src/config/urls.py
@@ -0,0 +1,53 @@
+import django_cas_ng.views
+from django.conf import settings
+from django.contrib import admin
+from django.contrib.auth import views as auth_views
+from django.urls import include, path
+from django.views.generic import RedirectView
+from drf_spectacular.views import (
+ SpectacularAPIView,
+ SpectacularRedocView,
+ SpectacularSwaggerView,
+)
+
+from config.router import router
+
+urlpatterns = [
+ # Redirection to Swagger
+ path("", RedirectView.as_view(url="api/docs/", permanent=False)),
+ path("admin/", admin.site.urls),
+ path("api/", include(router.urls)),
+ path("api/info/", include("src.apps.info.urls")),
+ path("api/auth/", include("src.apps.authentication.urls")),
+ # SWAGGER
+ path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
+ path(
+ "api/docs/",
+ SpectacularSwaggerView.as_view(url_name="schema"),
+ name="swagger-ui",
+ ),
+ path("api/redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"),
+]
+
+if getattr(settings, "USE_CAS", False):
+ urlpatterns += [
+ path(
+ "accounts/login",
+ django_cas_ng.views.LoginView.as_view(),
+ name="cas_ng_login",
+ ),
+ path(
+ "accounts/logout",
+ django_cas_ng.views.LogoutView.as_view(),
+ name="cas_ng_logout",
+ ),
+ ]
+else:
+ urlpatterns += [
+ path(
+ "accounts/login",
+ auth_views.LoginView.as_view(template_name="admin/login.html"),
+ name="cas_ng_login",
+ ),
+ path("accounts/logout", auth_views.LogoutView.as_view(), name="cas_ng_logout"),
+ ]
diff --git a/src/config/wsgi.py b/src/config/wsgi.py
new file mode 100644
index 0000000000..217d3c4bb7
--- /dev/null
+++ b/src/config/wsgi.py
@@ -0,0 +1,23 @@
+import os
+import sys
+
+from django.core.wsgi import get_wsgi_application
+
+from config.env import env
+
+try:
+ settings_module = env.str("DJANGO_SETTINGS_MODULE")
+
+ if not settings_module:
+ raise ValueError("DJANGO_SETTINGS_MODULE is set but empty.")
+
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
+ application = get_wsgi_application()
+
+except Exception as e:
+ print(
+ f"FATAL ERROR: Failed to initialize the ASGI application. "
+ f"Check that DJANGO_SETTINGS_MODULE is set. Details: {e}",
+ file=sys.stderr,
+ )
+ sys.exit(1)