diff --git a/.github/workflows/README.md b/.github/workflows/README.md
index 0c5af53..73a5b23 100644
--- a/.github/workflows/README.md
+++ b/.github/workflows/README.md
@@ -27,19 +27,21 @@
#### File: [development_pipeline.yml](development_pipeline.yml)
-**Event:** On Pull Request โ any branch into develop
+**Event:** On Pull Request โ any branch into develop, and on push to develop
**Jobs:**
- Install dependencies (caches)
+- Audit runtime dependencies with pip-audit
- Run isort
- Run black
- Run flake8
+- Run unit and integration tests (`python -m flask tests` against a PostgreSQL service container)
- Build images (caches)
- Push images to Docker Hub
**Description:**
-This workflow is triggered on Pull Requests into the develop branch. It ensures a clean and standardized codebase by installing dependencies, checking code formatting with isort, black, and flake8, and finally building and pushing Docker images to Docker Hub.
+This workflow is triggered on Pull Requests into the develop branch and on every push to it. It ensures a clean and standardized codebase by installing dependencies, auditing the runtime dependencies for known vulnerabilities with pip-audit, checking code formatting with isort, black, and flake8, running the test suite, and finally building and pushing Docker images to Docker Hub.
### Staging - CI/CD Pipeline
@@ -50,9 +52,11 @@ This workflow is triggered on Pull Requests into the develop branch. It ensures
**Jobs:**
- Install dependencies (caches)
+- Audit runtime dependencies with pip-audit
- Run isort
- Run black
- Run flake8
+- Run unit and integration tests (`python -m flask tests` against a PostgreSQL service container)
- Build images (caches)
- Push images to Docker Hub
- Create infrastructure
@@ -72,9 +76,11 @@ This pipeline is designed for the staging environment and is triggered on Pull R
**Jobs:**
- Install dependencies (caches)
+- Audit runtime dependencies with pip-audit
- Run isort
- Run black
- Run flake8
+- Run unit and integration tests (`python -m flask tests` against a PostgreSQL service container)
- Build images (caches)
- Push images to Docker Hub
- Create infrastructure
diff --git a/.github/workflows/cloudformations/server.yml b/.github/workflows/cloudformations/server.yml
index b1e1133..bff3848 100644
--- a/.github/workflows/cloudformations/server.yml
+++ b/.github/workflows/cloudformations/server.yml
@@ -31,7 +31,7 @@ Parameters:
AMItoUse:
Description: AMI to use for our base image - Canonical, Ubuntu, 22.04 LTS, amd64 jammy image build on 2023-05-16
Type: String
- Default: "ami-053b0d53c279acc90"
+ Default: "ami-key"
Resources:
VPC:
diff --git a/.github/workflows/development_pipeline.yml b/.github/workflows/development_pipeline.yml
index e6f9e45..a736f0d 100644
--- a/.github/workflows/development_pipeline.yml
+++ b/.github/workflows/development_pipeline.yml
@@ -31,7 +31,10 @@ jobs:
cache: "pip"
- name: Install Python dependencies
- run: python -m pip install -r requirements.txt
+ run: python -m pip install -r requirements-dev.txt
+
+ - name: Audit runtime dependencies for known vulnerabilities
+ run: pip-audit -r requirements.txt
- name: Run isort
run: isort --check-only --profile=black .
diff --git a/.github/workflows/production_pipeline.yml b/.github/workflows/production_pipeline.yml
index d251ce2..647e126 100644
--- a/.github/workflows/production_pipeline.yml
+++ b/.github/workflows/production_pipeline.yml
@@ -28,7 +28,10 @@ jobs:
cache: "pip"
- name: Install Python dependencies
- run: python -m pip install -r requirements.txt
+ run: python -m pip install -r requirements-dev.txt
+
+ - name: Audit runtime dependencies for known vulnerabilities
+ run: pip-audit -r requirements.txt
- name: Run isort
run: isort --check-only --profile=black .
diff --git a/.github/workflows/staging_pipeline.yml b/.github/workflows/staging_pipeline.yml
index 07056ab..5ace4a9 100644
--- a/.github/workflows/staging_pipeline.yml
+++ b/.github/workflows/staging_pipeline.yml
@@ -28,7 +28,10 @@ jobs:
cache: "pip"
- name: Install Python dependencies
- run: python -m pip install -r requirements.txt
+ run: python -m pip install -r requirements-dev.txt
+
+ - name: Audit runtime dependencies for known vulnerabilities
+ run: pip-audit -r requirements.txt
- name: Run isort
run: isort --check-only --profile=black .
diff --git a/.gitignore b/.gitignore
index 52a3ac4..d42a1bb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -93,9 +93,11 @@ celerybeat.pid
# SageMath parsed files
*.sage.py
-# Environment variable
-# .env
-# .env*
+# Environment variable (real env files must never be committed; templates are allowed)
+.env
+.env*
+!.env.example
+!.env.*.example
# Environments
.venv/
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..1e26040
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,3 @@
+{
+ "python.terminal.useEnvFile": true
+}
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
index ba6ac7c..faafb79 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,26 +1,37 @@
-FROM python:3.10.9-slim
+FROM python:3.10-slim
WORKDIR /app
-# Update the package lists and install the PostgreSQL client
+# postgresql-client provides psql, used by entrypoint.sh to wait for the database
RUN apt-get update && \
- apt-get install -y postgresql-client && \
- apt clean && \
- rm -rf /var/cache/apt/*
+ apt-get install -y --no-install-recommends postgresql-client && \
+ apt-get clean && \
+ rm -rf /var/lib/apt/lists/*
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
- PYTHONIOENCODING=utf-8
+ PYTHONIOENCODING=utf-8 \
+ PIP_NO_CACHE_DIR=1 \
+ PIP_DISABLE_PIP_VERSION_CHECK=1
-COPY requirements.txt /app
+# Runtime dependencies only (no linters, test tools or notebooks in the image)
+COPY requirements.txt /app/
+RUN pip install --upgrade pip && \
+ pip install -r requirements.txt
-RUN pip install --upgrade pip
-RUN pip install --no-cache-dir -r requirements.txt
+# Unprivileged user. uid/gid 1000 so that the ./logs bind mount in
+# docker-compose.yml stays writable on a typical single-user host.
+RUN groupadd --gid 1000 app && \
+ useradd --uid 1000 --gid app --no-create-home --shell /usr/sbin/nologin app && \
+ mkdir -p /app/logs && \
+ chown app:app /app /app/logs
-COPY . /app
+COPY --chown=app:app . /app
-# Chmod to entrypoint.sh
-RUN chmod +x ./entrypoint.sh
+RUN chmod +x /app/entrypoint.sh
+
+USER app
+
+EXPOSE 5000
-# Run entrypoint.sh
ENTRYPOINT ["/app/entrypoint.sh"]
diff --git a/README.md b/README.md
index c94bf17..2c18b14 100644
--- a/README.md
+++ b/README.md
@@ -8,364 +8,579 @@
-Rest API template developed in Python with the Flask framework. The template covers user management, jwt tokens for authentication, and assign permissions for each user with Flask Principal. In the local environment, it uses docker to create an environment made up of several services such as api (flask), database (postgresql), reverse-proxy (nginx).
+Rest API template developed in Python with the Flask framework. The template covers user management, JWT tokens for authentication, and role/permission based authorization. In the local environment, it uses Docker to create an environment made up of several services: api (Flask + Gunicorn), database (PostgreSQL) and reverse-proxy (Nginx).
+
+All commands in this guide are given for **Bash** (Linux / macOS / WSL / Git Bash) **and** **PowerShell** (Windows). Wherever a command is identical in both shells, it is shown only once.
## Index
- [Technology](#technology)
- [Requirements](#requirements)
+- [Security Best Practices](#security-best-practices)
+ - [Security Checklist](#security-checklist)
+ - [Verify Your Repository is Secure](#verify-your-repository-is-secure)
+ - [Generating Secrets](#generating-secrets)
+ - [Default Seed Accounts](#default-seed-accounts)
+ - [How authorization works](#how-authorization-works)
+ - [Other Things to Know Before Going to Production](#other-things-to-know-before-going-to-production)
- [Environments](#environments)
+ - [Environment Variables](#environment-variables)
- [Develop](#develop)
- [Testing](#testing)
- [Local](#local)
- [Production](#production)
+- [Windows / PowerShell Notes](#windows--powershell-notes)
+- [Creating Deployment Archive](#creating-deployment-archive)
- [Flask Commands](#flask-commands)
- [Flask-cli](#flask-cli)
-- [Database commands](#bbdd-commands)
+- [Database Commands](#database-commands)
- [Flask-migrate](#flask-migrate)
+- [API Endpoints](#api-endpoints)
- [Swagger](#swagger)
+- [CI/CD Status](#cicd-status)
- [Reference](#reference)
- [Contribution](#contribution)
## Technology
-- **Operating System:** Ubuntu
+- **Operating System:** Ubuntu (containers / deploy target), developed on Linux, macOS and Windows
- **Web Framework:** Flask
- **ORM:** Flask-sqlalchemy
-- **Swagger:** Swagger-UI
-- **Authentication:** Flask Json Web Token
-- **Permission:** JWT Decorator
+- **Swagger:** Swagger-UI (via flask-smorest)
+- **Authentication:** Flask-JWT-Extended
+- **Permission:** JWT + role/permission decorator
- **Serialization, Deserialization and Validation:** Marshmallow
- **Migration Database:** Flask-migrate
-- **Environment manager:** Anaconda/Miniconda
-- **Containerization:** Docker, docker-compose
+- **Environment Manager:** Anaconda/Miniconda or `venv`
+- **Containerization:** Docker, Docker Compose
- **Database:** PostgreSQL
- **Python WSGI HTTP Server:** Gunicorn
- **Proxy:** Nginx
- **Tests:** Unittest
-- **Deployment platform:** AWS
+- **Deployment Platform:** AWS
- **CI/CD:** Github Actions
## Requirements
-- [Python](https://www.python.org/downloads/)
-- [Anaconda/Miniconda](instructions/anaconda-miniconda.md)
-- [Docker](instructions/docker-dockercompose.md)
-- [Docker-Compose](instructions/docker-dockercompose.md)
-- [Github](https://github.com)
+- **Python:** 3.10 (the version used by the [Dockerfile](Dockerfile) and the CI pipelines). The pinned dependencies also install and pass the test suite on 3.12.
+- **Git**
+- **Docker** and **Docker Compose** (Docker Desktop on Windows/macOS) โ only needed for the [Local](#local) environment
+- **PostgreSQL** โ provided by Docker Compose; a SQLite file can be used instead for quick local development (see [Develop](#develop))
+- An environment manager: [Anaconda/Miniconda](https://docs.conda.io/en/latest/miniconda.html) or the built-in `venv` module
+- On Windows: **PowerShell 5.1** or **PowerShell 7+** (all PowerShell snippets in this README work in both)
-## Environments
+## Security Best Practices
-### Develop
+### ๐ Before You Start
-Development environment that uses PostgreSQL in local and uses the server flask in debug mode.
+**IMPORTANT:** Never commit sensitive files to version control!
-1. **Create environment and install packages**
+This template reads every secret from environment variables (see [Environment Variables](#environment-variables)). Nothing in the repository should ever contain a real secret โ not the code, not the Docker image, and not the deployment archive.
-```shell
-conda create -n backend python=3.10
+### Security Checklist
-conda activate backend
+- [ ] Verify `.gitignore` excludes all `.env*` files (it does โ see the `# Environment variable` block; only `*.example` templates are re-included)
+- [ ] Verify `.dockerignore` excludes:
+ - `.env*`
+ - `.git`
+ - `__pycache__`
+ - `*.pyc`
+ - `*.log` (so the `logs/` content is never baked into an image)
+- [ ] Use `.env.example` templates only (never commit actual `.env` files)
+- [ ] Generate strong, unique secrets for `SECRET_KEY` and `JWT_SECRET_KEY` in every environment (see [Generating Secrets](#generating-secrets))
+- [ ] Change or remove the [default seed accounts](#default-seed-accounts) before exposing the API
+- [ ] Never share or commit real credentials โ use GitHub _Secrets_ for CI/CD (see [.github/workflows/README.md](.github/workflows/README.md))
+- [ ] Rotate secrets regularly and after any suspected leak
+- [ ] Install the pre-commit hooks โ they include `detect-private-key` (see [Contribution](#contribution))
-pip install -r requirements.txt
-```
+### Verify Your Repository is Secure
-2. **Create PosgresSQL on Ubuntu**
+Run these from the repository root. Both variants do the same thing.
-```shell
-# Install PosgresSQL
-sudo apt-get install postgresql-12
+**Bash**
-# Access to PosgresSQL
-sudo -u postgres psql
+```bash
+# 1. Check that no .env files are tracked by git
+git ls-files | grep -E '(^|/)\.env'
+# Should return NOTHING (or only *.example files)
-# Create user and password
-CREATE USER db_user WITH PASSWORD 'db_password';
+# 2. Check that .gitignore has the rules
+grep -n '\.env' .gitignore
+# Should show ".env" and ".env*" (and the "!.env*.example" exceptions)
-# Create Database dev
-CREATE DATABASE db_dev;
+# 3. Ask git directly whether a given file would be ignored
+git check-ignore -v .env .env.api.local .env.db.local
+# Each file should be listed together with the matching .gitignore rule
-# Add permission User to Database
-GRANT ALL PRIVILEGES ON DATABASE db_dev TO db_user;
+# 4. Make sure no .env file ever made it into the history
+git log --all --name-only --format='' | grep -E '(^|/)\.env' | sort -u
+# Should return NOTHING (or only *.example files)
```
-3. **Create or update `.env` file**
+**PowerShell**
-```shell
-# APP configuration
-APP_NAME=Flask API Rest Template
-APP_ENV=develop
+```powershell
+# 1. Check that no .env files are tracked by git
+git ls-files | Select-String -Pattern '(^|/)\.env'
+# Should return NOTHING (or only *.example files)
-# Flask Configuration
-FLASK_APP=app:app
-FLASK_DEBUG=true
-APP_SETTINGS_MODULE=config.DevelopConfig
-FLASK_RUN_HOST=0.0.0.0
-FLASK_RUN_PORT=5000
+# 2. Check that .gitignore has the rules
+Get-Content .gitignore | Select-String -Pattern '\.env'
+# Should show ".env" and ".env*" (and the "!.env*.example" exceptions)
-# Secret key
-SECRET_KEY=
-JWT_SECRET_KEY=
+# 3. Ask git directly whether a given file would be ignored
+git check-ignore -v .env .env.api.local .env.db.local
+# Each file should be listed together with the matching .gitignore rule
-# Database service configuration
-DATABASE_URL=postgresql://db_user:db_password@localhost/db_dev
+# 4. Make sure no .env file ever made it into the history
+git log --all --name-only --format='' | Select-String -Pattern '(^|/)\.env' | Sort-Object -Unique
+# Should return NOTHING (or only *.example files)
```
-4. **Run application**
+If step 1 or step 4 returns a real `.env` file, **treat every secret in it as compromised**: rotate the secrets first, then remove the file from the history (for example with [`git filter-repo`](https://github.com/newren/git-filter-repo)).
-```shell
-# Create database
-flask create-db
+### Generating Secrets
-# Create user admin
-flask create-user-admin
+`SECRET_KEY` (Flask) and `JWT_SECRET_KEY` (token signing) must be long, random and different from each other. The same command works in Bash and PowerShell:
-# Run a development server
-flask run
+```bash
+python -c "import secrets; print(secrets.token_hex(32))"
```
-### Testing
+Run it twice and paste one value into each variable. Never reuse the development values in staging or production.
-Testing environment that uses PostgreSQL as database (db_test) and performs unit tests, integration tests and API tests.
+### Default Seed Accounts
-1. **Create test environment**
+`flask create-user-admin` (which the Docker `entrypoint.sh` runs automatically when `APP_ENV=local`) seeds three accounts for convenience:
-2. **Create Test Database**
+| Username | Password | Role | Permissions |
+| -------- | -------- | ----- | -------------------------- |
+| `admin` | `123456` | Admin | read, write, delete, admin |
+| `user` | `123456` | User | read, write |
+| `guest` | `123456` | Guest | read |
-3. **Create or update `.env` file**
+These are **public, well-known credentials**. Before any environment is reachable by someone other than you:
-```shell
-# APP configuration
-APP_NAME=Flask API Rest Template
-APP_ENV=testing
+- change the passwords (`PUT /user/`), or
+- edit `init_db_user()` in [manage.py](manage.py) to read the initial password from an environment variable, or
+- do not run `create-user-admin` at all in that environment (in `APP_ENV=production` the entrypoint does not run it).
-# Flask Configuration
-FLASK_APP=app:app
-FLASK_DEBUG=true
-APP_SETTINGS_MODULE=config.TestingConfig
-FLASK_RUN_HOST=0.0.0.0
-FLASK_RUN_PORT=3000
+#### How authorization works
-# Secret key
-SECRET_KEY=
-JWT_SECRET_KEY=
+- `read`, `write` and `delete` gate access to data.
+- The `admin` permission gates everything that changes _who may do what_: creating / editing / deleting roles and permissions, assigning roles to users, and blocking users. `write` alone never lets a user change authorization.
+- Users may update their own username and password; only an admin may update other users or change `roles`.
+- Nothing authorization-related is stored in the JWT. Every request re-reads roles and permissions from the database, so revoking a role or blocking a user takes effect on the user's very next request.
+- Lockout guard: any change that would remove the caller's own `admin` access (e.g. deleting the Admin role, removing the `admin` permission from it, renaming the permission, or an admin blocking themselves) is rejected with `400` before it is committed.
-# Database service configuration
-DATABASE_TEST_URL=postgresql://db_user:db_password@localhost/db_test
-```
+There is no special "super admin" user id. Whoever holds a role with the `admin` permission is an admin; running `flask create-user-admin` on a database seeded by an older version of this template adds the `admin` permission to the existing `Admin` role.
-4. **Init database**
+### Other Things to Know Before Going to Production
-```shell
-# Create database
-flask create-db
+- **CORS** is off unless `CORS_ORIGINS` lists your front-end origin(s); credentials are never allowed (authentication is a bearer token, not a cookie). `DevelopConfig` defaults to `*` for convenience โ never use `*` in production.
+- **Rate limiting** protects `/login` (`RATELIMIT_LOGIN`, default `5 per minute`) and `/register` (`RATELIMIT_REGISTER`, default `3 per minute`) per client IP. The default `memory://` store is per Gunicorn worker; set `RATELIMIT_STORAGE_URI` to a shared store (e.g. Redis) for exact limits across workers. Behind Nginx, `TRUSTED_PROXY_COUNT` must be set (the Local / Production configs default to `1`) so the limit is keyed on the real client address and not on the proxy.
+- **Dependencies**: the Docker image installs only `requirements.txt` (runtime). Linters, test tools and `pip-audit` are in `requirements-dev.txt`. CI runs `pip-audit -r requirements.txt` on every pipeline and fails on known vulnerabilities โ run it locally too before bumping versions.
+- **Container user**: the image runs as the unprivileged user `app` (uid/gid 1000). The `./logs` bind mount must be writable by that uid; on a host where your user is not uid 1000, `chown -R 1000:1000 logs` (or change the ids in the Dockerfile).
+- **Token lifetimes** are set in `config.py` (`JWT_ACCESS_TOKEN_EXPIRES` = 30 minutes, `JWT_REFRESH_TOKEN_EXPIRES` = 30 days). Logging out or refreshing adds the token `jti` to a database blocklist.
+- **Registration** (`POST /register`) is open and assigns the `Guest` (read-only) role, looked up by name. Disable or protect it if you do not want self sign-up.
+- **Environment files are not part of the deployment archive** (see [Creating Deployment Archive](#creating-deployment-archive)); `.env.api.local` / `.env.db.local` must be provisioned on the server (or injected by your orchestrator) out of band.
+- **Gunicorn worker count / timeouts** are tunable via environment variables (`WEB_CONCURRENCY`, `MAX_WORKERS`, `TIMEOUT`, โฆ) โ see [gunicorn/gunicorn_config.py](gunicorn/gunicorn_config.py).
+- Run the app behind TLS (terminate at the load balancer or in Nginx). The provided [nginx/default.conf](nginx/default.conf) is plain HTTP.
-# Create user admin
-flask create-user-admin
+## Environments
+
+The configuration class is selected with `APP_SETTINGS_MODULE` (see [config.py](config.py)):
+
+| Environment | `APP_SETTINGS_MODULE` | `APP_ENV` | Database variable | Debug | Typical use |
+| ----------- | ------------------------- | ------------ | ------------------- | ----- | ---------------------------------- |
+| Develop | `config.DevelopConfig` | `develop` | `DATABASE_URL` | on | `flask run` on your machine |
+| Testing | `config.TestingConfig` | `testing` | `DATABASE_TEST_URL` | on | `flask tests` / CI |
+| Local | `config.LocalConfig` | `local` | `DATABASE_URL` | off | Docker Compose (api + db + nginx) |
+| Production | `config.ProductionConfig` | `production` | `DATABASE_URL` | off | Docker image on the server (CI/CD) |
+
+### Environment Variables
+
+`python-dotenv` is installed, so the `flask` command automatically loads a `.env` file from the current directory โ this is the recommended, shell-independent way to set variables for development and testing. Docker Compose instead reads `.env.api.local` and `.env.db.local` (see [Local](#local)). All of these files are git-ignored.
+
+| Variable | Used by | Description |
+| -------------------------------------------------------------------------------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------ |
+| `APP_SETTINGS_MODULE` | `app/__init__.py` | Config class, e.g. `config.DevelopConfig` |
+| `APP_TEST_SETTINGS_MODULE` | `tests/` | Config class for tests, normally `config.TestingConfig` |
+| `APP_NAME` | `config.py` | Application name |
+| `SECRET_KEY` | Flask | Flask secret โ **generate a random value** |
+| `JWT_SECRET_KEY` | Flask-JWT-Extended | Token signing key โ **generate a random value**, different from `SECRET_KEY` |
+| `DATABASE_URL` | Develop / Local / Production | SQLAlchemy URL, e.g. `postgresql://user:pass@host:5432/db` or `sqlite:///dev.db` |
+| `DATABASE_TEST_URL` | Testing | SQLAlchemy URL for the test database (tables are created and dropped by every test) |
+| `APP_ENV` | `entrypoint.sh` | `local` or `production` โ decides what the container entrypoint does |
+| `DATABASE` | `entrypoint.sh` | Set to `postgres` to make the entrypoint wait for PostgreSQL before starting |
+| `BBDD_HOST` | `entrypoint.sh` | PostgreSQL host used by the readiness check (`db_service` in Docker Compose) |
+| `POSTGRES_USER` | `entrypoint.sh`, postgres | Database user |
+| `POSTGRES_PASSWORD` | postgres image | Database password |
+| `POSTGRES_DB` | `entrypoint.sh`, postgres | Database name |
+| `PGPASSWORD` | `entrypoint.sh` (`psql`) | Same value as `POSTGRES_PASSWORD`; `psql` needs it for the non-interactive readiness check |
+| `API_ENTRYPOINT` | `entrypoint.sh` | WSGI entrypoint for Gunicorn: `app:app` |
+| `API_HOST` / `API_PORT` | Gunicorn | Bind address, defaults `0.0.0.0` / `5000` |
+| `WEB_CONCURRENCY`, `MAX_WORKERS`, `WORKERS_PER_CORE`, `TIMEOUT`, `GRACEFUL_TIMEOUT`, `KEEP_ALIVE`, `LOG_LEVEL` | Gunicorn | Optional tuning, see [gunicorn/gunicorn_config.py](gunicorn/gunicorn_config.py) |
+| `CORS_ORIGINS` | Flask-CORS | Comma separated allowed origins; empty = no cross-origin access (Develop defaults to `*`) |
+| `RATELIMIT_LOGIN` / `RATELIMIT_REGISTER` | Flask-Limiter | Limits for `/login` and `/register`, defaults `5 per minute` / `3 per minute` |
+| `RATELIMIT_STORAGE_URI` | Flask-Limiter | Limit counter storage, default `memory://` (per process); e.g. `redis://redis:6379` |
+| `TRUSTED_PROXY_COUNT` | `ProxyFix` | Reverse proxies whose `X-Forwarded-*` headers are trusted; `0` (Develop), `1` (Local/Prod) |
+
+> **The `logs/` directory must exist** before the application is imported: `config.py` points the file logger at `logs/api.log` (or `logs/api_tests.log` for tests) and the app fails with `FileNotFoundError` otherwise. The directory is not committed (its content is git-ignored), so create it once after cloning โ every section below includes that step.
+
+### Develop
+
+Run the API directly on your machine with Flask's development server.
+
+**1. Clone and create the virtual environment**
+
+Bash:
+
+```bash
+git clone https://github.com/vectornguyen76/flask-rest-api-template.git
+cd flask-rest-api-template
+
+# Option A โ venv
+python3.10 -m venv venv
+source venv/bin/activate
+
+# Option B โ conda
+conda create -n flask-template python=3.10 -y
+conda activate flask-template
+
+pip install -r requirements-dev.txt # runtime + linters/test tools
+mkdir -p logs
```
-5. **Run all the tests**
+PowerShell:
+
+```powershell
+git clone https://github.com/vectornguyen76/flask-rest-api-template.git
+Set-Location flask-rest-api-template
+
+# Option A โ venv (if activation is blocked, see "Windows / PowerShell Notes")
+py -3.10 -m venv venv
+.\venv\Scripts\Activate.ps1
-```shell
-flask tests
+# Option B โ conda (run "conda init powershell" once, then reopen the terminal)
+conda create -n flask-template python=3.10 -y
+conda activate flask-template
+
+pip install -r requirements-dev.txt # runtime + linters/test tools
+New-Item -ItemType Directory -Force -Path logs | Out-Null
```
-6. **Run unit tests**
+**2. Create a `.env` file** in the project root (git-ignored). Either point `DATABASE_URL` at a PostgreSQL instance (for example the one from [Local](#local): `docker compose up -d db_service`), or use SQLite for a zero-setup start:
-```shell
-flask tests_unit
+```dotenv
+APP_NAME=flask-rest-api-template
+APP_SETTINGS_MODULE=config.DevelopConfig
+APP_TEST_SETTINGS_MODULE=config.TestingConfig
+SECRET_KEY=
+JWT_SECRET_KEY=
+DATABASE_URL=sqlite:///dev.db
+DATABASE_TEST_URL=sqlite:///test.db
```
-7. **Run integration tests**
+If you prefer not to use a `.env` file, export the variables in the shell instead:
-```shell
-flask tests_integration
+```bash
+# Bash
+export APP_SETTINGS_MODULE=config.DevelopConfig
```
-8. **Run API tests**
+```powershell
+# PowerShell (current session only)
+$env:APP_SETTINGS_MODULE = "config.DevelopConfig"
+```
-```shell
-flask tests_api
+**3. Create the schema, seed the default accounts and run**
+
+```bash
+flask create-db
+flask create-user-admin
+flask run
```
-9. **Run coverage**
+The API is now on and Swagger UI on .
+
+**4. Quick smoke test** โ log in as the seeded `admin` and call a protected endpoint:
-```shell
-flask coverage
+Bash:
+
+```bash
+TOKEN=$(curl -s -X POST http://127.0.0.1:5000/login \
+ -H "Content-Type: application/json" \
+ -d '{"username":"admin","password":"123456"}' | python -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
+
+curl -s http://127.0.0.1:5000/user -H "Authorization: Bearer $TOKEN"
```
-10. **Run coverage report**
+PowerShell:
+
+```powershell
+$login = Invoke-RestMethod -Method Post -Uri http://127.0.0.1:5000/login `
+ -ContentType "application/json" `
+ -Body '{"username":"admin","password":"123456"}'
-```shell
-flask coverage_report
+Invoke-RestMethod -Uri http://127.0.0.1:5000/user -Headers @{ Authorization = "Bearer $($login.access_token)" }
```
-### Local
+(In Windows PowerShell 5.1, `curl` is an alias of `Invoke-WebRequest`; use `curl.exe` if you want the real curl.)
-Containerized services separately with PostgreSQL databases (db), API (api) and Nginx reverse proxy (nginx) with Docker and docker-compose.
+### Testing
-1. **Create `.env.api.local`, `.env.db.local` files**
+Tests live in `tests/unit` and `tests/integration` and are discovered with the pattern `tests_*.py`. They build the app from `APP_TEST_SETTINGS_MODULE` and create/drop all tables on `DATABASE_TEST_URL` around every test, so **point `DATABASE_TEST_URL` at a throw-away database**.
- 1. **.env.api.local**
+```bash
+flask tests # run all tests
+flask tests --pattern "tests_users_*.py" # run a subset
+flask cov # tests + coverage summary in the terminal
+flask cov-html # tests + HTML report in report/htmlcov/
+```
- ```shell
- # APP configuration
- APP_NAME=[Name APP] # For example Flask API Rest Template
- APP_ENV=local
+The CI pipelines run the same `python -m flask tests` against a PostgreSQL service container with `DATABASE_TEST_URL=postgresql://db_user:db_password@localhost/db_test`. To reproduce that locally:
- # Flask configuration
- API_ENTRYPOINT=app:app
- APP_SETTINGS_MODULE=config.LocalConfig
- APP_TEST_SETTINGS_MODULE=config.TestingConfig
+```bash
+docker compose up -d db_service
+```
- # API service configuration
- API_HOST= # For example 0.0.0.0
- API_PORT= # For example 5000
+and set `DATABASE_TEST_URL=postgresql://:@localhost:5432/` in your `.env`.
- # Database service configuration
- DATABASE=postgres
- DB_HOST= # For example db_service (name service in docker-compose)
- DB_PORT= # For example 5432 (port service in docker-compose)
- POSTGRES_DB= # For example db_dev
- POSTGRES_USER= # For example db_user
- PGPASSWORD= # For example db_password
+### Local
- # Secret key
- SECRET_KEY=
- JWT_SECRET_KEY=
+The `local` environment runs the full stack with Docker Compose: `api_service` (Gunicorn, port 5000), `db_service` (PostgreSQL 14, port 5432) and `nginx_service` (port 80). The container entrypoint waits for PostgreSQL, runs `flask create-db` and `flask create-user-admin`, then starts Gunicorn.
- DATABASE_TEST_URL= # For example postgresql+psycopg2://db_user:db_password@db_service:5432/db_test
- DATABASE_URL= # For example postgresql+psycopg2://db_user:db_password@db_service:5432/db_dev
- ```
+**1. Create the two env files** in the project root (both are git-ignored and docker-ignored):
- 2. **.env.db.local**:
+`.env.db.local`
- ```shell
- POSTGRES_USER= # For example db_user
- POSTGRES_PASSWORD= # For example db_password
- POSTGRES_DB= # For example db_dev
- ```
+```dotenv
+POSTGRES_USER=db_user
+POSTGRES_PASSWORD=
+POSTGRES_DB=flask_template
+```
-2. **Build and run services**
- `shell docker-compose up --build ` 2. Stop services:
- `shell docker-compose stop ` 3. Delete services:
- `shell docker compose down ` 4. Remove services (removing volumes):
- `shell docker-compose down -v ` 4. Remove services (removing volumes and images):
- `shell docker-compose down -v --rmi all ` 5. View services:
- `shell docker-compose ps `
- **NOTE:** The Rest API defaults to host _localhost_ and port _80_.
+`.env.api.local`
+
+```dotenv
+APP_NAME=flask-rest-api-template
+APP_SETTINGS_MODULE=config.LocalConfig
+APP_ENV=local
+SECRET_KEY=
+JWT_SECRET_KEY=
+
+# Database โ must match .env.db.local
+DATABASE=postgres
+BBDD_HOST=db_service
+POSTGRES_USER=db_user
+POSTGRES_PASSWORD=
+PGPASSWORD=
+POSTGRES_DB=flask_template
+DATABASE_URL=postgresql://db_user:@db_service:5432/flask_template
+
+# Gunicorn
+API_ENTRYPOINT=app:app
+API_HOST=0.0.0.0
+API_PORT=5000
+```
-### Production
+> `PGPASSWORD` is required: `entrypoint.sh` polls the database with `psql`, which cannot prompt for a password inside a container. Without it the container loops on `Waiting for PostgreSQL...` forever.
-Apply CI/CD with Github Actions to automatically deployed to AWS platform use EC2, RDS PostgresSQL.
+**2. Build and start** (identical in Bash and PowerShell):
-1. Create file **.env.pro** and enter the environment variables needed for production. For example:
+```bash
+docker compose up -d --build
+docker compose logs -f api_service # watch the entrypoint / Gunicorn output
+```
- ```shell
- # APP configuration
- APP_NAME=Flask API Rest Template
- APP_ENV=production
+- API through Nginx: โ Swagger UI:
+- API directly:
+- Application logs are written to `./logs/api.log` on the host (bind mount, must be writable by uid 1000 โ see [container user](#other-things-to-know-before-going-to-production)), Nginx logs to `./nginx/log/`.
- # Flask configuration
- API_ENTRYPOINT=app:app
- APP_SETTINGS_MODULE=config.ProductionConfig
+**3. Stop**
- # API service configuration
- API_HOST= # For example 0.0.0.0
+```bash
+docker compose down # keep the database volume
+docker compose down -v # also delete the postgresql_data volume
+```
- # Secret key
- SECRET_KEY=
- JWT_SECRET_KEY=
+### Production
- # Database service configuration
- DATABASE_URL= # For example sqlite:///production.db
+In production the same image is started with `APP_ENV=production` and `APP_SETTINGS_MODULE=config.ProductionConfig`. In that mode the entrypoint does **not** create the schema or seed accounts โ run migrations (see [Flask-migrate](#flask-migrate)) as a separate, deliberate step โ and starts Gunicorn with `--bind $API_HOST:$API_PORT --workers 4 --timeout 10`.
- # Deploy platform
- PLATFORM_DEPLOY=AWS
- ```
+The staging and production GitHub Actions pipelines build and push the image to Docker Hub, create an EC2 host with CloudFormation, and use Ansible to unzip the deployment archive on the server and run `docker compose up -d`. See [.github/workflows/README.md](.github/workflows/README.md) for the required GitHub _Secrets_ and _Variables_.
-## Flask Commands
+Because the archive never contains `.env*` files, **`.env.api.local` and `.env.db.local` must already exist on the server** (in `/home/ubuntu/server`) with production values โ provision them through your secrets manager, Ansible Vault, or by hand over SSH. Never add them to the repository or the archive to "make it work".
-### Flask-cli
+## Windows / PowerShell Notes
-- Create all tables in the database:
+- **Script execution policy.** If `.\venv\Scripts\Activate.ps1` fails with "running scripts is disabled on this system", allow locally-created scripts for your user:
- ```sh
- flask create_db
+ ```powershell
+ Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
```
-- Delete all tables in the database:
+- **Line endings.** `entrypoint.sh` runs inside a Linux container and **must keep LF line endings**; with CRLF the container fails with `exec /app/entrypoint.sh: no such file or directory`. The repository's `.gitattributes` (`*.sh text eol=lf`) enforces this on checkout regardless of your `core.autocrlf` setting, but editors can still convert it when saving. Check with:
- ```sh
- flask drop_db
+ ```powershell
+ git ls-files --eol entrypoint.sh
+ # expected: i/lf w/lf attr/text eol=lf entrypoint.sh
```
-- Create admin user for the Rest API:
+ If the working-tree side shows `w/crlf`, restore it with `git checkout -- entrypoint.sh`.
- ```sh
- flask create-user-admin
- ```
+- **Environment variables.** `$env:NAME = "value"` only lasts for the current PowerShell session. Prefer the `.env` file, which Flask loads automatically on every platform.
-- Database reset:
+- **Paths.** Use `Set-Location` / `cd` and backslashes or forward slashes interchangeably; Docker Compose bind mounts (`./logs`, `./nginx`) work unchanged with Docker Desktop (WSL 2 backend recommended).
- ```sh
- flask reset-db
- ```
+- **`curl`.** In Windows PowerShell 5.1 `curl` is an alias for `Invoke-WebRequest`. Use `curl.exe` for the real binary or the `Invoke-RestMethod` examples in this README.
-- Run tests without coverage:
+- **Docker commands** (`docker compose ...`) are identical in both shells.
- ```sh
- flask reset-db
- ```
+## Creating Deployment Archive
-- Run tests with coverage without report in html:
+The production/staging pipelines zip the repository checkout (`zip -qq -r artifact.zip .`) and Ansible extracts it on the server. Because CI runs on a clean checkout, no secrets can end up in that archive. When creating one **by hand**, exclude everything that is local, generated or secret:
- ```sh
- flask cov
- ```
+**Bash**
-- Run tests with coverage with report in html:
- ```sh
- flask cov-html
- ```
+```bash
+zip -r artifact.zip . \
+ -x '.git/*' '.env*' 'logs/*' 'nginx/log/*' 'venv/*' '.venv/*' \
+ '*/__pycache__/*' '*.pyc' 'report/*' '*.db'
+```
-## Database commands
+**PowerShell**
-### Flask-migrate
+```powershell
+Get-ChildItem -Path . -Force -Exclude .git, .env*, logs, venv, .venv, report, *.db |
+ Compress-Archive -DestinationPath artifact.zip -Force
+```
-- Create a migration repository:
+Then verify the archive before shipping it:
- ```sh
- flask db init
- ```
+```bash
+# Bash
+unzip -l artifact.zip | grep -E '\.env|\.git/'
+```
-- Generate a migration version:
+```powershell
+# PowerShell
+Add-Type -AssemblyName System.IO.Compression.FileSystem
+[IO.Compression.ZipFile]::OpenRead("$PWD\artifact.zip").Entries.FullName | Select-String -Pattern '\.env|\.git/'
+```
- ```sh
- flask db migrate -m "Init"
- ```
+Both must return nothing.
-- Apply migration to the Database:
- ```sh
- flask db upgrade
- ```
+## Flask Commands
-## Swagger
+### Flask-cli
+Custom commands are registered in [manage.py](manage.py) and are available through the `flask` CLI once `APP_SETTINGS_MODULE` (and a database URL) is set. Run `flask --help` to list them.
+
+| Command | Description | Available in production |
+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
+| `flask create-db` | Create all tables (`db.create_all()`) | yes |
+| `flask reset-db` | Drop and recreate all tables โ **destroys data** | yes |
+| `flask drop-db` | Drop all tables โ **destroys data** | yes |
+| `flask create-user-admin` | Seed permissions, roles and the three [default accounts](#default-seed-accounts) if `admin` does not exist; otherwise make sure the `admin` permission exists and is granted to the Admin role (upgrade path) | yes |
+| `flask tests [--pattern]` | Run the unittest suite | no |
+| `flask cov [--pattern]` | Run the tests with a coverage summary (needs `requirements-dev.txt`) | no |
+| `flask cov-html [--pattern]` | Run the tests and write an HTML coverage report to `report/htmlcov/` | no |
+| `flask routes` | List all registered routes (built-in) | yes |
+| `flask run` | Start the development server (built-in, **not** for production โ use Gunicorn) | yes |
+
+The `flask` CLI locates the application automatically through the `app` package, so `FLASK_APP` does not need to be set.
+
+## Database Commands
+
+### Flask-migrate
+
+Flask-Migrate (Alembic) is initialised in `app/__init__.py`, so the standard commands are available:
+
+```bash
+flask db init # once โ creates the migrations/ folder
+flask db migrate -m "add column" # autogenerate a revision from model changes
+flask db upgrade # apply pending revisions
+flask db downgrade # roll back one revision
+flask db history # show revisions
```
-http://localhost:/swagger-ui
-```
+
+> **Note:** this template's `.gitignore` lists `migrations/`, so generated migrations are **not** committed by default. For a real project you will almost certainly want to remove that line and version your migrations, otherwise production schema changes cannot be reproduced.
+
+## API Endpoints
+
+All endpoints except `/login` and `/register` require `Authorization: Bearer `. The permission column is enforced by the `permission_required` decorator through the user's roles (see [How authorization works](#how-authorization-works)). Unknown ids return a JSON `404`.
+
+| Method | Path | Permission | Description |
+| ------ | --------------------------------- | -------------- | ------------------------------------------------------------- |
+| POST | `/register` | โ | Create a user (gets the `Guest` role) |
+| POST | `/login` | โ | Returns `access_token` and `refresh_token` |
+| POST | `/refresh` | refresh token | New (non-fresh) token pair; the used refresh token is revoked |
+| POST | `/logout` | any token | Revoke the access token and its paired refresh token |
+| GET | `/user` | read | List users |
+| GET | `/user/` | read | Get a user |
+| PUT | `/user/` | self, or admin | Update own username / password; admin may also set `roles` |
+| PUT | `/block-user/` | admin | Block or unblock a user (not yourself) |
+| POST | `/user//role/` | admin | Assign a role to a user |
+| DELETE | `/user//role/` | admin | Remove a role from a user |
+| GET | `/role`, `/role/` | read | List / get roles |
+| POST | `/role` | admin | Create a role |
+| PUT | `/role/` | admin | Update a role and its permissions |
+| DELETE | `/role/` | admin | Delete a role |
+| GET | `/permission`, `/permission/` | read | List / get permissions |
+| POST | `/permission` | admin | Create a permission |
+| PUT | `/permission/` | admin | Update a permission |
+| PUT | `/permission-role-update` | admin | Replace the roles of one or more permissions |
+| GET | `/role-permission` | read | List role โ permission links |
+
+A Postman environment is provided in [tests/postman/](tests/postman/FlaskTemplate.postman_environment.json) (`HOST`, `TOKEN`, `REFRESHTOKEN`).
+
+## Swagger
+
+Interactive documentation is generated by flask-smorest from the Marshmallow schemas:
+
+- Swagger UI: `http:///swagger-ui` (e.g. in develop, through Nginx in local)
+- OpenAPI document: `http:///openapi.json`
+
+Click **Authorize** and enter `Bearer ` to call protected endpoints from the UI.
-
+
+## CI/CD Status
+
+The badges at the top of this file show the status of the three GitHub Actions workflows:
+
+| Workflow | Trigger | What it does |
+| ----------- | --------------------------- | ------------------------------------------------------------------------------------- |
+| Development | PR into / push to `develop` | isort, black, flake8, tests against PostgreSQL, build & push image |
+| Staging | PR into `staging` | Same as development + CloudFormation stack, Ansible deploy, A/B clean-up of old stack |
+| Production | PR into `master` | Same as staging, targeting the production stack |
+
+Details, required secrets and variables: [.github/workflows/README.md](.github/workflows/README.md). CloudFormation helper commands: [.github/workflows/cloudformations/README.md](.github/workflows/cloudformations/README.md).
+
## Reference
-- [Udemy - REST APIs with Flask and Python in 2023](https://www.udemy.com/course/rest-api-flask-and-python/)
-- [Github - Flask API REST Template](https://github.com/igp7/flask-rest-api-template)
-- [Github - Uvicorn Gunicorn Fastapi Docker](https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker)
+- [Flask](https://flask.palletsprojects.com/) ยท [Flask-SQLAlchemy](https://flask-sqlalchemy.palletsprojects.com/) ยท [Flask-Migrate](https://flask-migrate.readthedocs.io/)
+- [Flask-JWT-Extended](https://flask-jwt-extended.readthedocs.io/) ยท [flask-smorest](https://flask-smorest.readthedocs.io/) ยท [Marshmallow](https://marshmallow.readthedocs.io/)
+- [Gunicorn settings](https://docs.gunicorn.org/en/stable/settings.html) ยท [Docker Compose](https://docs.docker.com/compose/)
+- [python-dotenv and the Flask CLI](https://flask.palletsprojects.com/en/2.2.x/cli/#environment-variables-from-dotenv)
+- [PowerShell execution policies](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_execution_policies)
## Contribution
-Feel free to make any suggestions or improvements to the project.
+1. Fork the repository and create a branch from `develop`.
+2. Install the pre-commit hooks so that formatting and secret detection run before every commit:
+
+ ```bash
+ pip install pre-commit
+ pre-commit install
+ pre-commit run --all-files # optional: check the whole tree once
+ ```
+
+ The hooks run `isort` (black profile), `black`, `flake8`, `prettier` (Markdown/YAML/JSON), `detect-private-key`, `end-of-file-fixer` and `trailing-whitespace` โ the same checks as the CI pipeline.
+
+3. Add or update tests under `tests/` and make sure `flask tests` passes.
+4. Open a pull request into `develop`. Do not include `.env*` files, logs, databases or coverage reports.
diff --git a/app/__init__.py b/app/__init__.py
index ab57a0c..4c64cde 100644
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -1,11 +1,12 @@
import os
from flask import Flask
+from werkzeug.middleware.proxy_fix import ProxyFix
import manage
from app.blueprint import register_routing
from app.db import db
-from app.extention import cors, migrate
+from app.extention import cors, limiter, migrate
from app.utils.auth import jwt
from app.utils.logging import configure_logging
@@ -14,11 +15,25 @@ def create_app(settings_module):
app = Flask(__name__)
app.config.from_object(settings_module)
+ # Trust X-Forwarded-* from the configured number of reverse proxies so that
+ # request.remote_addr (logs, rate limiting) is the real client address.
+ proxies = app.config["TRUSTED_PROXY_COUNT"]
+ if proxies > 0:
+ app.wsgi_app = ProxyFix(
+ app.wsgi_app, x_for=proxies, x_proto=proxies, x_host=proxies
+ )
+
# Initialize the extensions
db.init_app(app)
migrate.init_app(app, db)
jwt.init_app(app)
- cors.init_app(app, supports_credentials="true", resources={r"*": {"origins": "*"}})
+ limiter.init_app(app)
+ # No CORS headers at all unless origins are configured. Credentials are not
+ # needed: authentication is a bearer token, not a cookie.
+ if app.config["CORS_ORIGINS"]:
+ cors.init_app(
+ app, origins=app.config["CORS_ORIGINS"], supports_credentials=False
+ )
manage.init_app(app)
# Logging configuration
diff --git a/app/extention.py b/app/extention.py
index d311947..6e46bd3 100644
--- a/app/extention.py
+++ b/app/extention.py
@@ -1,7 +1,12 @@
from flask_cors import CORS
from flask_jwt_extended import JWTManager
+from flask_limiter import Limiter
+from flask_limiter.util import get_remote_address
from flask_migrate import Migrate
migrate = Migrate()
jwt = JWTManager()
cors = CORS()
+# Limits are keyed by client IP; see TRUSTED_PROXY_COUNT in config.py when
+# running behind a reverse proxy.
+limiter = Limiter(key_func=get_remote_address)
diff --git a/app/routers/permission_router.py b/app/routers/permission_router.py
index 53fcd39..b8fcebc 100644
--- a/app/routers/permission_router.py
+++ b/app/routers/permission_router.py
@@ -5,6 +5,7 @@
from app.schemas.permission_schema import UpdatePermissionRoleSchema
from app.schemas.role_permission_schema import PermissionSchema
from app.services import permission_service, role_permission_service
+from app.utils.authorization import ADMIN_PERMISSION
from app.utils.decorators import permission_required
blp = Blueprint("Permission", __name__, description="Permission API")
@@ -20,10 +21,10 @@ def get(self):
return result
@jwt_required()
- @permission_required(permission_name="write")
+ @permission_required(permission_name=ADMIN_PERMISSION)
@blp.arguments(PermissionSchema)
- def post(self, qa_history_data):
- result = permission_service.post_permission(qa_history_data)
+ def post(self, permission_data):
+ result = permission_service.post_permission(permission_data)
return result
@@ -37,7 +38,7 @@ def get(self, permission_id):
return result
@jwt_required()
- @permission_required(permission_name="write")
+ @permission_required(permission_name=ADMIN_PERMISSION)
@blp.arguments(PermissionSchema)
def put(self, permission_data, permission_id):
result = permission_service.update_permission(permission_data, permission_id)
@@ -47,7 +48,7 @@ def put(self, permission_data, permission_id):
@blp.route("/permission-role-update")
class PermissionRole(MethodView):
@jwt_required()
- @permission_required(permission_name="write")
+ @permission_required(permission_name=ADMIN_PERMISSION)
@blp.arguments(UpdatePermissionRoleSchema)
def put(self, permission_data):
result = role_permission_service.update_roles_to_permission(permission_data)
diff --git a/app/routers/role_router.py b/app/routers/role_router.py
index 7c42c0f..d488838 100644
--- a/app/routers/role_router.py
+++ b/app/routers/role_router.py
@@ -4,6 +4,7 @@
from app.schemas.role_permission_schema import RoleSchema, UpdateRolePermissionSchema
from app.services import role_service
+from app.utils.authorization import ADMIN_PERMISSION
from app.utils.decorators import permission_required
blp = Blueprint("Role", __name__, description="Role API")
@@ -19,10 +20,10 @@ def get(self):
return result
@jwt_required()
- @permission_required(permission_name="write")
+ @permission_required(permission_name=ADMIN_PERMISSION)
@blp.arguments(UpdateRolePermissionSchema)
- def post(self, qa_history_data):
- result = role_service.post_role(qa_history_data)
+ def post(self, role_data):
+ result = role_service.post_role(role_data)
return result
@@ -36,14 +37,14 @@ def get(self, role_id):
return result
@jwt_required()
- @permission_required(permission_name="write")
+ @permission_required(permission_name=ADMIN_PERMISSION)
@blp.arguments(UpdateRolePermissionSchema)
def put(self, role_data, role_id):
result = role_service.update_role(role_data, role_id)
return result
@jwt_required()
- @permission_required(permission_name="delete")
+ @permission_required(permission_name=ADMIN_PERMISSION)
def delete(self, role_id):
result = role_service.delete_role(role_id)
return result
diff --git a/app/routers/user_role_router.py b/app/routers/user_role_router.py
index 114fd43..e6fd0df 100644
--- a/app/routers/user_role_router.py
+++ b/app/routers/user_role_router.py
@@ -5,6 +5,7 @@
from app.schemas.role_permission_schema import RoleSchema
from app.schemas.user_schema import UserAndRoleSchema
from app.services import user_role_service
+from app.utils.authorization import ADMIN_PERMISSION
from app.utils.decorators import permission_required
blp = Blueprint("User And Role", __name__, description="User And Role API")
@@ -13,14 +14,14 @@
@blp.route("/user//role/")
class LinkRolesToUser(MethodView):
@jwt_required()
- @permission_required(permission_name="write")
+ @permission_required(permission_name=ADMIN_PERMISSION)
@blp.response(201, RoleSchema)
def post(self, user_id, role_id):
result = user_role_service.link_roles_to_user(user_id, role_id)
return result
@jwt_required()
- @permission_required(permission_name="delete")
+ @permission_required(permission_name=ADMIN_PERMISSION)
@blp.response(200, UserAndRoleSchema)
def delete(self, user_id, role_id):
result = user_role_service.delete_roles_to_user(user_id, role_id)
diff --git a/app/routers/user_router.py b/app/routers/user_router.py
index 042c850..4503c6b 100644
--- a/app/routers/user_router.py
+++ b/app/routers/user_router.py
@@ -1,9 +1,12 @@
+from flask import current_app
from flask.views import MethodView
-from flask_jwt_extended import get_jwt, jwt_required
+from flask_jwt_extended import jwt_required
from flask_smorest import Blueprint
+from app.extention import limiter
from app.schemas.user_schema import UpdateBlockUserSchema, UserSchema, UserUpdateSchema
from app.services import user_service
+from app.utils.authorization import ADMIN_PERMISSION
from app.utils.decorators import permission_required
blp = Blueprint("User", __name__, description="User API")
@@ -29,9 +32,9 @@ def get(self, user_id):
return result
@jwt_required()
- @permission_required(permission_name="write")
@blp.arguments(UserUpdateSchema)
def put(self, user_data, user_id):
+ # Authorization is in the service: self-update, or admin for any user
result = user_service.update_user(user_data, user_id)
return result
@@ -39,7 +42,7 @@ def put(self, user_data, user_id):
@blp.route("/block-user/")
class BlockUser(MethodView):
@jwt_required()
- @permission_required(permission_name="delete")
+ @permission_required(permission_name=ADMIN_PERMISSION)
@blp.arguments(UpdateBlockUserSchema)
def put(self, user_data, user_id):
result = user_service.update_block_user(user_data, user_id)
@@ -48,6 +51,9 @@ def put(self, user_data, user_id):
@blp.route("/login")
class Login(MethodView):
+ # Brute-force protection; limit string comes from config (RATELIMIT_LOGIN)
+ decorators = [limiter.limit(lambda: current_app.config["RATELIMIT_LOGIN"])]
+
@blp.arguments(UserSchema)
def post(self, user_data):
result = user_service.login_user(user_data)
@@ -56,6 +62,8 @@ def post(self, user_data):
@blp.route("/register")
class Register(MethodView):
+ decorators = [limiter.limit(lambda: current_app.config["RATELIMIT_REGISTER"])]
+
@blp.arguments(UserSchema)
def post(self, user_data):
result = user_service.register_user(user_data)
@@ -66,11 +74,9 @@ def post(self, user_data):
class Logout(MethodView):
@jwt_required()
def post(self):
- # Block access_token
- jti = get_jwt()["jti"]
- user_service.add_jti_blocklist(jti)
-
- return {"message": "Logout successfully!"}
+ # Revokes the access token and its paired refresh token
+ result = user_service.logout_user()
+ return result
@blp.route("/refresh")
diff --git a/app/schemas/permission_schema.py b/app/schemas/permission_schema.py
index c0086a0..13f1ee6 100644
--- a/app/schemas/permission_schema.py
+++ b/app/schemas/permission_schema.py
@@ -4,7 +4,7 @@
class PlainPermissionSchema(Schema):
id = fields.Int(dump_only=True)
name = fields.Str(required=True)
- route = fields.Str(required=True)
+ description = fields.Str(allow_none=True, load_default=None)
class UpdatePermissionRoleSchema(Schema):
diff --git a/app/schemas/user_schema.py b/app/schemas/user_schema.py
index 7c8baaf..1010c2a 100644
--- a/app/schemas/user_schema.py
+++ b/app/schemas/user_schema.py
@@ -8,14 +8,18 @@ class PlainUserSchema(Schema):
# Dump only: only read
id = fields.Str(dump_only=True)
username = fields.Str(required=True)
- password = fields.Str(required=True)
+ # load_only: accepted on input (login/register) but never serialized in a
+ # response, so password hashes are not exposed by GET /user endpoints.
+ password = fields.Str(required=True, load_only=True)
time_created = fields.Str(dump_only=True)
class UserUpdateSchema(Schema):
- username = fields.Str(allow_none=True, required=True)
- password = fields.Str(allow_none=True, required=True)
- roles = fields.List(cls_or_instance=fields.Int, required=True)
+ # All fields optional: omitted / null fields are left unchanged.
+ # "roles" may only be set by an admin (enforced in user_service.update_user).
+ username = fields.Str(allow_none=True, load_default=None)
+ password = fields.Str(allow_none=True, load_only=True, load_default=None)
+ roles = fields.List(fields.Int, allow_none=True, load_default=None)
class UserSchema(PlainUserSchema):
diff --git a/app/services/permission_service.py b/app/services/permission_service.py
index 2ccfd3a..a90858a 100644
--- a/app/services/permission_service.py
+++ b/app/services/permission_service.py
@@ -5,6 +5,7 @@
from app.db import db
from app.models.permission_model import PermissionModel
+from app.utils.authorization import ensure_caller_keeps_admin, get_or_404
# Create logger for this module
logger = logging.getLogger(__name__)
@@ -24,10 +25,10 @@ def post_permission(permission_data):
db.session.add(new_row)
db.session.commit()
- except Exception as ex:
+ except Exception:
db.session.rollback()
- logger.error(f"Can not add permission! Error: {ex}")
- abort(400, message=f"Can not add permission! Error: {ex}")
+ logger.exception("Can not add permission!")
+ abort(400, message="Can not add permission!")
return {"message": "Add successfully!"}
@@ -38,23 +39,22 @@ def get_permission(permission_id):
def update_permission(permission_data, permission_id):
- permission = PermissionModel.query.filter_by(id=permission_id).first()
+ permission = get_or_404(PermissionModel, permission_id, "Permission")
- if not permission:
- logger.error("permission doesn't exist, cannot update!")
- abort(400, message="permission doesn't exist, cannot update!")
+ if permission_data["name"]:
+ permission.name = permission_data["name"]
- try:
- if permission_data["name"]:
- permission.name = permission_data["name"]
+ if permission_data["description"]:
+ permission.description = permission_data["description"]
- if permission_data["description"]:
- permission.description = permission_data["description"]
+ # Renaming the admin permission would lock every admin out
+ ensure_caller_keeps_admin()
+ try:
db.session.commit()
- except Exception as ex:
+ except Exception:
db.session.rollback()
- logger.error(f"Can not update permission! Error: {ex}")
- abort(400, message=f"Can not update permission! Error: {ex}")
+ logger.exception("Can not update permission!")
+ abort(400, message="Can not update permission!")
return {"message": "Update successfully!"}
diff --git a/app/services/role_permission_service.py b/app/services/role_permission_service.py
index 8b7f7c6..96a8ea1 100644
--- a/app/services/role_permission_service.py
+++ b/app/services/role_permission_service.py
@@ -6,6 +6,7 @@
from app.models.permission_model import PermissionModel
from app.models.role_model import RoleModel
from app.models.role_permission_model import RolePermissionModel
+from app.utils.authorization import ensure_caller_keeps_admin, get_or_404
# Create logger for this module
logger = logging.getLogger(__name__)
@@ -17,20 +18,26 @@ def get_role_permission():
def update_roles_to_permission(permission_data):
- for permission_id in permission_data["data_update"]:
- permission = PermissionModel.query.filter_by(id=int(permission_id)).first()
+ """
+ Replace the roles of each permission in {permission_id: [role_id, ...]}.
+ All changes are applied in a single transaction.
+ """
+ for permission_id, role_ids in permission_data["data_update"].items():
+ try:
+ permission_id = int(permission_id)
+ except (TypeError, ValueError):
+ abort(400, message=f"Invalid permission id: {permission_id!r}")
- permission.roles = []
+ permission = get_or_404(PermissionModel, permission_id, "Permission")
+ permission.roles = [get_or_404(RoleModel, rid, "Role") for rid in role_ids]
+
+ ensure_caller_keeps_admin()
+
+ try:
+ db.session.commit()
+ except Exception:
+ db.session.rollback()
+ logger.exception("An error occurred while inserting the roles.")
+ abort(500, message="An error occurred while inserting the roles.")
- for role_id in permission_data["data_update"][permission_id]:
- role = RoleModel.query.filter_by(id=role_id).first()
- permission.roles.append(role)
- try:
- db.session.add(permission)
- db.session.commit()
- except Exception as ex:
- logger.error(f"An error occurred while inserting the roles. Error: {ex}")
- abort(
- 500, message=f"An error occurred while inserting the roles. Error: {ex}"
- )
return {"message": "Update successfully!"}
diff --git a/app/services/role_service.py b/app/services/role_service.py
index 2786aff..b484936 100644
--- a/app/services/role_service.py
+++ b/app/services/role_service.py
@@ -6,36 +6,34 @@
from app.db import db
from app.models.permission_model import PermissionModel
from app.models.role_model import RoleModel
-from app.models.role_permission_model import RolePermissionModel
-from app.models.user_role_model import UserRoleModel
+from app.utils.authorization import ensure_caller_keeps_admin, get_or_404
# Create logger for this module
logger = logging.getLogger(__name__)
+def _permissions_from_ids(permission_ids):
+ return [get_or_404(PermissionModel, pid, "Permission") for pid in permission_ids]
+
+
def get_all_role():
results = RoleModel.query.order_by(asc(RoleModel.id)).all()
return results
def post_role(role_data):
- name = role_data["name"]
- description = role_data["description"]
-
- try:
- new_row = RoleModel(name=name, description=description)
+ permissions = _permissions_from_ids(role_data["permissions"])
- # Add Permission
- for permission_id in role_data["permissions"]:
- permission = PermissionModel.query.filter_by(id=permission_id).first()
- new_row.permissions.append(permission)
+ new_row = RoleModel(name=role_data["name"], description=role_data["description"])
+ new_row.permissions = permissions
+ try:
db.session.add(new_row)
db.session.commit()
- except Exception as ex:
+ except Exception:
db.session.rollback()
- logger.error(f"Can not add role! Error: {ex}")
- abort(400, message=f"Can not add role! Error: {ex}")
+ logger.exception("Can not add role!")
+ abort(400, message="Can not add role!")
return {"message": "Add successfully!"}
@@ -46,44 +44,42 @@ def get_role(role_id):
def update_role(role_data, role_id):
- role = RoleModel.query.filter_by(id=role_id).first()
-
- if not role:
- logger.error("role doesn't exist, cannot update!")
- abort(400, message="role doesn't exist, cannot update!")
+ role = get_or_404(RoleModel, role_id, "Role")
+ permissions = _permissions_from_ids(role_data["permissions"])
- # Updete role
- try:
- role.permissions = []
+ role.permissions = permissions
- for permission_id in role_data["permissions"]:
- permission = PermissionModel.query.filter_by(id=permission_id).first()
- role.permissions.append(permission)
+ if role_data["name"]:
+ role.name = role_data["name"]
- if role_data["name"]:
- role.name = role_data["name"]
+ if role_data["description"]:
+ role.description = role_data["description"]
- if role_data["description"]:
- role.description = role_data["description"]
+ # Changing a role's permissions changes what every user holding it may do
+ ensure_caller_keeps_admin()
- db.session.add(role)
+ try:
db.session.commit()
- except Exception as ex:
+ except Exception:
db.session.rollback()
- logger.error(f"Can not update role! Error: {ex}")
- abort(400, message=f"Can not update role! Error: {ex}")
+ logger.exception("Can not update role!")
+ abort(400, message="Can not update role!")
return {"message": "Update successfully!"}
def delete_role(role_id):
- RolePermissionModel.query.filter_by(role_id=role_id).delete()
- UserRoleModel.query.filter_by(role_id=role_id).delete()
- role = RoleModel.query.filter_by(id=role_id).delete()
+ role = get_or_404(RoleModel, role_id, "Role")
+
+ # ORM delete so the role_permission / user_role link rows are removed too
+ db.session.delete(role)
+ ensure_caller_keeps_admin()
- if not role:
- logger.error("Role doesn't exist, cannot delete!")
- abort(400, message="Role doesn't exist, cannot delete!")
+ try:
+ db.session.commit()
+ except Exception:
+ db.session.rollback()
+ logger.exception("Can not delete role!")
+ abort(400, message="Can not delete role!")
- db.session.commit()
return {"message": "Delete successfully!"}
diff --git a/app/services/user_role_service.py b/app/services/user_role_service.py
index 1d1a1e0..0eaf34d 100644
--- a/app/services/user_role_service.py
+++ b/app/services/user_role_service.py
@@ -5,38 +5,46 @@
from app.db import db
from app.models.role_model import RoleModel
from app.models.user_model import UserModel
+from app.utils.authorization import ensure_caller_keeps_admin, get_or_404
# Create logger for this module
logger = logging.getLogger(__name__)
def link_roles_to_user(user_id, role_id):
- user = UserModel.query.filter_by(id=user_id).first()
- role = RoleModel.query.filter_by(id=role_id).first()
+ user = get_or_404(UserModel, user_id, "User")
+ role = get_or_404(RoleModel, role_id, "Role")
+
+ if role in user.roles:
+ abort(400, message="User already has this role.")
user.roles.append(role)
try:
- db.session.add(user)
db.session.commit()
- except Exception as ex:
- logger.error(f"An error occurred while inserting the role. Error: {ex}")
- abort(500, message=f"An error occurred while inserting the role. Error: {ex}")
+ except Exception:
+ db.session.rollback()
+ logger.exception("An error occurred while inserting the role.")
+ abort(500, message="An error occurred while inserting the role.")
return role
def delete_roles_to_user(user_id, role_id):
- user = UserModel.query.filter_by(id=user_id).first()
- role = RoleModel.query.filter_by(id=role_id).first()
+ user = get_or_404(UserModel, user_id, "User")
+ role = get_or_404(RoleModel, role_id, "Role")
+
+ if role not in user.roles:
+ abort(400, message="User does not have this role.")
user.roles.remove(role)
+ ensure_caller_keeps_admin()
try:
- db.session.add(user)
db.session.commit()
- except Exception as ex:
- logger.error(f"An error occurred while deleting the role. Error: {ex}")
- abort(500, message=f"An error occurred while deleting the role. Error: {ex}")
+ except Exception:
+ db.session.rollback()
+ logger.exception("An error occurred while deleting the role.")
+ abort(500, message="An error occurred while deleting the role.")
return {"message": "User removed from role", "user": user, "role": role}
diff --git a/app/services/user_service.py b/app/services/user_service.py
index 3e38d68..e92962a 100644
--- a/app/services/user_service.py
+++ b/app/services/user_service.py
@@ -3,18 +3,27 @@
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
+ decode_token,
get_jwt,
- get_jwt_identity,
)
from flask_smorest import abort
from passlib.hash import pbkdf2_sha256
from sqlalchemy import asc
+from werkzeug.exceptions import HTTPException
from app.db import db
from app.models.blocklist_model import BlocklistModel
from app.models.role_model import RoleModel
from app.models.user_model import UserModel
-from app.services import user_role_service
+from app.utils.authorization import (
+ current_user_id,
+ current_user_is_admin,
+ ensure_caller_keeps_admin,
+ get_or_404,
+)
+
+# Role given to every newly registered user
+DEFAULT_ROLE_NAME = "Guest"
# Create logger for this module
logger = logging.getLogger(__name__)
@@ -31,98 +40,78 @@ def get_user(user_id):
def update_user(user_data, user_id):
- user = UserModel.query.filter_by(id=user_id).first()
- if not user:
- logger.error("User doesn't exist, cannot update!")
- abort(400, message="User doesn't exist, cannot update!")
+ """
+ Update a user. Users may change their own username / password; only an
+ admin may update other users or change role assignments.
+ """
+ is_admin = current_user_is_admin()
+
+ if not is_admin and user_id != current_user_id():
+ logger.warning("User %s tried to update user %s", current_user_id(), user_id)
+ abort(403, message="You can only update your own account.")
+
+ if user_data.get("roles") is not None and not is_admin:
+ logger.warning("User %s tried to change roles", current_user_id())
+ abort(403, message="Only an admin can change roles.")
+
+ user = get_or_404(UserModel, user_id, "User")
try:
- if user_data["username"]:
+ if user_data.get("username"):
user.username = user_data["username"]
- if user_data["password"]:
+ if user_data.get("password"):
# Hash password
- password = pbkdf2_sha256.hash(user_data["password"])
- user.password = password
+ user.password = pbkdf2_sha256.hash(user_data["password"])
- # Update roles
- user.roles = []
-
- for role_id in user_data["roles"]:
- role = RoleModel.query.filter_by(id=role_id).first()
- user.roles.append(role)
+ if user_data.get("roles") is not None:
+ user.roles = [
+ get_or_404(RoleModel, role_id, "Role") for role_id in user_data["roles"]
+ ]
+ ensure_caller_keeps_admin()
db.session.commit()
- except Exception as ex:
+ except HTTPException:
+ raise
+ except Exception:
db.session.rollback()
- logger.error(f"Can not update! Error: {ex}")
- abort(400, message=f"Can not update! Error: {ex}")
+ logger.exception("Can not update!")
+ abort(400, message="Can not update!")
return {"message": "Update successfully!"}
def update_block_user(user_data, user_id):
- # Only admin can delete user
- jwt = get_jwt()
- if not jwt.get("is_admin"):
- logger.error("Admin privilege requierd.")
- abort(401, message="Admin privilege requierd.")
-
- if user_id == 1:
- logger.error("Can not block Super Admin!")
- abort(401, message="Can not block Super Admin!")
-
- user = UserModel.query.filter_by(id=user_id).first()
+ """
+ Block / unblock a user. Requires the admin permission (enforced by the
+ router); an admin cannot block their own account.
+ """
+ if user_id == current_user_id():
+ abort(400, message="You can not block your own account.")
- if not user:
- logger.error("User doesn't exist, cannot update!")
- abort(400, message="User doesn't exist, cannot update!")
+ user = get_or_404(UserModel, user_id, "User")
try:
# Update status block
user.block = user_data["block"]
- db.session.add(user)
db.session.commit()
- except Exception as ex:
+ except Exception:
db.session.rollback()
- logger.error(f"Can not update status block User! Error: {ex}")
- abort(400, message=f"Can not update status block User! Error: {ex}")
+ logger.exception("Can not update status block User!")
+ abort(400, message="Can not update status block User!")
return {"message": "Block successfully!"}
-def delete_user(id):
- # Only admin can delete user
- jwt = get_jwt()
- if not jwt.get("is_admin"):
- logger.error("Admin privilege requierd.")
- abort(401, message="Admin privilege requierd.")
-
- result = UserModel.query.filter_by(id=id).delete()
- if not result:
- logger.error("User doesn't exist, cannot delete!")
- abort(400, message="User doesn't exist, cannot delete!")
-
- db.session.commit()
- return {"message": "Delete successfully!"}
-
-
def login_user(user_data):
# Check user name
user = UserModel.query.filter(UserModel.username == user_data["username"]).first()
# Verify
if user and pbkdf2_sha256.verify(user_data["password"], user.password):
- # Create access_token
- access_token = create_access_token(identity=user.id, fresh=True)
-
- # Create refresh_token
- refresh_token = create_refresh_token(identity=user.id)
-
logger.info(f"User login successfully! user_name: {user_data['username']}")
-
- return {"access_token": access_token, "refresh_token": refresh_token}
+ return create_token_pair(user.id, fresh=True)
logger.error("Invalid credentials.")
abort(401, message="Invalid credentials.")
@@ -138,58 +127,93 @@ def register_user(user_data):
logger.error("Username already exists.")
abort(400, message="Username already exists.")
+ default_role = RoleModel.query.filter_by(name=DEFAULT_ROLE_NAME).first()
+ if default_role is None:
+ logger.error(
+ "Default role '%s' is missing - run `flask create-user-admin`",
+ DEFAULT_ROLE_NAME,
+ )
+ abort(500, message="Registration is not available.")
+
# Hash password
password = pbkdf2_sha256.hash(password)
new_user = UserModel(username=username, password=password)
+ new_user.roles.append(default_role)
try:
db.session.add(new_user)
db.session.commit()
-
- except Exception as ex:
+ except Exception:
db.session.rollback()
- logger.error(f"Can not register! Error: {ex}")
- abort(400, message=f"Can not register! Error: {ex}")
+ logger.exception("Can not register!")
+ abort(400, message="Can not register!")
- try:
- # Add default role for user
- user_role_service.link_roles_to_user(user_id=new_user.id, role_id=3)
+ return {"message": "Register successfully!"}
- except Exception as ex:
- logger.error(f"Can not register! - Can not add role default. Error: {ex}")
- abort(400, message=f"Can not register! - Can not add role default. Error: {ex}")
- return {"message": "Register successfully!"}
+def create_token_pair(user_id, fresh=False):
+ """
+ Create an access/refresh token pair.
+ The refresh token is created first so that its jti can be embedded in the
+ access token (claim "refresh_jti"). That lets /logout revoke both tokens
+ of the pair even though the client only presents the access token.
+ """
+ # "sub" must be a string (RFC 7519); see authorization.current_user_id()
+ identity = str(user_id)
-def refresh_token():
- # Get id current user
- current_user_id = get_jwt_identity()
+ refresh_token = create_refresh_token(identity=identity)
+ refresh_jti = decode_token(refresh_token)["jti"]
- # Create access_token
- access_token = create_access_token(identity=current_user_id, fresh=True)
+ access_token = create_access_token(
+ identity=identity,
+ fresh=fresh,
+ additional_claims={"refresh_jti": refresh_jti},
+ )
- # Create refresh_token
- refresh_token = create_refresh_token(identity=current_user_id)
+ return {"access_token": access_token, "refresh_token": refresh_token}
- # Block previous access_token
- jti = get_jwt()["jti"]
- # Block access token
- add_jti_blocklist(jti)
+def logout_user():
+ """
+ Revoke the current access token and the refresh token that was issued
+ together with it.
+ """
+ jwt = get_jwt()
+ add_jti_blocklist(jwt["jti"])
- return {"access_token": access_token, "refresh_token": refresh_token}
+ refresh_jti = jwt.get("refresh_jti")
+ if refresh_jti:
+ add_jti_blocklist(refresh_jti)
+
+ return {"message": "Logout successfully!"}
+
+
+def refresh_token():
+ # Get id current user
+ user_id = current_user_id()
+
+ # Refresh tokens are single-use: revoke the one that was just presented.
+ # NOTE: the access token that was paired with it is *not* revoked here
+ # (its jti is not known in this context) and stays valid until it expires.
+ add_jti_blocklist(get_jwt()["jti"])
+
+ return create_token_pair(user_id, fresh=False)
def add_jti_blocklist(jti):
- # Add to blockist when remove jti
- new_row = BlocklistModel(jti_blocklist=str(jti))
+ """
+ Add a token id to the blocklist. Idempotent: revoking an already revoked
+ token is not an error.
+ """
+ if BlocklistModel.query.filter_by(jti_blocklist=str(jti)).first():
+ return
try:
- db.session.add(new_row)
+ db.session.add(BlocklistModel(jti_blocklist=str(jti)))
db.session.commit()
- except Exception as ex:
+ except Exception:
db.session.rollback()
- logger.error(f"Can not add jti! Error: {ex}")
- abort(400, message=f"Can not add jti! Error: {ex}")
+ logger.exception("Could not add token %s to the blocklist", jti)
+ abort(500, message="Could not revoke token.")
diff --git a/app/utils/auth.py b/app/utils/auth.py
index 26d6c09..323b65f 100644
--- a/app/utils/auth.py
+++ b/app/utils/auth.py
@@ -1,19 +1,29 @@
from flask import jsonify
+from app.db import db
from app.extention import jwt
from app.models import BlocklistModel, UserModel
@jwt.token_verification_loader
def custom_token_verification_callback(jwt_header, jwt_data):
- # Query in database
- user = UserModel.query.filter_by(id=jwt_data["sub"]).first()
+ # A token is only valid while its user exists and is not blocked. This is
+ # checked on every request, so blocking a user takes effect immediately.
+ user = db.session.get(UserModel, int(jwt_data["sub"]))
+ return user is not None and not user.block
- # If user was blocked, user will not access.
- if user.block is True:
- return False
- return True
+@jwt.token_verification_failed_loader
+def token_verification_failed_callback(jwt_header, jwt_payload):
+ return (
+ jsonify(
+ {
+ "description": "The user is blocked or no longer exists",
+ "error": "user_blocked",
+ }
+ ),
+ 401,
+ )
@jwt.token_in_blocklist_loader
@@ -41,14 +51,6 @@ def token_not_fresh_callback(jwt_header, jwt_payload):
)
-@jwt.additional_claims_loader
-def add_claims_to_jwt(identity):
- # Look in admin in database
- if identity == 1:
- return {"is_admin": True}
- return {"is_admin": False}
-
-
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
return jsonify({"message": "Token has expired.", "error": "token_expired"}), 401
diff --git a/app/utils/authorization.py b/app/utils/authorization.py
new file mode 100644
index 0000000..896ea66
--- /dev/null
+++ b/app/utils/authorization.py
@@ -0,0 +1,78 @@
+"""
+Authorization helpers.
+
+The permission model is role based: a user has roles, a role has permissions.
+Data access is gated by the "read" / "write" / "delete" permissions; anything
+that changes *who is allowed to do what* (roles, permissions, role assignments,
+blocking users) additionally requires the ADMIN_PERMISSION.
+
+All checks query the database, so a change of roles takes effect on the very
+next request - nothing authorization related is cached inside the JWT.
+"""
+import logging
+
+from flask_jwt_extended import get_jwt_identity
+from flask_smorest import abort
+
+from app.db import db
+from app.models.permission_model import PermissionModel
+from app.models.role_model import RoleModel
+from app.models.user_model import UserModel
+
+ADMIN_PERMISSION = "admin"
+
+logger = logging.getLogger(__name__)
+
+
+def user_has_permission(user_id, permission_name):
+ """
+ Return True if the user holds the permission through any of their roles.
+ Single query, no N+1 over roles / permissions.
+ """
+ return (
+ db.session.query(UserModel.id)
+ .join(UserModel.roles)
+ .join(RoleModel.permissions)
+ .filter(UserModel.id == user_id, PermissionModel.name == permission_name)
+ .first()
+ is not None
+ )
+
+
+def current_user_id():
+ # The JWT "sub" claim must be a string (RFC 7519 / PyJWT >= 2.10);
+ # the application works with integer primary keys.
+ return int(get_jwt_identity())
+
+
+def current_user_is_admin():
+ return user_has_permission(current_user_id(), ADMIN_PERMISSION)
+
+
+def ensure_caller_keeps_admin():
+ """
+ Guard against locking yourself out.
+
+ Call this *before* committing any change to roles / permissions / role
+ assignments. It flushes the pending changes and verifies the caller still
+ holds the admin permission; if not, the transaction is rolled back and the
+ request is rejected.
+ """
+ db.session.flush()
+ if not user_has_permission(current_user_id(), ADMIN_PERMISSION):
+ db.session.rollback()
+ logger.warning(
+ "User %s attempted a change that would remove their own admin access",
+ current_user_id(),
+ )
+ abort(400, message="This change would remove your own admin access.")
+
+
+def get_or_404(model, object_id, label):
+ """
+ Fetch a row by primary key or abort with a JSON 404.
+ """
+ obj = db.session.get(model, object_id)
+ if obj is None:
+ abort(404, message=f"{label} {object_id} does not exist.")
+ return obj
diff --git a/app/utils/decorators.py b/app/utils/decorators.py
index 29f791e..0a700dc 100644
--- a/app/utils/decorators.py
+++ b/app/utils/decorators.py
@@ -2,27 +2,36 @@
import time
from functools import wraps
-from flask_jwt_extended import get_jwt
from flask_smorest import abort
-from app.models import UserModel
+from app.utils.authorization import current_user_id, user_has_permission
# Create logger for this module
logger = logging.getLogger(__name__)
def permission_required(permission_name):
+ """
+ Reject the request with 403 unless the authenticated user holds the
+ permission through one of their roles. Must be applied *after*
+ jwt_required() (i.e. listed below it), since it relies on the verified JWT.
+ """
+
def decorator(func):
+ # wraps() copies the function metadata (including the _apidoc attribute
+ # that flask-smorest attaches), so Swagger docs survive this decorator.
+ @wraps(func)
def wrapper(*arg, **kwargs):
- jwt_data = get_jwt()
- user_id = jwt_data["sub"]
- user = UserModel.query.filter_by(id=user_id).first()
- for role in user.roles:
- for permission in role.permissions:
- if permission.name == permission_name:
- return func(*arg, **kwargs)
- logger.error("User does not have permission to access this API!")
- abort(403, message="User does not have permission to access this API!")
+ user_id = current_user_id()
+ if not user_has_permission(user_id, permission_name):
+ logger.warning(
+ "User %s lacks permission '%s' for %s",
+ user_id,
+ permission_name,
+ func.__qualname__,
+ )
+ abort(403, message="User does not have permission to access this API!")
+ return func(*arg, **kwargs)
return wrapper
@@ -30,6 +39,7 @@ def wrapper(*arg, **kwargs):
def time_profiling(func):
+ @wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
diff --git a/config.py b/config.py
index 0a44e99..bb801d0 100644
--- a/config.py
+++ b/config.py
@@ -24,14 +24,37 @@ class DefaultConfig:
JWT_REFRESH_TOKEN_EXPIRES = datetime.timedelta(days=30)
# Algorithm used to generate the token
JWT_ALGORITHM = "HS256"
- # Algorithm used to decode the token
- JWT_DECODE_ALGORITHMS = "HS256"
+ # Algorithms accepted when decoding a token (a list - never include "none")
+ JWT_DECODE_ALGORITHMS = ["HS256"]
# Header that should contain the JWT in a request
JWT_HEADER_NAME = "Authorization"
# Word that goes before the token in the Authorization header in this case empty
JWT_HEADER_TYPE = "Bearer"
- # Where to look for a JWT when processing a request.
- JWT_TOKEN_LOCATION = "headers"
+ # Where to look for a JWT when processing a request (a list)
+ JWT_TOKEN_LOCATION = ["headers"]
+
+ # CORS: comma separated list of allowed origins, e.g.
+ # "https://app.example.com,https://admin.example.com".
+ # Empty (default) = no cross-origin access at all. "*" = any origin.
+ CORS_ORIGINS = [
+ origin.strip()
+ for origin in os.environ.get("CORS_ORIGINS", "").split(",")
+ if origin.strip()
+ ]
+
+ # Rate limiting (Flask-Limiter). The default "memory://" storage is per
+ # process - with several Gunicorn workers point RATELIMIT_STORAGE_URI at a
+ # shared store (e.g. "redis://redis:6379") for accurate limits.
+ RATELIMIT_ENABLED = True
+ RATELIMIT_STORAGE_URI = os.environ.get("RATELIMIT_STORAGE_URI", "memory://")
+ RATELIMIT_HEADERS_ENABLED = True
+ RATELIMIT_LOGIN = os.environ.get("RATELIMIT_LOGIN", "5 per minute")
+ RATELIMIT_REGISTER = os.environ.get("RATELIMIT_REGISTER", "3 per minute")
+
+ # Number of reverse proxies in front of the app whose X-Forwarded-For /
+ # X-Forwarded-Proto headers are trusted (0 = none). Needed for correct
+ # client IPs in logs and rate limiting when running behind Nginx.
+ TRUSTED_PROXY_COUNT = int(os.environ.get("TRUSTED_PROXY_COUNT", "0"))
# Config API documents
API_TITLE = "Flask REST API Template"
@@ -64,6 +87,9 @@ class DevelopConfig(DefaultConfig):
# Activate debug mode
DEBUG = True
+ # Convenience for local front-end development: any origin unless overridden
+ CORS_ORIGINS = DefaultConfig.CORS_ORIGINS or ["*"]
+
# Database configuration
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
@@ -81,6 +107,9 @@ class TestingConfig(DefaultConfig):
# False to disable CSRF protection during tests
WTF_CSRF_ENABLED = False
+ # Tests log in many times in quick succession
+ RATELIMIT_ENABLED = False
+
# Logging
LOG_FILE_API = f"{basedir}/logs/api_tests.log"
@@ -95,6 +124,9 @@ class LocalConfig(DefaultConfig):
# Activate debug mode
DEBUG = False
+ # docker-compose puts one Nginx in front of the API
+ TRUSTED_PROXY_COUNT = int(os.environ.get("TRUSTED_PROXY_COUNT", "1"))
+
# Database configuration
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
@@ -106,5 +138,8 @@ class ProductionConfig(DefaultConfig):
# Activate debug mode
DEBUG = False
+ # docker-compose puts one Nginx in front of the API
+ TRUSTED_PROXY_COUNT = int(os.environ.get("TRUSTED_PROXY_COUNT", "1"))
+
# Database configuration
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
diff --git a/manage.py b/manage.py
index 556e144..02d4197 100644
--- a/manage.py
+++ b/manage.py
@@ -1,17 +1,12 @@
+import sys
import unittest
import click
-import coverage
from passlib.hash import pbkdf2_sha256
from app.db import db
-from app.models import (
- PermissionModel,
- RoleModel,
- RolePermissionModel,
- UserModel,
- UserRoleModel,
-)
+from app.models import PermissionModel, RoleModel, UserModel
+from app.utils.authorization import ADMIN_PERMISSION
@click.option(
@@ -21,6 +16,8 @@ def cov(pattern):
"""
Run the unit tests with coverage
"""
+ import coverage # dev dependency (requirements-dev.txt), not needed at runtime
+
cov = coverage.coverage(branch=True, include="app/*")
cov.start()
tests = unittest.TestLoader().discover("tests", pattern=pattern)
@@ -31,8 +28,9 @@ def cov(pattern):
print("Coverage Summary:")
cov.report()
cov.erase()
- return 0
- return 1
+ sys.exit(0)
+ # A non-zero exit code is what makes CI fail; Click ignores return values.
+ sys.exit(1)
@click.option(
@@ -42,6 +40,8 @@ def cov_html(pattern):
"""
Run the unit tests with coverage and generate an HTML report.
"""
+ import coverage # dev dependency (requirements-dev.txt), not needed at runtime
+
cov = coverage.coverage(branch=True, include="app/*")
cov.start()
@@ -56,9 +56,9 @@ def cov_html(pattern):
cov.report()
cov.html_report(directory="report/htmlcov")
cov.erase()
- return 0
+ sys.exit(0)
- return 1
+ sys.exit(1)
@click.option("--pattern", default="tests_*.py", help="Test pattern", required=False)
@@ -68,9 +68,7 @@ def tests(pattern):
"""
tests = unittest.TestLoader().discover("tests", pattern=pattern)
result = unittest.TextTestRunner(verbosity=2).run(tests)
- if result.wasSuccessful():
- return 0
- return 1
+ sys.exit(0 if result.wasSuccessful() else 1)
def create_db():
@@ -98,53 +96,72 @@ def drop_db():
db.session.commit()
+# Seed data. Passwords are for local development only - see README "Default Seed Accounts".
+SEED_PASSWORD = "123456"
+
+SEED_PERMISSIONS = {
+ "read": "Read data",
+ "write": "Write data",
+ "delete": "Delete data",
+ ADMIN_PERMISSION: "Manage users, roles and permissions",
+}
+
+# role name -> (description, permissions)
+SEED_ROLES = {
+ "Admin": ("Full Permission", ["read", "write", "delete", ADMIN_PERMISSION]),
+ "User": ("Can read, write data", ["read", "write"]),
+ "Guest": ("Just read data", ["read"]),
+}
+
+# username -> role
+SEED_USERS = {"admin": "Admin", "user": "User", "guest": "Guest"}
+
+
def init_db_user():
- # Insert Permission
- read_perrmission = PermissionModel(name="read", description="Read data")
- write_perrmission = PermissionModel(name="write", description="Write data")
- delete_perrmission = PermissionModel(name="delete", description="Delete data")
- db.session.add_all([read_perrmission, write_perrmission, delete_perrmission])
- db.session.commit()
+ """
+ Seed permissions, roles and users. Relationships are built from objects,
+ not hard-coded ids, so the result does not depend on sequence values.
+ """
+ permissions = {
+ name: PermissionModel(name=name, description=description)
+ for name, description in SEED_PERMISSIONS.items()
+ }
+ db.session.add_all(permissions.values())
+
+ roles = {}
+ for name, (description, permission_names) in SEED_ROLES.items():
+ role = RoleModel(name=name, description=description)
+ role.permissions = [permissions[p] for p in permission_names]
+ roles[name] = role
+ db.session.add_all(roles.values())
+
+ password = pbkdf2_sha256.hash(SEED_PASSWORD)
+ for username, role_name in SEED_USERS.items():
+ user = UserModel(username=username, password=password)
+ user.roles.append(roles[role_name])
+ db.session.add(user)
- # Insert Role
- admin_role = RoleModel(name="Admin", description="Full Permission")
- user_role = RoleModel(name="User", description="Can read, write data")
- guest_role = RoleModel(name="Guest", description="Just read data")
- db.session.add_all([admin_role, user_role, guest_role])
db.session.commit()
- # Insert Role_Permission
- role_permission_admin1 = RolePermissionModel(role_id=1, permission_id=1)
- role_permission_admin2 = RolePermissionModel(role_id=1, permission_id=2)
- role_permission_admin3 = RolePermissionModel(role_id=1, permission_id=3)
- role_permission_user1 = RolePermissionModel(role_id=2, permission_id=1)
- role_permission_user2 = RolePermissionModel(role_id=2, permission_id=2)
- role_permission_guest = RolePermissionModel(role_id=3, permission_id=1)
- db.session.add_all(
- [
- role_permission_admin1,
- role_permission_admin2,
- role_permission_admin3,
- role_permission_user1,
- role_permission_user2,
- role_permission_guest,
- ]
- )
- db.session.commit()
- # Insert User
- password = pbkdf2_sha256.hash("123456")
- admin_user = UserModel(username="admin", password=password)
- normal_user = UserModel(username="user", password=password)
- guest_user = UserModel(username="guest", password=password)
- db.session.add_all([admin_user, normal_user, guest_user])
- db.session.commit()
+def ensure_admin_permission():
+ """
+ Upgrade path for databases seeded before the "admin" permission existed:
+ create it if missing and grant it to the "Admin" role.
+ """
+ permission = PermissionModel.query.filter_by(name=ADMIN_PERMISSION).first()
+ if permission is None:
+ permission = PermissionModel(
+ name=ADMIN_PERMISSION, description=SEED_PERMISSIONS[ADMIN_PERMISSION]
+ )
+ db.session.add(permission)
+ print(f"Created missing '{ADMIN_PERMISSION}' permission.")
+
+ admin_role = RoleModel.query.filter_by(name="Admin").first()
+ if admin_role is not None and permission not in admin_role.permissions:
+ admin_role.permissions.append(permission)
+ print(f"Granted '{ADMIN_PERMISSION}' permission to the Admin role.")
- # Insert UserRole
- user_role1 = UserRoleModel(user_id=1, role_id=1)
- user_role2 = UserRoleModel(user_id=2, role_id=2)
- user_role3 = UserRoleModel(user_id=3, role_id=3)
- db.session.add_all([user_role1, user_role2, user_role3])
db.session.commit()
@@ -159,6 +176,7 @@ def create_user_admin(username="admin"):
init_db_user()
else:
print("user-admin is created!")
+ ensure_admin_permission()
def init_app(app):
diff --git a/requirements-dev.txt b/requirements-dev.txt
new file mode 100644
index 0000000..77e3759
--- /dev/null
+++ b/requirements-dev.txt
@@ -0,0 +1,8 @@
+# Development / CI tooling. Installs the runtime requirements too.
+-r requirements.txt
+black==23.9.1
+coverage==7.16.2
+flake8==6.1.0
+isort==5.12.0
+pip-audit==2.10.1
+pre-commit==4.6.2
diff --git a/requirements.txt b/requirements.txt
index c41a256..e07ff62 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,78 +1,37 @@
-alembic==1.10.2
-apispec==6.3.0
-asttokens==2.2.1
-backcall==0.2.0
-black==23.9.1
-blinker==1.5
-certifi==2023.5.7
-click==8.1.3
-colorama==0.4.6
-comm==0.1.2
-coverage==7.2.7
-debugpy==1.6.4
-decorator==5.1.1
-distlib==0.3.6
-entrypoints==0.4
-executing==1.2.0
-filelock==3.12.2
-flake8==6.1.0
-Flask==2.2.5
-Flask-Cors==3.0.10
-Flask-JWT-Extended==4.4.4
-Flask-Migrate==4.0.4
-Flask-Script==2.0.5
-flask-smorest==0.40.0
-Flask-SQLAlchemy==3.0.3
-greenlet==2.0.2
-gunicorn==20.1.0
-importlib-metadata==6.7.0
-ipykernel==6.19.2
-ipython==8.10.0
-isort==5.12.0
-itsdangerous==2.1.2
-jedi==0.18.2
-Jinja2==3.1.2
-jupyter_client==7.4.8
-jupyter_core==5.1.0
-Mako==1.2.4
-MarkupSafe==2.1.2
-marshmallow==3.19.0
-matplotlib-inline==0.1.6
-mccabe==0.7.0
-mypy-extensions==1.0.0
-nest-asyncio==1.5.6
-packaging==22.0
-parso==0.8.3
+# Runtime dependencies (what the Docker image installs). Pinned; regenerate with:
+# pip install && pip freeze
+# Development tooling lives in requirements-dev.txt.
+alembic==1.20.1
+apispec==6.10.0
+backports-datetime-fromisoformat==2.0.3
+blinker==1.9.0
+click==8.5.0
+Deprecated==1.3.1
+flask-cors==6.0.5
+Flask-JWT-Extended==4.7.4
+Flask-Limiter==4.1.1
+Flask-Migrate==4.1.0
+flask-smorest==0.47.0
+Flask-SQLAlchemy==3.1.1
+Flask==3.1.3
+greenlet==3.5.6
+gunicorn==26.2.0
+itsdangerous==2.2.0
+Jinja2==3.1.6
+limits==5.8.0
+Mako==1.4.3
+MarkupSafe==3.0.4
+marshmallow==4.3.1
+ordered-set==4.1.0
+packaging==26.3
passlib==1.7.4
-pathspec==0.12.1
-pexpect==4.8.0
-pickleshare==0.7.5
-pipenv==2023.7.3
-platformdirs==3.8.0
-prompt-toolkit==3.0.36
-psutil==5.9.4
-psycopg2-binary==2.9.6
-ptyprocess==0.7.0
-pure-eval==0.2.2
-pycodestyle==2.11.1
-pyflakes==3.1.0
-Pygments==2.13.0
-PyJWT==2.6.0
-python-dateutil==2.8.2
-python-dotenv==1.0.0
-pytz==2023.3
-pyzmq==24.0.1
-six==1.16.0
-SQLAlchemy==2.0.7
-stack-data==0.6.2
-tomli==2.0.1
-tornado==6.3.2
-traitlets==5.7.1
-typing_extensions==4.5.0
-virtualenv==20.23.1
-virtualenv-clone==0.5.7
-wcwidth==0.2.5
-webargs==8.2.0
-Werkzeug==2.2.3
-wincertstore==0.2
-zipp==3.15.0
+psycopg2-binary==2.9.13
+PyJWT==2.15.1
+python-dotenv==1.2.4
+pytz==2026.5
+SQLAlchemy==2.0.55
+tomli==2.5.0
+typing_extensions==4.16.0
+webargs==8.7.1
+Werkzeug==3.1.9
+wrapt==2.5.1
diff --git a/tests/integration/tests_auth_integration.py b/tests/integration/tests_auth_integration.py
new file mode 100644
index 0000000..90137ca
--- /dev/null
+++ b/tests/integration/tests_auth_integration.py
@@ -0,0 +1,160 @@
+import os
+import unittest
+
+import manage
+from app import create_app, db
+
+
+class AuthIntegrationTests(unittest.TestCase):
+ """
+ HTTP-level tests for authentication / authorization behaviour.
+
+ Each test gets a fresh schema seeded with the default permissions, roles
+ and users from manage.init_db_user() (admin / user / guest, password 123456).
+ """
+
+ def setUp(self):
+ self.app = create_app(
+ settings_module=os.environ.get("APP_TEST_SETTINGS_MODULE")
+ )
+ self.client = self.app.test_client()
+ with self.app.app_context():
+ db.create_all()
+ manage.init_db_user()
+
+ def tearDown(self):
+ with self.app.app_context():
+ db.session.remove()
+ db.drop_all()
+
+ # Helpers
+
+ def login(self, username="admin", password="123456"):
+ response = self.client.post(
+ "/login", json={"username": username, "password": password}
+ )
+ self.assertEqual(200, response.status_code, response.get_json())
+ return response.get_json()
+
+ @staticmethod
+ def bearer(token):
+ return {"Authorization": f"Bearer {token}"}
+
+ # Tests
+
+ def test_login_returns_token_pair(self):
+ tokens = self.login()
+ self.assertIn("access_token", tokens)
+ self.assertIn("refresh_token", tokens)
+
+ def test_login_with_wrong_password_is_rejected(self):
+ response = self.client.post(
+ "/login", json={"username": "admin", "password": "wrong"}
+ )
+ self.assertEqual(401, response.status_code)
+
+ def test_password_hash_is_never_returned(self):
+ tokens = self.login()
+ headers = self.bearer(tokens["access_token"])
+
+ response = self.client.get("/user", headers=headers)
+ self.assertEqual(200, response.status_code)
+ for user in response.get_json():
+ self.assertNotIn("password", user)
+
+ response = self.client.get("/user/1", headers=headers)
+ self.assertEqual(200, response.status_code)
+ self.assertNotIn("password", response.get_json())
+
+ def test_logout_revokes_access_and_refresh_token(self):
+ tokens = self.login()
+
+ response = self.client.post(
+ "/logout", headers=self.bearer(tokens["access_token"])
+ )
+ self.assertEqual(200, response.status_code)
+
+ # The access token is revoked...
+ response = self.client.get("/user", headers=self.bearer(tokens["access_token"]))
+ self.assertEqual(401, response.status_code)
+ self.assertEqual("token_revoked", response.get_json()["error"])
+
+ # ...and so is the refresh token that was issued together with it.
+ response = self.client.post(
+ "/refresh", headers=self.bearer(tokens["refresh_token"])
+ )
+ self.assertEqual(401, response.status_code)
+ self.assertEqual("token_revoked", response.get_json()["error"])
+
+ def test_logout_twice_is_not_an_error(self):
+ tokens = self.login()
+ headers = self.bearer(tokens["access_token"])
+
+ self.assertEqual(200, self.client.post("/logout", headers=headers).status_code)
+ # Second call fails only because the token is already revoked, not with a 4xx/5xx from the blocklist insert.
+ response = self.client.post("/logout", headers=headers)
+ self.assertEqual(401, response.status_code)
+ self.assertEqual("token_revoked", response.get_json()["error"])
+
+ def test_refresh_token_is_single_use(self):
+ tokens = self.login()
+ refresh_headers = self.bearer(tokens["refresh_token"])
+
+ response = self.client.post("/refresh", headers=refresh_headers)
+ self.assertEqual(200, response.status_code)
+ new_tokens = response.get_json()
+ self.assertIn("access_token", new_tokens)
+ self.assertIn("refresh_token", new_tokens)
+
+ # Re-using the old refresh token must fail.
+ response = self.client.post("/refresh", headers=refresh_headers)
+ self.assertEqual(401, response.status_code)
+ self.assertEqual("token_revoked", response.get_json()["error"])
+
+ # The new pair works, and logging out with it revokes the new refresh token too.
+ self.assertEqual(
+ 200,
+ self.client.post(
+ "/logout", headers=self.bearer(new_tokens["access_token"])
+ ).status_code,
+ )
+ response = self.client.post(
+ "/refresh", headers=self.bearer(new_tokens["refresh_token"])
+ )
+ self.assertEqual(401, response.status_code)
+
+ def test_error_responses_do_not_leak_internal_details(self):
+ tokens = self.login()
+ headers = self.bearer(tokens["access_token"])
+
+ # "Admin" already exists -> unique constraint violation in the database.
+ response = self.client.post(
+ "/role",
+ headers=headers,
+ json={"name": "Admin", "description": "dup", "permissions": [1]},
+ )
+ self.assertEqual(400, response.status_code)
+ message = response.get_json()["message"].lower()
+ for needle in (
+ "sqlite",
+ "psycopg",
+ "sql",
+ "integrityerror",
+ "constraint",
+ "traceback",
+ ):
+ self.assertNotIn(needle, message)
+
+ def test_openapi_document_keeps_schemas_on_protected_endpoints(self):
+ response = self.client.get("/openapi.json")
+ self.assertEqual(200, response.status_code)
+ paths = response.get_json()["paths"]
+
+ # @blp.response(...) behind @permission_required must still be documented
+ self.assertIn("content", paths["/user"]["get"]["responses"]["200"])
+ # @blp.arguments(...) behind @permission_required must still be documented
+ self.assertIn("requestBody", paths["/role"]["post"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/integration/tests_authorization_integration.py b/tests/integration/tests_authorization_integration.py
new file mode 100644
index 0000000..b8bde58
--- /dev/null
+++ b/tests/integration/tests_authorization_integration.py
@@ -0,0 +1,410 @@
+import os
+import unittest
+
+import manage
+from app import create_app, db
+from app.models import PermissionModel, RoleModel, UserModel
+
+
+class AuthorizationIntegrationTests(unittest.TestCase):
+ """
+ HTTP-level tests for the role / permission model.
+
+ Seeded accounts (manage.init_db_user):
+ admin -> Admin role: read, write, delete, admin
+ user -> User role: read, write
+ guest -> Guest role: read
+ """
+
+ def setUp(self):
+ self.app = create_app(
+ settings_module=os.environ.get("APP_TEST_SETTINGS_MODULE")
+ )
+ self.client = self.app.test_client()
+ with self.app.app_context():
+ db.create_all()
+ manage.init_db_user()
+ self.ids = {
+ "users": {u.username: u.id for u in UserModel.query.all()},
+ "roles": {r.name: r.id for r in RoleModel.query.all()},
+ "permissions": {p.name: p.id for p in PermissionModel.query.all()},
+ }
+
+ def tearDown(self):
+ with self.app.app_context():
+ db.session.remove()
+ db.drop_all()
+
+ # Helpers
+
+ def headers_for(self, username, password="123456"):
+ response = self.client.post(
+ "/login", json={"username": username, "password": password}
+ )
+ self.assertEqual(200, response.status_code, response.get_json())
+ return {"Authorization": f"Bearer {response.get_json()['access_token']}"}
+
+ def user_id(self, username):
+ return self.ids["users"][username]
+
+ def role_id(self, name):
+ return self.ids["roles"][name]
+
+ def permission_id(self, name):
+ return self.ids["permissions"][name]
+
+ def roles_of(self, username, headers):
+ response = self.client.get(f"/user/{self.user_id(username)}", headers=headers)
+ self.assertEqual(200, response.status_code)
+ return sorted(r["name"] for r in response.get_json()["roles"])
+
+ # --- Privilege escalation (audit findings #1 / #2) ---
+
+ def test_write_user_cannot_grant_itself_admin_role(self):
+ headers = self.headers_for("user")
+
+ response = self.client.put(
+ f"/user/{self.user_id('user')}",
+ headers=headers,
+ json={"roles": [self.role_id("Admin")]},
+ )
+ self.assertEqual(403, response.status_code)
+ self.assertEqual(["User"], self.roles_of("user", headers))
+
+ # ...nor via the role-link endpoint
+ response = self.client.post(
+ f"/user/{self.user_id('user')}/role/{self.role_id('Admin')}",
+ headers=headers,
+ )
+ self.assertEqual(403, response.status_code)
+ self.assertEqual(["User"], self.roles_of("user", headers))
+
+ def test_write_user_cannot_escalate_by_editing_roles_or_permissions(self):
+ headers = self.headers_for("user")
+ all_permissions = list(self.ids["permissions"].values())
+
+ # Add every permission to the User role
+ response = self.client.put(
+ f"/role/{self.role_id('User')}",
+ headers=headers,
+ json={"name": "User", "description": "x", "permissions": all_permissions},
+ )
+ self.assertEqual(403, response.status_code)
+
+ # Create a new all-powerful role
+ response = self.client.post(
+ "/role",
+ headers=headers,
+ json={"name": "Super", "description": "x", "permissions": all_permissions},
+ )
+ self.assertEqual(403, response.status_code)
+
+ # Attach the User role to the admin permission
+ response = self.client.put(
+ "/permission-role-update",
+ headers=headers,
+ json={
+ "data_update": {
+ str(self.permission_id("admin")): [self.role_id("User")]
+ }
+ },
+ )
+ self.assertEqual(403, response.status_code)
+
+ # Delete a role
+ response = self.client.delete(f"/role/{self.role_id('Guest')}", headers=headers)
+ self.assertEqual(403, response.status_code)
+
+ # Still cannot do something that needs "delete"
+ response = self.client.delete(
+ f"/role/{self.role_id('Guest')}", headers=self.headers_for("user")
+ )
+ self.assertEqual(403, response.status_code)
+
+ def test_non_admin_cannot_update_other_users(self):
+ headers = self.headers_for("user")
+
+ response = self.client.put(
+ f"/user/{self.user_id('admin')}",
+ headers=headers,
+ json={"password": "pwned"},
+ )
+ self.assertEqual(403, response.status_code)
+
+ # Admin's password is unchanged
+ response = self.client.post(
+ "/login", json={"username": "admin", "password": "123456"}
+ )
+ self.assertEqual(200, response.status_code)
+
+ def test_guest_cannot_do_anything_but_read(self):
+ headers = self.headers_for("guest")
+
+ self.assertEqual(200, self.client.get("/user", headers=headers).status_code)
+ self.assertEqual(200, self.client.get("/role", headers=headers).status_code)
+
+ response = self.client.post(
+ "/role",
+ headers=headers,
+ json={"name": "x", "description": "x", "permissions": []},
+ )
+ self.assertEqual(403, response.status_code)
+ response = self.client.put(
+ f"/block-user/{self.user_id('user')}",
+ headers=headers,
+ json={"block": True},
+ )
+ self.assertEqual(403, response.status_code)
+
+ # --- What users MAY do with their own account ---
+
+ def test_any_user_can_change_own_password(self):
+ headers = self.headers_for("guest")
+
+ response = self.client.put(
+ f"/user/{self.user_id('guest')}",
+ headers=headers,
+ json={"password": "new-password"},
+ )
+ self.assertEqual(200, response.status_code)
+
+ self.assertEqual(
+ 200,
+ self.client.post(
+ "/login", json={"username": "guest", "password": "new-password"}
+ ).status_code,
+ )
+ self.assertEqual(
+ 401,
+ self.client.post(
+ "/login", json={"username": "guest", "password": "123456"}
+ ).status_code,
+ )
+ # Roles untouched
+ self.assertEqual(["Guest"], self.roles_of("guest", headers))
+
+ # --- What admins CAN do ---
+
+ def test_admin_can_manage_roles_of_other_users(self):
+ headers = self.headers_for("admin")
+
+ response = self.client.post(
+ f"/user/{self.user_id('guest')}/role/{self.role_id('User')}",
+ headers=headers,
+ )
+ self.assertEqual(201, response.status_code)
+ self.assertEqual(["Guest", "User"], self.roles_of("guest", headers))
+
+ # Takes effect on the next request, without a new token
+ guest_headers = self.headers_for("guest")
+ response = self.client.post(
+ "/permission", headers=guest_headers, json={"name": "x"}
+ )
+ self.assertEqual(403, response.status_code) # still needs admin
+ response = self.client.put(
+ f"/user/{self.user_id('guest')}",
+ headers=guest_headers,
+ json={"username": "guest2"},
+ )
+ self.assertEqual(200, response.status_code)
+
+ response = self.client.delete(
+ f"/user/{self.user_id('guest')}/role/{self.role_id('User')}",
+ headers=headers,
+ )
+ self.assertEqual(200, response.status_code)
+ self.assertEqual(["Guest"], self.roles_of("guest", headers))
+
+ def test_admin_can_set_roles_via_user_update(self):
+ headers = self.headers_for("admin")
+
+ response = self.client.put(
+ f"/user/{self.user_id('guest')}",
+ headers=headers,
+ json={"roles": [self.role_id("User"), self.role_id("Guest")]},
+ )
+ self.assertEqual(200, response.status_code)
+ self.assertEqual(["Guest", "User"], self.roles_of("guest", headers))
+
+ def test_admin_can_block_and_unblock_user(self):
+ headers = self.headers_for("admin")
+ user_headers = self.headers_for("user")
+
+ response = self.client.put(
+ f"/block-user/{self.user_id('user')}",
+ headers=headers,
+ json={"block": True},
+ )
+ self.assertEqual(200, response.status_code)
+
+ # Existing token is rejected immediately, and login is refused
+ response = self.client.get("/user", headers=user_headers)
+ self.assertEqual(401, response.status_code)
+ self.assertEqual("user_blocked", response.get_json()["error"])
+
+ response = self.client.put(
+ f"/block-user/{self.user_id('user')}",
+ headers=headers,
+ json={"block": False},
+ )
+ self.assertEqual(200, response.status_code)
+ self.assertEqual(
+ 200, self.client.get("/user", headers=user_headers).status_code
+ )
+
+ def test_admin_can_create_role_and_permission(self):
+ headers = self.headers_for("admin")
+
+ response = self.client.post(
+ "/permission",
+ headers=headers,
+ json={"name": "export", "description": "Export data"},
+ )
+ self.assertEqual(200, response.status_code, response.get_json())
+
+ response = self.client.post(
+ "/role",
+ headers=headers,
+ json={
+ "name": "Exporter",
+ "description": "x",
+ "permissions": [self.permission_id("read")],
+ },
+ )
+ self.assertEqual(200, response.status_code, response.get_json())
+
+ # --- Lockout guards ---
+
+ def test_admin_cannot_block_self(self):
+ headers = self.headers_for("admin")
+ response = self.client.put(
+ f"/block-user/{self.user_id('admin')}",
+ headers=headers,
+ json={"block": True},
+ )
+ self.assertEqual(400, response.status_code)
+
+ def test_admin_cannot_remove_own_admin_access(self):
+ headers = self.headers_for("admin")
+ admin_id = self.user_id("admin")
+ admin_role = self.role_id("Admin")
+
+ # via PUT /user roles
+ response = self.client.put(
+ f"/user/{admin_id}", headers=headers, json={"roles": [self.role_id("User")]}
+ )
+ self.assertEqual(400, response.status_code)
+
+ # via DELETE /user//role/
+ response = self.client.delete(
+ f"/user/{admin_id}/role/{admin_role}", headers=headers
+ )
+ self.assertEqual(400, response.status_code)
+
+ # via removing the admin permission from the Admin role
+ response = self.client.put(
+ f"/role/{admin_role}",
+ headers=headers,
+ json={
+ "name": "Admin",
+ "description": "x",
+ "permissions": [self.permission_id("read")],
+ },
+ )
+ self.assertEqual(400, response.status_code)
+
+ # via deleting the Admin role
+ response = self.client.delete(f"/role/{admin_role}", headers=headers)
+ self.assertEqual(400, response.status_code)
+
+ # via detaching the Admin role from the admin permission
+ response = self.client.put(
+ "/permission-role-update",
+ headers=headers,
+ json={"data_update": {str(self.permission_id("admin")): []}},
+ )
+ self.assertEqual(400, response.status_code)
+
+ # via renaming the admin permission
+ response = self.client.put(
+ f"/permission/{self.permission_id('admin')}",
+ headers=headers,
+ json={"name": "administrator"},
+ )
+ self.assertEqual(400, response.status_code)
+
+ # Nothing was persisted: admin still has full access
+ self.assertEqual(["Admin"], self.roles_of("admin", headers))
+ response = self.client.delete(f"/role/{self.role_id('Guest')}", headers=headers)
+ self.assertEqual(200, response.status_code)
+
+ # --- Missing resources return JSON 404s instead of HTML 500s (#7) ---
+
+ def test_unknown_ids_return_404(self):
+ headers = self.headers_for("admin")
+
+ for method, url, body in [
+ ("put", "/user/999", {"username": "x"}),
+ ("put", "/block-user/999", {"block": True}),
+ ("post", f"/user/999/role/{self.role_id('User')}", None),
+ ("post", f"/user/{self.user_id('user')}/role/999", None),
+ ("delete", f"/user/{self.user_id('user')}/role/999", None),
+ ("put", "/role/999", {"name": "x", "description": "x", "permissions": []}),
+ ("delete", "/role/999", None),
+ ("put", "/permission/999", {"name": "x"}),
+ (
+ "put",
+ "/permission-role-update",
+ {"data_update": {"999": [self.role_id("User")]}},
+ ),
+ ("put", f"/user/{self.user_id('user')}", {"roles": [999]}),
+ ]:
+ response = getattr(self.client, method)(url, headers=headers, json=body)
+ self.assertEqual(404, response.status_code, f"{method.upper()} {url}")
+ self.assertIn("message", response.get_json(), f"{method.upper()} {url}")
+
+ def test_removing_role_user_does_not_have_is_a_400(self):
+ headers = self.headers_for("admin")
+ response = self.client.delete(
+ f"/user/{self.user_id('guest')}/role/{self.role_id('Admin')}",
+ headers=headers,
+ )
+ self.assertEqual(400, response.status_code)
+
+ # --- Registration ---
+
+ def test_register_assigns_guest_role_by_name(self):
+ response = self.client.post(
+ "/register", json={"username": "newbie", "password": "secret"}
+ )
+ self.assertEqual(200, response.status_code, response.get_json())
+
+ headers = self.headers_for("newbie", "secret")
+ with self.app.app_context():
+ new_id = UserModel.query.filter_by(username="newbie").first().id
+ response = self.client.get(f"/user/{new_id}", headers=headers)
+ self.assertEqual(["Guest"], [r["name"] for r in response.get_json()["roles"]])
+
+ # --- Upgrade path for existing databases ---
+
+ def test_ensure_admin_permission_upgrades_old_seed_data(self):
+ with self.app.app_context():
+ # Simulate a database seeded before the admin permission existed
+ permission = PermissionModel.query.filter_by(name="admin").first()
+ db.session.delete(permission)
+ db.session.commit()
+ self.assertIsNone(PermissionModel.query.filter_by(name="admin").first())
+
+ manage.create_user_admin() # admin user exists -> upgrade path
+
+ admin_role = RoleModel.query.filter_by(name="Admin").first()
+ self.assertIn("admin", [p.name for p in admin_role.permissions])
+
+ # ...and the admin is functional again
+ headers = self.headers_for("admin")
+ response = self.client.delete(f"/role/{self.role_id('Guest')}", headers=headers)
+ self.assertEqual(200, response.status_code)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/integration/tests_hardening_integration.py b/tests/integration/tests_hardening_integration.py
new file mode 100644
index 0000000..f4e1cc6
--- /dev/null
+++ b/tests/integration/tests_hardening_integration.py
@@ -0,0 +1,99 @@
+import base64
+import json
+import os
+import unittest
+
+import manage
+from app import create_app, db
+from config import TestingConfig
+
+
+class RateLimitedTestingConfig(TestingConfig):
+ """TestingConfig normally disables rate limiting; this test needs it on."""
+
+ RATELIMIT_ENABLED = True
+ RATELIMIT_STORAGE_URI = "memory://"
+ RATELIMIT_LOGIN = "3 per minute"
+ RATELIMIT_REGISTER = "2 per minute"
+
+
+class HardeningIntegrationTests(unittest.TestCase):
+ def setUp(self):
+ self.app = create_app(settings_module=RateLimitedTestingConfig)
+ self.client = self.app.test_client()
+ with self.app.app_context():
+ db.create_all()
+ manage.init_db_user()
+
+ def tearDown(self):
+ with self.app.app_context():
+ db.session.remove()
+ db.drop_all()
+
+ def test_login_is_rate_limited(self):
+ bad = {"username": "admin", "password": "wrong"}
+ codes = [self.client.post("/login", json=bad).status_code for _ in range(4)]
+ self.assertEqual([401, 401, 401, 429], codes)
+
+ response = self.client.post("/login", json=bad)
+ self.assertEqual(429, response.status_code)
+ self.assertIn("Retry-After", response.headers)
+ self.assertEqual("application/json", response.mimetype)
+
+ # Other endpoints are not affected by the login limit
+ self.assertEqual(200, self.client.get("/openapi.json").status_code)
+
+ def test_register_is_rate_limited(self):
+ codes = [
+ self.client.post(
+ "/register", json={"username": f"u{i}", "password": "x"}
+ ).status_code
+ for i in range(3)
+ ]
+ self.assertEqual([200, 200, 429], codes)
+
+ def test_jwt_subject_is_a_string(self):
+ response = self.client.post(
+ "/login", json={"username": "admin", "password": "123456"}
+ )
+ self.assertEqual(200, response.status_code)
+ for token in response.get_json().values():
+ payload = token.split(".")[1]
+ payload = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))
+ claims = json.loads(payload)
+ self.assertIsInstance(claims["sub"], str)
+ self.assertNotIn("is_admin", claims)
+
+ def test_no_cors_headers_unless_configured(self):
+ # TestingConfig inherits the default: CORS_ORIGINS empty
+ self.assertEqual([], self.app.config["CORS_ORIGINS"])
+ response = self.client.get(
+ "/openapi.json", headers={"Origin": "https://evil.example"}
+ )
+ self.assertNotIn("Access-Control-Allow-Origin", response.headers)
+
+
+class ConfiguredCorsTests(unittest.TestCase):
+ def test_only_configured_origin_is_allowed_without_credentials(self):
+ class CorsConfig(TestingConfig):
+ CORS_ORIGINS = ["https://app.example.com"]
+
+ client = create_app(settings_module=CorsConfig).test_client()
+
+ response = client.get(
+ "/openapi.json", headers={"Origin": "https://app.example.com"}
+ )
+ self.assertEqual(
+ "https://app.example.com",
+ response.headers.get("Access-Control-Allow-Origin"),
+ )
+ self.assertNotIn("Access-Control-Allow-Credentials", response.headers)
+
+ response = client.get(
+ "/openapi.json", headers={"Origin": "https://evil.example"}
+ )
+ self.assertNotIn("Access-Control-Allow-Origin", response.headers)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/postman/FlaskTemplate.postman_collection.json b/tests/postman/FlaskTemplate.postman_collection.json
deleted file mode 100644
index 8bff22b..0000000
--- a/tests/postman/FlaskTemplate.postman_collection.json
+++ /dev/null
@@ -1,634 +0,0 @@
-{
- "info": {
- "_postman_id": "03bd1377-f65e-4a5d-b478-2af9d4f41f18",
- "name": "FlaskTemplate",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
- "_exporter_id": "20498029",
- "_collection_link": "https://dark-escape-873868.postman.co/workspace/My-Workspace~fd59678e-5c9a-4e36-8407-3c2ba6dcae38/collection/20498029-03bd1377-f65e-4a5d-b478-2af9d4f41f18?action=share&source=collection_link&creator=20498029"
- },
- "item": [
- {
- "name": "User",
- "item": [
- {
- "name": "GetAllUser",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{HOST}}/user",
- "host": ["{{HOST}}"],
- "path": ["user"]
- }
- },
- "response": []
- },
- {
- "name": "GetUser",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{HOST}}/user/2",
- "host": ["{{HOST}}"],
- "path": ["user", "2"]
- }
- },
- "response": []
- },
- {
- "name": "Update",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "PUT",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"username\": null,\r\n \"password\": \"123456\",\r\n \"roles\": [1,2,3]\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/user/1",
- "host": ["{{HOST}}"],
- "path": ["user", "1"]
- }
- },
- "response": []
- },
- {
- "name": "Block User",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [""],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "PUT",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"block\": true\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/block-user/3",
- "host": ["{{HOST}}"],
- "path": ["block-user", "3"]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Login",
- "item": [
- {
- "name": "Login",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "var jsonData = JSON.parse(responseBody);\r",
- "pm.environment.set(\"TOKEN\", jsonData.access_token);\r",
- "pm.environment.set(\"REFRESHTOKEN\", jsonData.refresh_token);"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"username\": \"admin\",\r\n \"password\": \"123456\"\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/login",
- "host": ["{{HOST}}"],
- "path": ["login"]
- }
- },
- "response": []
- },
- {
- "name": "Logout",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [],
- "url": {
- "raw": "{{HOST}}/logout",
- "host": ["{{HOST}}"],
- "path": ["logout"]
- }
- },
- "response": []
- },
- {
- "name": "RefreshToken",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "var jsonData = JSON.parse(responseBody);\r",
- "pm.environment.set(\"TOKEN\", jsonData.access_token);\r",
- "pm.environment.set(\"REFRESHTOKEN\", jsonData.refresh_token);"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{REFRESHTOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [],
- "url": {
- "raw": "{{HOST}}/refresh",
- "host": ["{{HOST}}"],
- "path": ["refresh"]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Register",
- "item": [
- {
- "name": "Register",
- "request": {
- "method": "POST",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"email\": \"phuoc@gmail.com\",\r\n \"password\": \"Phuoc12345@\"\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/auth/users",
- "host": ["{{HOST}}"],
- "path": ["auth", "users"]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Role",
- "item": [
- {
- "name": "Get all",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{HOST}}/role",
- "host": ["{{HOST}}"],
- "path": ["role"]
- }
- },
- "response": []
- },
- {
- "name": "Get by id",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{HOST}}/role/1",
- "host": ["{{HOST}}"],
- "path": ["role", "1"]
- }
- },
- "response": []
- },
- {
- "name": "Add new",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"name\": \"nhรขn viรชn2\",\r\n \"description\": \"Nhรขn viรชn nรจ\",\r\n \"permissions\": [1,3]\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/role",
- "host": ["{{HOST}}"],
- "path": ["role"]
- }
- },
- "response": []
- },
- {
- "name": "Update",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "PUT",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"name\": \"Super admin\",\r\n \"description\": \"Full permissions\",\r\n \"permissions\": [1]\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/role/1",
- "host": ["{{HOST}}"],
- "path": ["role", "1"]
- }
- },
- "response": []
- },
- {
- "name": "Delete",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "DELETE",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"display_name\": \"\",\r\n \"email\": \"\"\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/role/13",
- "host": ["{{HOST}}"],
- "path": ["role", "13"]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Permission",
- "item": [
- {
- "name": "Get all",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{HOST}}/permission",
- "host": ["{{HOST}}"],
- "path": ["permission"]
- }
- },
- "response": []
- },
- {
- "name": "Get by id",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{HOST}}/permission/1",
- "host": ["{{HOST}}"],
- "path": ["permission", "1"]
- }
- },
- "response": []
- },
- {
- "name": "Add new",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"name\": \"read\",\r\n \"description\": \"Read data\"\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/permission",
- "host": ["{{HOST}}"],
- "path": ["permission"]
- }
- },
- "response": []
- },
- {
- "name": "Update",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "PUT",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"name\": \"read\",\r\n \"description\": \"Read data\"\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/permission/4",
- "host": ["{{HOST}}"],
- "path": ["permission", "4"]
- }
- },
- "response": []
- },
- {
- "name": "Update Roles",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "PUT",
- "header": [],
- "body": {
- "mode": "raw",
- "raw": "{\r\n \"data_update\" : {\"1\" : [1,2,3], \"2\": [2]}\r\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{HOST}}/permission-role-update",
- "host": ["{{HOST}}"],
- "path": ["permission-role-update"]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "User Role",
- "item": [
- {
- "name": "Link Roles to User",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [],
- "url": {
- "raw": "{{HOST}}/user/1/role/2",
- "host": ["{{HOST}}"],
- "path": ["user", "1", "role", "2"]
- }
- },
- "response": []
- },
- {
- "name": "Delete Roles to User",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "DELETE",
- "header": [],
- "url": {
- "raw": "{{HOST}}/user/1/role/2",
- "host": ["{{HOST}}"],
- "path": ["user", "1", "role", "2"]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Role Permission",
- "item": [
- {
- "name": "Get All",
- "request": {
- "auth": {
- "type": "bearer",
- "bearer": [
- {
- "key": "token",
- "value": "{{TOKEN}}",
- "type": "string"
- }
- ]
- },
- "method": "GET",
- "header": [],
- "url": {
- "raw": "{{HOST}}/role-permission",
- "host": ["{{HOST}}"],
- "path": ["role-permission"]
- }
- },
- "response": []
- }
- ]
- }
- ]
-}