CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/pypi-flask-security

Simple security for Flask apps

Overview
Eval results
Files

index.mddocs/

Flask-Security

Flask-Security is a comprehensive Flask extension that provides authentication and authorization functionality for Flask web applications. It integrates seamlessly with Flask-Login for session management, Flask-Principal for role-based access control, Flask-WTF for secure forms, and passlib for password hashing. The library offers complete user management features including user registration, login/logout, password recovery, email confirmation, role-based permissions, and token-based authentication.

Package Information

  • Package Name: Flask-Security
  • Language: Python
  • Installation: pip install Flask-Security

Core Imports

from flask_security import Security

Common imports for user and role management:

from flask_security import (
    Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin,
    login_required, roles_required, login_user, logout_user
)

Basic Usage

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'

db = SQLAlchemy(app)

# Define models
roles_users = db.Table('roles_users',
    db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean(), default=True)
    roles = db.relationship('Role', secondary=roles_users, backref='users')

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

# Create database tables
with app.app_context():
    db.create_all()
    if not user_datastore.find_user(email="admin@example.com"):
        user_datastore.create_user(email="admin@example.com", password="password")
        db.session.commit()

Architecture

Flask-Security is built around several key components:

  • Security Extension: Central coordinator that initializes all components and registers blueprints
  • Datastores: Abstraction layer for user/role persistence across different ORMs (SQLAlchemy, MongoEngine, Peewee, Pony)
  • User/Role Mixins: Base classes providing standard authentication and authorization interfaces
  • Forms: WTForms-based forms for user registration, login, password reset, etc.
  • Views: Blueprint routes handling authentication workflows
  • Decorators: Function decorators for protecting views with authentication and authorization requirements
  • Signals: Flask signals for extending and customizing security workflows
  • Feature Modules: Optional capabilities like confirmation, password recovery, registration, passwordless login

Capabilities

Core Extension and Configuration

The main Security extension class and configuration system that initializes Flask-Security with your Flask application and manages all security features.

class Security:
    def __init__(self, app=None, datastore=None, **kwargs): ...
    def init_app(self, app, datastore=None, register_blueprint=True, **kwargs): ...

Core Extension

User and Role Management

Core classes and mixins for implementing user and role models compatible with Flask-Security's authentication and authorization system.

class UserMixin:
    def has_role(self, role): ...
    def get_auth_token(self): ...
    @property
    def is_active(self): ...

class RoleMixin:
    def __eq__(self, other): ...
    def __ne__(self, other): ...

class AnonymousUser:
    def has_role(self, *args): ...

User and Role Models

Data Storage and Persistence

Datastore classes that provide an abstraction layer for user and role persistence across different database backends and ORMs.

class SQLAlchemyUserDatastore:
    def __init__(self, db, user_model, role_model): ...
    def get_user(self, identifier): ...
    def find_user(self, **kwargs): ...
    def create_user(self, **kwargs): ...

class MongoEngineUserDatastore: ...
class PeeweeUserDatastore: ...
class PonyUserDatastore: ...

Data Storage

Authentication and Session Management

Functions and utilities for managing user authentication, login/logout operations, and session handling.

def login_user(user, remember=None): ...
def logout_user(): ...
def url_for_security(endpoint, **values): ...

# Current user proxy
current_user: User

Authentication

Authorization and Access Control

Decorators and utilities for implementing role-based access control and protecting views with authentication requirements.

def login_required(fn): ...
def roles_required(*roles): ...
def roles_accepted(*roles): ...
def auth_token_required(fn): ...
def http_auth_required(realm): ...
def auth_required(*auth_methods): ...

Authorization

Forms and User Interface

Form classes for handling user registration, login, password reset, and other security-related user interactions.

class LoginForm: ...
class RegisterForm: ...
class ConfirmRegisterForm: ...
class ForgotPasswordForm: ...
class ResetPasswordForm: ...
class PasswordlessLoginForm: ...

Forms

Signals and Extension Points

Signal objects that allow you to hook into Flask-Security's workflows for customization and extension.

user_registered: Signal
user_confirmed: Signal
confirm_instructions_sent: Signal
password_reset: Signal
reset_password_instructions_sent: Signal

Signals and Events

Feature Modules

Optional security features including email confirmation, password recovery, user registration, password changing, and passwordless authentication.

# Confirmable
def send_confirmation_instructions(user): ...
def confirm_user(user): ...

# Recoverable  
def send_reset_password_instructions(user): ...
def update_password(user, password): ...

# Registerable
def register_user(**kwargs): ...

Security Features

Types

class User:
    """Base user interface expected by Flask-Security"""
    id: Any
    email: str
    password: str
    active: bool
    roles: List[Role]

class Role:
    """Base role interface expected by Flask-Security"""
    name: str
tessl i tessl/pypi-flask-security@3.0.0

docs

authentication.md

authorization.md

core-extension.md

data-storage.md

forms.md

index.md

security-features.md

signals.md

user-role-models.md

tile.json