CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/pypi-flask-security

Simple security for Flask apps

Overview
Eval results
Files

core-extension.mddocs/

Core Extension and Configuration

The Security extension class provides the main interface for initializing and configuring Flask-Security with your Flask application. It manages all security features, configures defaults, and integrates with Flask's application context.

Capabilities

Security Extension Initialization

The main Security class that initializes Flask-Security with comprehensive configuration options.

class Security:
    def __init__(self, app=None, datastore=None, **kwargs):
        """
        Initialize Flask-Security extension.
        
        Args:
            app (Flask, optional): Flask application instance
            datastore (UserDatastore, optional): User datastore implementation
            **kwargs: Additional configuration options
        """
    
    def init_app(self, app, datastore=None, register_blueprint=True,
                 login_form=None, confirm_register_form=None,
                 register_form=None, forgot_password_form=None,
                 reset_password_form=None, change_password_form=None,
                 send_confirmation_form=None, passwordless_login_form=None,
                 anonymous_user=None):
        """
        Initialize Flask-Security for the specified application.
        
        Args:
            app (Flask): Flask application instance
            datastore (UserDatastore, optional): User datastore implementation
            register_blueprint (bool): Whether to register security blueprint
            login_form (Form, optional): Custom login form class
            confirm_register_form (Form, optional): Custom confirm registration form
            register_form (Form, optional): Custom registration form class
            forgot_password_form (Form, optional): Custom forgot password form
            reset_password_form (Form, optional): Custom reset password form
            change_password_form (Form, optional): Custom change password form
            send_confirmation_form (Form, optional): Custom send confirmation form
            passwordless_login_form (Form, optional): Custom passwordless login form
            anonymous_user (AnonymousUser, optional): Custom anonymous user class
            
        Returns:
            SecurityState: Internal state object with configuration
        """
    
    def render_template(self, *args, **kwargs):
        """
        Render a template using Flask's render_template.
        
        Returns:
            str: Rendered template content
        """

Configuration System

Flask-Security uses a comprehensive configuration system with over 50 configuration options. All options are prefixed with SECURITY_ when set in Flask's config.

Key configuration categories:

  • Blueprint Settings: BLUEPRINT_NAME, URL_PREFIX, SUBDOMAIN
  • Feature Toggles: CONFIRMABLE, REGISTERABLE, RECOVERABLE, TRACKABLE, PASSWORDLESS, CHANGEABLE
  • URL Endpoints: LOGIN_URL, LOGOUT_URL, REGISTER_URL, RESET_URL, CHANGE_URL, CONFIRM_URL
  • Post-Action Redirects: POST_LOGIN_VIEW, POST_LOGOUT_VIEW, POST_REGISTER_VIEW, POST_CONFIRM_VIEW
  • Templates: LOGIN_USER_TEMPLATE, REGISTER_USER_TEMPLATE, RESET_PASSWORD_TEMPLATE
  • Email Settings: EMAIL_SENDER, SEND_REGISTER_EMAIL, SEND_PASSWORD_CHANGE_EMAIL
  • Security Parameters: PASSWORD_HASH, PASSWORD_SCHEMES, TOKEN_MAX_AGE
  • Time Limits: LOGIN_WITHIN, CONFIRM_EMAIL_WITHIN, RESET_PASSWORD_WITHIN

Example configuration:

app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_CONFIRMABLE'] = True
app.config['SECURITY_RECOVERABLE'] = True
app.config['SECURITY_TRACKABLE'] = True
app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SECURITY_PASSWORD_SALT'] = 'your-salt-here'
app.config['SECURITY_POST_LOGIN_VIEW'] = '/dashboard'
app.config['SECURITY_POST_LOGOUT_VIEW'] = '/'

Extension State and Context

The Security extension creates an internal state object that manages configuration, forms, serializers, and context processors.

class _SecurityState:
    """Internal state management for Flask-Security"""
    def context_processor(self, fn): ...
    def login_context_processor(self, fn): ...
    def register_context_processor(self, fn): ...
    def forgot_password_context_processor(self, fn): ...
    def reset_password_context_processor(self, fn): ...
    def change_password_context_processor(self, fn): ...
    def send_confirmation_context_processor(self, fn): ...
    def send_login_context_processor(self, fn): ...
    def mail_context_processor(self, fn): ...
    def send_mail_task(self, fn): ...
    def unauthorized_handler(self, fn): ...

Usage Examples

Basic Setup

from flask import Flask
from flask_security import Security, SQLAlchemyUserDatastore

app = Flask(__name__)
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

Application Factory Pattern

security = Security()

def create_app():
    app = Flask(__name__)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore)
    return app

Custom Forms

from flask_security.forms import LoginForm, RegisterForm
from wtforms import StringField

class CustomLoginForm(LoginForm):
    username = StringField('Username')

class CustomRegisterForm(RegisterForm):
    first_name = StringField('First Name')
    last_name = StringField('Last Name')

security = Security(app, user_datastore, 
                   login_form=CustomLoginForm,
                   register_form=CustomRegisterForm)

Context Processors

@security.context_processor  
def security_context():
    return dict(admin_base_template=admin.base_template)

@security.login_context_processor
def login_context():
    return dict(custom_login_data="value")
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