Quickly add security features to your Flask application.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Essential classes and functions for initializing Flask-Security in your application, including the main Security extension class, user/role mixins, and configuration management.
The main Flask-Security extension class that initializes and configures the security framework for your Flask application.
class Security:
"""
Main Flask-Security extension class.
Parameters:
- app: Flask application instance (optional)
- datastore: User datastore instance
- register_blueprint: Whether to register security blueprint (default: True)
- login_form: Custom login form class
- confirm_register_form: Custom registration confirmation form class
- register_form: Custom registration form class
- forgot_password_form: Custom forgot password form class
- reset_password_form: Custom reset password form class
- change_password_form: Custom change password form class
- send_confirmation_form: Custom send confirmation form class
- passwordless_login_form: Custom passwordless login form class
"""
def __init__(self, app=None, datastore=None, **kwargs): ...
def init_app(self, app, datastore, register_blueprint=True, **kwargs): ...Base mixin providing standard methods and properties required for Flask-Security user models.
class UserMixin:
"""
Mixin for user models providing authentication interface.
Required attributes (implement in your User model):
- id: User identifier
- email: User email address
- password: Hashed password
- active: Boolean indicating if user is active
"""
def is_authenticated(self) -> bool:
"""Return True if user is authenticated."""
def is_active(self) -> bool:
"""Return True if user account is active."""
def is_anonymous(self) -> bool:
"""Return False for real users (always False for UserMixin)."""
def get_id(self) -> str:
"""Return unique identifier for user as unicode string."""
def has_role(self, role) -> bool:
"""Return True if user has the specified role."""
def get_security_payload(self) -> dict:
"""Return user data for token payload."""
@property
def roles(self):
"""Return list of roles assigned to user."""
def get_auth_token(self) -> str:
"""Generate authentication token for user."""Base mixin providing standard methods and properties for Flask-Security role models.
class RoleMixin:
"""
Mixin for role models providing role comparison interface.
Required attributes (implement in your Role model):
- name: Role name
- description: Role description (optional)
"""
def __eq__(self, other) -> bool:
"""Compare roles for equality."""
def __ne__(self, other) -> bool:
"""Compare roles for inequality."""
def __hash__(self) -> int:
"""Return hash of role for set operations."""Mixin providing WebAuthn credential management for user models when WebAuthn is enabled.
class WebAuthnMixin:
"""
Mixin for user models providing WebAuthn credential interface.
"""
@property
def webauthn_credentials(self):
"""Return list of WebAuthn credentials for user."""
def get_webauthn_credential_by_id(self, credential_id):
"""Get WebAuthn credential by ID."""
def get_webauthn_credential_options(self) -> dict:
"""Get options for WebAuthn credential creation."""Proxy object providing access to the currently authenticated user in the request context.
def current_user():
"""
Proxy to the current user object for the request.
Returns:
- User object if authenticated
- AnonymousUser object if not authenticated
"""Default anonymous user implementation for unauthenticated requests.
class AnonymousUser:
"""
Anonymous user object for unauthenticated requests.
"""
def is_authenticated(self) -> bool:
"""Return False for anonymous users."""
def is_active(self) -> bool:
"""Return False for anonymous users."""
def is_anonymous(self) -> bool:
"""Return True for anonymous users."""
def get_id(self) -> None:
"""Return None for anonymous users."""
def has_role(self, role) -> bool:
"""Return False for anonymous users."""Dataclass for storing form configuration information used internally by Flask-Security.
class FormInfo:
"""
Dataclass containing form configuration information.
Attributes:
- form_class: Form class to instantiate
- form_args: Arguments to pass to form constructor
- form_kwargs: Keyword arguments to pass to form constructor
"""
form_class: type
form_args: tuple = ()
form_kwargs: dict = Nonefrom 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:///app.db'
db = SQLAlchemy(app)
# Define User and Role 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)
description = db.Column(db.String(255))
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=db.backref('users', lazy='dynamic'))
# Initialize Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)from flask_security import Security, RegisterForm
from wtforms import StringField
from wtforms.validators import DataRequired
class ExtendedRegisterForm(RegisterForm):
first_name = StringField('First Name', [DataRequired()])
last_name = StringField('Last Name', [DataRequired()])
security = Security(app, user_datastore, register_form=ExtendedRegisterForm)app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_RECOVERABLE'] = True
app.config['SECURITY_CONFIRMABLE'] = True
app.config['SECURITY_PASSWORD_SALT'] = 'your-salt-here'
app.config['SECURITY_LOGIN_URL'] = '/auth/login'
app.config['SECURITY_LOGOUT_URL'] = '/auth/logout'