Skip to content

About

flask-sqlalchemy-marshmallow-login-example

Resources

Security policy

Stars

10 stars

Watchers

1 watching

Forks

Latest commit

ย 

History

124 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Flask Login Example

A small, beginner-friendly example of token-based authentication with Flask. It uses Flask blueprints, a clean app factory, request rate limiting, and role-based access โ€” a nice next step after a "hello world" Flask app.

You register users, log them in, receive an access token + refresh token, and use those tokens to call protected endpoints.


Features

  • ๐Ÿ” Register / Login / Logout with JSON requests
  • ๐Ÿช™ Access + refresh tokens (signed and time-limited)
  • ๐Ÿ‘ฎ Role-based access โ€” user, admin, super_admin
  • ๐Ÿ”‘ Passwords hashed with PBKDF2-SHA256 (never stored in plaintext)
  • ๐Ÿšฆ Rate limiting on login via Flask-Limiter
  • ๐Ÿงฑ Organised with a blueprint + app factory layout
  • ๐Ÿงช A small test suite (nose2) you can run in one command

Tech stack

Purpose Library
Web framework Flask (blueprints)
Database / ORM Flask-SQLAlchemy + SQLite
Password hashing passlib (pbkdf2-sha256)
Token signing itsdangerous
Rate limiting Flask-Limiter
Tests nose2

Project structure

flask-login-example/
โ”œโ”€โ”€ run.py                      # App entry point
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ api/
    โ”œโ”€โ”€ routes/
    โ”‚   โ””โ”€โ”€ routes.py           # All endpoints (register, login, ...)
    โ”œโ”€โ”€ database/
    โ”‚   โ”œโ”€โ”€ config.py           # SQLAlchemy setup
    โ”‚   โ””โ”€โ”€ models/
    โ”‚       โ”œโ”€โ”€ model_user.py   # User model + password hashing
    โ”‚       โ””โ”€โ”€ blacklist_model.py
    โ””โ”€โ”€ utils/
        โ”œโ”€โ”€ factory.py          # Builds the Flask app (the "app factory")
        โ”œโ”€โ”€ config.py           # Configuration classes
        โ”œโ”€โ”€ auth.py             # Token serializers + auth object
        โ”œโ”€โ”€ decorators.py       # @permission role checks
        โ””โ”€โ”€ responses.py        # Helper for consistent JSON responses

Prerequisites

  • Python 3.8+
  • A tool to send HTTP requests: httpie (used below), curl, Postman, or Insomnia.

Quick start

# 1. Get the code
git clone https://github.com/melihcolpan/flask-login-example
cd flask-login-example

# 2. Create and activate a virtual environment
python -m venv venv
source venv/bin/activate        # On Windows: venv\Scripts\activate

# 3. Install dependencies
pip install -r requirements.txt

# 4. Set the required secrets (any random strings; generated here for you)
export JWT_SECRET=$(python -c "import secrets; print(secrets.token_hex(32))")
export REFRESH_JWT_SECRET=$(python -c "import secrets; print(secrets.token_hex(32))")
export SECRET_KEY=$(python -c "import secrets; print(secrets.token_hex(32))")

# 5. (Optional, recommended for a first try) create ready-made demo users
export SEED_DEMO_USERS=true

# 6. Run it
python run.py

The API is now running at http://localhost:5000.

๐Ÿ’ก On Windows PowerShell, use $env:JWT_SECRET="..." instead of export.

Environment variables

Variable Required Default What it does
JWT_SECRET โœ… โ€“ Signs access tokens. Keep it secret.
REFRESH_JWT_SECRET โœ… โ€“ Signs refresh tokens. Keep it secret.
SECRET_KEY โœ… โ€“ Flask's secret key.
APP_CONFIG โŒ production production, development (debug on), or testing.
SEED_DEMO_USERS โŒ false Set to true to create the demo accounts listed below.
DATABASE_URI โŒ local SQLite Override the database connection string.

The app refuses to start if a required secret is missing โ€” this prevents accidentally shipping hardcoded secrets.

Demo accounts

These are created only when you run with SEED_DEMO_USERS=true (off by default, so a real deployment never ships with known passwords):

Role Email Password
Super admin sa_email@example.com sa_password
Admin admin_email@example.com admin_password
User test_email@example.com test_password

How authentication works (the 30-second version)

  1. You register a user, then log in with their email + password.
  2. The server returns two tokens inside the value field:
    • access_token โ€” short-lived (1 hour). Send it on every protected request as Authorization: Bearer <access_token>.
    • refresh_token โ€” longer-lived (2 hours). Use it to get a fresh access token without logging in again.
  3. Logout invalidates a refresh token by blacklisting it.

Every response has the same shape:

{ "code": "test_stat", "message": "SUCCESS.", "value": { ... } }

API reference

Base URL: http://localhost:5000

Method Endpoint Auth required Description
POST /v1.0/auth/register โ€“ Create a new user
POST /v1.0/auth/login โ€“ (rate limited) Log in, receive tokens
POST /v1.0/auth/refresh โ€“ Exchange a refresh token for a new access token
POST /v1.0/auth/logout โœ… Bearer Invalidate a refresh token
POST /v1.0/auth/password_change โœ… Bearer Change your password
GET /v1.0/data โœ… Admin+ Example protected route โ€” lists users

Note on roles: register always creates a normal user. The admin and super_admin roles come from the demo seed or are assigned directly in the database.


Usage examples

Examples use httpie, with a curl equivalent for the first two.

1. Register

http POST :5000/v1.0/auth/register \
  username=alice password=s3cret-pass email=alice@example.com
# curl version
curl -X POST http://localhost:5000/v1.0/auth/register \
  -H "Content-Type: application/json" \
  -d '{"username":"alice","password":"s3cret-pass","email":"alice@example.com"}'

2. Login

http POST :5000/v1.0/auth/login email=alice@example.com password=s3cret-pass
# curl version
curl -X POST http://localhost:5000/v1.0/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"alice@example.com","password":"s3cret-pass"}'

Response โ€” the tokens are under value:

{
  "code": "test_stat",
  "message": "SUCCESS.",
  "value": {
    "access_token": "eyJ...",
    "refresh_token": "eyJ..."
  }
}

3. Call a protected route

http GET :5000/v1.0/data Authorization:"Bearer <ACCESS_TOKEN>"

4. Refresh an expired access token

http POST :5000/v1.0/auth/refresh refresh_token=<REFRESH_TOKEN>

5. Change your password

http POST :5000/v1.0/auth/password_change \
  Authorization:"Bearer <ACCESS_TOKEN>" \
  old_pass=s3cret-pass new_pass=ev3nm0resecret

6. Logout (invalidate a refresh token)

http POST :5000/v1.0/auth/logout \
  Authorization:"Bearer <ACCESS_TOKEN>" \
  refresh_token=<REFRESH_TOKEN>

Running the tests

# Tests need the secret env vars and the testing config.
export JWT_SECRET=test REFRESH_JWT_SECRET=test SECRET_KEY=test
export APP_CONFIG=testing

python -m nose2 -v

You should see all tests pass.


Security notes

This example follows a few basic good practices:

  • No hardcoded secrets โ€” token secrets and SECRET_KEY come from the environment, and the app won't start without them.
  • Passwords are hashed with PBKDF2-SHA256; plaintext is never stored.
  • A password policy โ€” on registration and password change, a password must have at least 8 characters and not be only spaces. Passwords are used exactly as typed; leading and trailing spaces are part of the password.
  • Login doesn't leak which emails exist โ€” an unknown email and a wrong password get the same 401 response.
  • Roles are checked on every request โ€” admin-only routes deny by default: a missing or invalid token gets 401, a token without the role gets 403.
  • No default accounts by default โ€” demo users only exist when you opt in with SEED_DEMO_USERS=true.
  • Debug is off by default โ€” enable it only locally with APP_CONFIG=development.

For real production use, add HTTPS, a production WSGI server (e.g. gunicorn), a real database (PostgreSQL), and a shared rate-limit store (e.g. Redis).


License

MIT โ€” free to use, modify, and learn from.

About

flask-sqlalchemy-marshmallow-login-example

Resources

Security policy

Stars

10 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages