### Run Guided Installation Source: https://flaskbb.readthedocs.io/en/latest/installation.html Commands to initiate the interactive installation process. ```bash $ make install ``` ```bash flaskbb install ``` -------------------------------- ### Start Configuration Wizard Source: https://flaskbb.readthedocs.io/en/latest/installation.html Initiates the interactive setup wizard to generate a configuration file. ```bash flaskbb makeconfig ``` -------------------------------- ### Install and Run Gunicorn Source: https://flaskbb.readthedocs.io/en/latest/installation.html Install Gunicorn via pip and start the FlaskBB WSGI server. ```bash pip install gunicorn ``` ```bash gunicorn wsgi:flaskbb --log-file logs/gunicorn.log --pid gunicorn.pid -w 4 ``` -------------------------------- ### Install uWSGI Source: https://flaskbb.readthedocs.io/en/latest/installation.html Install uWSGI and the required Python plugin. ```bash $ sudo apt-get install uwsgi uwsgi-plugin-python ``` -------------------------------- ### Install FlaskBB Dependencies and Initialize Source: https://flaskbb.readthedocs.io/en/latest/installation.html Commands to install Python requirements and initialize the FlaskBB configuration and database. ```bash pip3.5 install --user -r requirements.txt pip3.5 install --user -e . flaskbb makeconfig flaskbb install ``` -------------------------------- ### Run Development Server Source: https://flaskbb.readthedocs.io/en/latest/installation.html Starts the development server using make or the CLI. ```bash make run ``` ```bash flaskbb --config flaskbb.cfg run ``` -------------------------------- ### Install a Plugin Source: https://flaskbb.readthedocs.io/en/latest/plugins/index.html Commands to register plugin settings and apply database migrations. ```bash flaskbb plugins install ``` ```bash flaskbb db upgrade @head ``` -------------------------------- ### Install project dependencies Source: https://flaskbb.readthedocs.io/en/latest/installation.html Install required packages using pip or the provided make command. ```bash $ pip install -r requirements.txt ``` ```bash $ make dependencies ``` -------------------------------- ### Install Supervisor Source: https://flaskbb.readthedocs.io/en/latest/installation.html Install the process control system on Debian-based systems. ```bash $ sudo apt-get install supervisor ``` -------------------------------- ### flaskbb_additional_setup(app, pluggy) Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/startup.html Hook for performing additional setup tasks after all other application setup has finished. ```APIDOC ## flaskbb_additional_setup(app, pluggy) ### Description Hook for any additional setup a plugin wants to do after all other application setup has finished. ### Parameters - **app** (object) - Required - The application object. - **pluggy** (object) - Required - The pluggy object. ``` -------------------------------- ### Configure Mail Settings Source: https://flaskbb.readthedocs.io/en/latest/installation.html SMTP configuration examples for Google Mail and local servers. ```python MAIL_SERVER = "smtp.gmail.com" MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USERNAME = "your_username@gmail.com" MAIL_PASSWORD = "your_password" MAIL_DEFAULT_SENDER = ("Your Name", "your_username@gmail.com") ``` ```python MAIL_SERVER = "localhost" MAIL_PORT = 25 MAIL_USE_SSL = False MAIL_USERNAME = "" MAIL_PASSWORD = "" MAIL_DEFAULT_SENDER = "noreply@example.org" ``` -------------------------------- ### Download a Plugin Source: https://flaskbb.readthedocs.io/en/latest/plugins/index.html Commands to download a plugin from PyPI or install a local development package. ```bash $ pip install flaskbb-plugin-MYPLUGIN ``` ```bash $ pip install -e . ``` -------------------------------- ### Implement additional setup hook Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/startup.html Use this hook to perform actions after application setup, such as wrapping the WSGI application with middleware. ```python @impl def flaskbb_additional_setup(app): app.wsgi_app = ProxyFix(app.wsgi_app) ``` -------------------------------- ### Install development dependencies Source: https://flaskbb.readthedocs.io/en/latest/installation.html Install additional packages required for the development process. ```bash $ pip install -r requirements-dev.txt ``` -------------------------------- ### Install and manage Redis Source: https://flaskbb.readthedocs.io/en/latest/installation.html Commands to install Redis via package managers and manage the service status using systemctl. ```bash # Installing redis using 'pacman': $ sudo pacman -S redis # Installing redis using 'apt-get': $ sudo apt-get install redis-server # Check if redis is already running. $ systemctl status redis # If not, start it. $ sudo systemctl start redis # Optional: Lets start redis everytime you boot your machine $ sudo systemctl enable redis ``` -------------------------------- ### Run FlaskBB Server Source: https://flaskbb.readthedocs.io/en/latest/installation.html Starts the FlaskBB application using a specific configuration file. ```bash flaskbb --config flaskbb.cfg run [+] Using config from: /path/to/flaskbb/flaskbb.cfg * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` -------------------------------- ### Configure uWSGI for FlaskBB Source: https://flaskbb.readthedocs.io/en/latest/installation.html Example configuration file for running FlaskBB with uWSGI. ```ini [uwsgi] base = /var/apps/flaskbb home = /var/apps/.virtualenvs/flaskbb/ pythonpath = %(base) socket = 127.0.0.1:30002 module = wsgi callable = flaskbb uid = apps gid = apps logto = /var/apps/flaskbb/logs/uwsgi.log plugins = python ``` -------------------------------- ### Install virtualenvwrapper on Arch Linux Source: https://flaskbb.readthedocs.io/en/latest/installation.html Use the system package manager to install virtualenvwrapper on Arch Linux. ```bash $ sudo pacman -S python-virtualenvwrapper ``` -------------------------------- ### Install virtualenvwrapper on macOS Source: https://flaskbb.readthedocs.io/en/latest/installation.html Use pip to install virtualenvwrapper on macOS systems. ```bash $ sudo pip install virtualenvwrapper ``` -------------------------------- ### Configure Select Field Choices Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/developing.html Example of defining choices and coercion for select fields. ```python 'forum_ids': { ... 'extra': {"choices": available_forums, "coerce": int} } ``` -------------------------------- ### Implement LDAP Authentication Provider Source: https://flaskbb.readthedocs.io/en/latest/development/api/authentication.html Example implementation of an AuthenticationProvider using LDAP for user verification. ```python class LDAPAuthenticationProvider(AuthenticationProvider): def __init__(self, ldap_client): self.ldap_client = ldap_client def authenticate(self, identifier, secret): user_dn = "uid={},ou=flaskbb,ou=org".format(identifier) try: self.ldap_client.bind_user(user_dn, secret) return db.session.execute( db.select(User) .join(UserLDAP) .filter(UserLDAP.dn == user_dn) ).scalar_one() except Exception: return None ``` -------------------------------- ### Validate Setting Values with Min/Max Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/developing.html Example of using min/max keywords for integer or string validation. ```python 'recent_topics': { ... 'extra': {"min": 1}, }, ``` -------------------------------- ### Example deprecation warning output Source: https://flaskbb.readthedocs.io/en/latest/development/api/deprecations.html The warning message generated when a deprecated function is called. ```text warning: RemovedInPluginV2: thing_removed_in_plugin_v2 and will be removed in version 2.0.0. ``` -------------------------------- ### Implement User Details Update Validators Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/event.html Gather validators for UserDetailsChange events. This example demonstrates using a markdown renderer to validate signature content. ```python class DontAllowImageSignatures(ChangeSetValidator): def __init__(self, renderer): self._renderer = renderer def validate(self, model, changeset): rendered = self._renderer.render(changeset.signature) if '
{{ form.example(class="form-control", placeholder=form.example.label.text) }} {%- for error in form.example.errors -%} {{error}} {%- endfor -%}
""" ``` -------------------------------- ### Handle Persistence Errors Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/core/exceptions.html Example of wrapping database operations in a PersistenceError to manage model saving failures. ```python class PersistenceError(BaseFlaskBBError): """ Used to catch down errors when persisting models to the database instead of letting all issues percolate up, this should be raised from those exceptions without smashing their tracebacks. Example:: try: db.session.add(new_user) db.session.commit() except Exception: raise PersistenceError("Couldn't save user account") """ ``` -------------------------------- ### Configure Plugin Metadata in setup.py Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/developing.html Required metadata and entry points for plugin discovery by FlaskBB. ```python setup( name="flaskbb-plugin-YOUR_PLUGIN_NAME", # name on PyPI packages=["your_package_name"], # name of the folder your plugin is located in version='1.0', url=, license=, author=, author_email=, description=, long_description=__doc__, include_package_data=True, zip_safe=False, platforms='any', entry_points={ 'flaskbb_plugin': [ 'unique_name_of_plugin = your_package_name.pluginmodule', # most important part ] } ) ``` -------------------------------- ### Enable uWSGI Configuration Source: https://flaskbb.readthedocs.io/en/latest/installation.html Create a symlink to enable the uWSGI configuration. ```bash ln -s /etc/uwsgi/apps-available/flaskbb /etc/uwsgi/apps-enabled/flaskbb ``` -------------------------------- ### Create MySQL Database Source: https://flaskbb.readthedocs.io/en/latest/installation.html Initialize the database with the required utf8 charset. ```sql CREATE DATABASE flaskbb CHARACTER SET utf8; ``` -------------------------------- ### Display FlaskBB CLI Help Source: https://flaskbb.readthedocs.io/en/latest/cli.html View the available commands and options for the FlaskBB CLI. ```bash Usage: flaskbb [OPTIONS] COMMAND [ARGS]... This is the commandline interface for flaskbb. Options: --config CONFIG Specify the config to use in dotted module notation e.g. flaskbb.configs.default.DefaultConfig --version Show the FlaskBB version. --help Show this message and exit. Commands: celery Preconfigured wrapper around the 'celery' command. db Perform database migrations. download-emojis Downloads emojis from emoji-cheat-sheet.com. install Installs flaskbb. makeconfig Generates a FlaskBB configuration file. plugins Plugins command sub group. populate Creates the necessary tables and groups for FlaskBB. reindex Reindexes the search index. run Runs a development server. shell Runs a shell in the app context. start Starts a production ready wsgi server. themes Themes command sub group. translations Translations command sub group. upgrade Updates the migrations and fixtures. urls Show routes for the app. users Create, update or delete users. ``` -------------------------------- ### Create a virtualenv with virtualenvwrapper Source: https://flaskbb.readthedocs.io/en/latest/installation.html Initialize a new virtual environment named flaskbb with a specified project path and Python interpreter. ```bash $ mkvirtualenv -a /path/to/flaskbb -p $(which python) flaskbb ``` -------------------------------- ### Configure Redis Source: https://flaskbb.readthedocs.io/en/latest/installation.html Settings to enable and connect to a Redis instance. ```python REDIS_ENABLED = True REDIS_URL = "redis://localhost:6379" # or with a password: "redis://:password@localhost:6379" REDIS_DATABASE = 0 ``` -------------------------------- ### Example deprecation warning with custom message Source: https://flaskbb.readthedocs.io/en/latest/development/api/deprecations.html The warning message output when a custom message is provided to the decorator. ```text warning: RemovedInPluginV2: thing_removed_in_plugin_v2 and will be removed in version 2.0.0. Use plugin.frobinator instead. ``` -------------------------------- ### List available npm build tasks Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html Displays the available npm tasks for building, minifying, and watching theme assets. ```bash Usage npm run [TASK] Available tasks clean rm -f node_modules autoprefixer postcss -u autoprefixer -r static/css/* scss ./tools/build_css uglify ./tools/build_js imagemin imagemin src/img/* -o static/img fonts ./tools/build_fonts build:css npm run scss && npm run autoprefixer build:js npm run uglify build:images npm run imagemin && npm run fonts build:all npm run build:css && npm run build:js && npm run build:images watch:css onchange 'src/scss' -- npm run build:css watch:js onchange 'src/js' -- npm run build:js watch:all npm-run-all -p watch:css watch:js ``` -------------------------------- ### Implement Email Updated Hook Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/plugins/spec.html Example implementation of the flaskbb_email_updated hook to notify users after their email address has been changed. ```python @impl def flaskbb_email_updated(app): send_email( "Email changed", [email_change.old_email], text_body=..., html_body=... ) ``` -------------------------------- ### Enable a Plugin Source: https://flaskbb.readthedocs.io/en/latest/plugins/index.html Command to activate a previously disabled plugin. ```bash flaskbb plugins enable ``` -------------------------------- ### Configure Caching with Redis Source: https://flaskbb.readthedocs.io/en/latest/installation.html Sets up caching to use the Redis backend. ```python CACHE_TYPE = "redis" CACHE_REDIS_URL = REDIS_URL ``` -------------------------------- ### Upgrade Database Models Source: https://flaskbb.readthedocs.io/en/latest/installation.html Apply database migrations after a release. ```bash flaskbb db upgrade ``` -------------------------------- ### Create a virtualenv manually Source: https://flaskbb.readthedocs.io/en/latest/installation.html Initialize a virtual environment named .venv without using virtualenvwrapper. ```bash $ virtualenv .venv ``` -------------------------------- ### Manage Plugin Database Migrations Source: https://flaskbb.readthedocs.io/en/latest/plugins/index.html Commands for generating, upgrading, and downgrading plugin-specific database revisions using Alembic. ```bash flaskbb db revision --branch "" ``` ```bash flaskbb db upgrade @head ``` ```bash flaskbb db downgrade @-1 ``` -------------------------------- ### Clone FlaskBB Repository Source: https://flaskbb.readthedocs.io/en/latest/installation.html Initial commands to download the FlaskBB source code from GitHub. ```bash git clone https://github.com/sh4nks/flaskbb.git cd flaskbb ``` -------------------------------- ### Configure WSGI Application Entry Point Source: https://flaskbb.readthedocs.io/en/latest/installation.html Modifications required in the WSGI configuration file to point to the FlaskBB application factory. ```python from flask_app import app as application ``` ```python from flaskbb import create_app application = create_app("/path/to/your/configuration/file") ``` -------------------------------- ### Import Default Application Templates Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html Reference default application templates directly without the theme() function. ```jinja2 {% from 'macros.html' import topnav %} ``` -------------------------------- ### Generate Development Configuration Source: https://flaskbb.readthedocs.io/en/latest/installation.html Generates a configuration file specifically for development environments. ```bash flaskbb makeconfig -d ``` ```bash flaskbb makeconfig --development ``` -------------------------------- ### Configure Theme Metadata Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html The info.json file provides essential theme metadata used by the application for identification and display. ```json { "application": "flaskbb", "identifier": "aurora", "name": "Aurora", "author": "Peter Justin", "license": "BSD 3-Clause", "website": "https://flaskbb.com", "description": "The default theme for FlaskBB.", "preview": "preview.png", "version": "1.0.0" } ``` -------------------------------- ### Implement profile settings menu hook Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/template.html Use this hook to populate the side bar menu on the user settings page. Return a list of tuples containing the view name and display text. ```python @impl(trylast=True) def flaskbb_tpl_profile_settings_menu(): return [ (None, 'Account Settings'), ('user.settings', 'General Settings'), ('user.change_user_details', 'Change User Details'), ('user.change_email', 'Change E-Mail Address'), ('user.change_password', 'Change Password') ] ``` -------------------------------- ### Implement Admin Settings Menu Hook Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/template.html Adds navigation links to the admin menu. Returns a list of tuples containing view name, display text, and an optional icon. ```python @impl(trylast=True) def flaskbb_tpl_admin_settings_menu(): # only add this item if the user is an admin if Permission(IsAdmin, identity=current_user): return [ ("myplugin.foobar", "Foobar", "fa fa-foobar") ] ``` -------------------------------- ### Implement Registration Post-Processor Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/event.html This hook executes after a user is successfully persisted to the database. Use it for post-registration actions like sending notifications or flashing messages. ```python def greet_user(user): flash(_("Thanks for registering {}".format(user.username))) @impl def flaskbb_registration_post_processor(user): greet_user(user) ``` -------------------------------- ### Implement Authentication Manager Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/core/auth/authentication.html Abstract base class for managing the overall authentication process. ```python class AuthenticationManager(ABC): """ Used to handle the authentication process. A default is implemented, however this interface is provided in case alternative flows are needed. If a user successfully passes through the entire authentication process, then it should be returned to the caller. """ [docs] @abstractmethod def authenticate(self, identifier, secret): """ This method is abstract. :param str identifier: An identifer for the user, typically this is either a username or an email. :param str secret: A secret to verify the user is who they say they are :returns: A fully authenticated but not yet logged in user :rtype: :class:`User` """ pass ``` -------------------------------- ### Querying the Plugin Registry Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/manager.html Use the PluginRegistry model to retrieve plugin information by name. ```python plugin = PluginRegistry.get_by(name="portal") ``` -------------------------------- ### Defining a Hook Implementation with Execution Order Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/hooks.html Use the HookimplMarker to define a hook and specify execution priority using the trylast attribute. ```python hookimpl = HookimplMarker('flaskbb') @hookimpl(trylast=True) def flaskbb_additional_setup(app): return "save the best for last" ``` -------------------------------- ### Configure Rate Limiting with Redis Source: https://flaskbb.readthedocs.io/en/latest/installation.html Enables rate limiting and sets the storage URL to Redis. ```python RATELIMIT_ENABLED = True RATELIMIT_STORAGE_URL = REDIS_URL ``` -------------------------------- ### Theme Directory Structure Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html The required file and folder hierarchy for a custom FlaskBB theme. ```text ── example_theme/ ├── node_modules │ └── ... ├── src │ ├── img │ │ └── ... │ ├── js │ │ └── ... │ └── scss │ └── ... ├── static │ ├── img │ ├── css │ ├── fonts │ └── js ├── templates │ ├── ... │ └── layout.html ├── tools │ ├── build_css │ ├── build_fonts │ └── build_js ├── info.json ├── LICENSE ├── package.json └── README.md ``` -------------------------------- ### Define Plugin Directory Structure Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/developing.html Standard file layout for a FlaskBB plugin package. ```text your_package_name |-- setup.py |-- my_plugin |-- __init__.py |-- views.py |-- models.py |-- forms.py |-- static | |-- style.css |-- templates |-- myplugin.html |-- migrations |-- 59f7c49b6289_init.py ``` -------------------------------- ### Implement Custom Authentication Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/plugins/spec.html Define alternative authentication providers or block authentication based on specific criteria. ```python def ldap_auth(identifier, secret): "basic ldap example with imaginary ldap library" user_dn = "uid={},ou=flaskbb,dc=flaskbb,dc=org" try: ldap.bind(user_dn, secret) return User.query.join( UserLDAP ).filter( UserLDAP.dn==user_dn ).with_entities(User).one() except: return None @impl def flaskbb_authenticate(identifier, secret): return ldap_auth(identifier, secret) ``` ```python def prevent_login_with_too_many_failed_attempts(identifier): user = User.get( db.or_( User.username == identifier, User.email == identifier ) ) if user is not None: if has_too_many_failed_logins(user): raise StopAuthentication(_( "Your account is temporarily locked due to too many" " login attempts" )) @impl(tryfirst=True) def flaskbb_authenticate(user, identifier): prevent_login_with_too_many_failed_attempts(identifier) ``` -------------------------------- ### Compile translations Source: https://flaskbb.readthedocs.io/en/latest/faq.html Run this command to resolve 'AttributeError: 'NullTranslations' object has no attribute 'add'' exceptions. ```bash $ flaskbb translations compile ``` -------------------------------- ### Run theme asset watcher Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html Executes the watch task to automatically rebuild JS and SCSS files upon changes. ```bash npm run watch:all ``` -------------------------------- ### Reference Application Static Files Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html Use the standard url_for() function to include static files provided by the core FlaskBB application. ```html ``` -------------------------------- ### Configure Supervisor for uWSGI Source: https://flaskbb.readthedocs.io/en/latest/installation.html Configuration snippet for managing uWSGI processes via Supervisor. ```ini [program:uwsgi] command=/usr/bin/uwsgi --emperor /etc/uwsgi/apps-enabled user=apps stopsignal=QUIT autostart=true autorestart=true redirect_stderr=true ``` -------------------------------- ### Implement profile sidebar links hook Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/template.html Populate the user profile sidebar menu by returning an iterable of NavigationItem instances. ```python @impl def flaskbb_tpl_profile_sidebar_links(user): return [ NavigationLink( endpoint="user.profile", name=_("Overview"), icon="fa fa-home", urlforkwargs={"username": user.username}, ), NavigationLink( endpoint="user.view_all_topics", name=_("Topics"), icon="fa fa-comments", urlforkwargs={"username": user.username}, ), NavigationLink( endpoint="user.view_all_posts", name=_("Posts"), icon="fa fa-comment", urlforkwargs={"username": user.username}, ), ] ``` -------------------------------- ### Activate a virtualenv Source: https://flaskbb.readthedocs.io/en/latest/installation.html Activate the virtual environment located in the .venv directory. ```bash $ source .venv/bin/activate ``` -------------------------------- ### Implement Registration Failure Handler Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/event.html Handle registration errors by inspecting the failures list. This allows for custom logic like suggesting alternative usernames when validation fails. ```python from .utils import fuzz_username def has_already_registered(failures): return any( attr = "username" and "already registered" in msg for (attr, msg) in failures ) def suggest_alternate_usernames(user_info, failures): if has_already_registered(failures): suggestions = fuzz_username(user_info.username) failures.append(("username", "Try: {}".format(suggestions))) @impl def flaskbb_registration_failure_handler(user_info, failures): suggest_alternate_usernames(user_info, failures) ``` -------------------------------- ### Extend and Import Theme Templates Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html Use the theme() function to reference templates within the current theme directory. ```jinja2 {% extends theme('layout.html') %} {% from theme('macros.html') import horizontal_field %} ``` -------------------------------- ### Define Theme Directory Structure Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html The standard layout for a FlaskBB theme folder, including metadata, license, static assets, and templates. ```text my_theme ├── info.json ├── LICENSE ├── static │ └── style.css └── templates └── layout.html ``` -------------------------------- ### Reference Theme Static Files Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html Use the theme_static() function to generate URLs for assets located within the theme's static folder. ```html ``` -------------------------------- ### Implement Authentication Provider Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/core/auth/authentication.html Abstract base class for creating custom authentication providers, such as LDAP. ```python class AuthenticationProvider(ABC): """ Used to provide an authentication service for FlaskBB. For example, an implementer may choose to use LDAP as an authentication source:: class LDAPAuthenticationProvider(AuthenticationProvider): def __init__(self, ldap_client): self.ldap_client = ldap_client def authenticate(self, identifier, secret): user_dn = "uid={},ou=flaskbb,ou=org".format(identifier) try: self.ldap_client.bind_user(user_dn, secret) return db.session.execute( db.select(User) .join(UserLDAP) .filter(UserLDAP.dn == user_dn) ).scalar_one() except Exception: return None During an authentication process, a provider may raise a :class:`StopAuthentication` exception to completely, but safely halt the process. This is most useful when multiple providers are being used. """ [docs] @abstractmethod def authenticate(self, identifier, secret): """ This method is abstract. :param str identifier: An identifer for the user, typically this is either a username or an email. :param str secret: A secret to verify the user is who they say they are :returns: An authenticated user. :rtype: :class:`User` """ pass def __call__(self, identifier, secret): return self.authenticate(identifier, secret) ``` -------------------------------- ### Accessing a Plugin Instance Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/manager.html Retrieve an enabled plugin instance directly from the application's pluggy manager. ```python plugin_instance = current_app.pluggy.get_plugin(name) ``` -------------------------------- ### flaskbb_tpl_admin_settings_menu(user) Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/template.html Emitted in the admin panel to add navigation links to the admin menu. Implementations should return a list of tuples containing the view name, display text, and an optional icon. ```APIDOC ## flaskbb_tpl_admin_settings_menu(user) ### Description This hook is emitted in the admin panel and used to add additional navigation links to the admin menu. ### Parameters - **user** (object) - Required - The current user object. ### Return Value - **list** - A list of tuples containing (view name, display text, icon). ``` -------------------------------- ### AccountActivator.initiate_account_activation Source: https://flaskbb.readthedocs.io/en/latest/development/api/accountmanagement.html Initiates the account activation process for a user, typically by sending a communication like an email. ```APIDOC ## initiate_account_activation(user) ### Description Used to extend an offer of activation to the user. This method is intended to trigger a permanent communication, such as an email, to the user. ### Parameters - **user** (User) - Required - The user that the activation request applies to. ### Errors - May raise `ValidationError` if token creation fails (e.g., invalid email or account already activated). ``` -------------------------------- ### Define Plugin Settings Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/developing.html Structure for the SETTINGS dictionary used to integrate with the Admin Panel. ```python SETTINGS = { # This key has to be unique across FlaskBB. # Using a prefix is recommended. 'forum_ids': { # Default Value. The type of the default value depends on the # SettingValueType. 'value': [1], # The Setting Value Type. 'value_type': SettingValueType.selectmultiple, # The human readable name of your configuration variable 'name': "Forum IDs", # A short description of what the settings variable does 'description': ("The forum ids from which forums the posts " "should be displayed on the portal."), # extra stuff like the 'choices' in a select field or the # validators are defined in here 'extra': {"choices": available_forums, "coerce": int} } } ``` -------------------------------- ### Implement LDAP Authentication Hook Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/event.html Demonstrates an alternative authentication provider using LDAP. The hook returns a User object or None, and is executed after other providers. ```python def ldap_auth(identifier, secret): "basic ldap example with imaginary ldap library" user_dn = "uid={},ou=flaskbb,dc=flaskbb,dc=org" try: ldap.bind(user_dn, secret) return User.query.join( UserLDAP ).filter( UserLDAP.dn==user_dn ).with_entities(User).one() except: return None @impl def flaskbb_authenticate(identifier, secret): return ldap_auth(identifier, secret) ``` -------------------------------- ### Implement Authentication Failure Handler Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/core/auth/authentication.html Abstract base class for handling post-authentication failures. ```python class AuthenticationFailureHandler(ABC): """ Used to post process authentication failures, such as no provider returning a user or a provider raising :class:`StopAuthentication`. Postprocessing may take many forms, such as incrementing the login attempts locking an account if too many attempts are made, forcing a reauth if the user is currently authenticated in a different session, etc. Failure handlers should not return a value as it will not be considered. """ [docs] @abstractmethod def handle_authentication_failure(self, identifier): """ This method is abstract. :param str identifier: An identifer for the user, typically this is either a username or an email. """ pass def __call__(self, identifier): self.handle_authentication_failure(identifier) ``` -------------------------------- ### Implement Post-Authentication Hook Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/event.html Executes logic after a user is authenticated but before they are set as the current user. This hook is blocking and should be used carefully. ```python def post_auth(user): today = utcnow() if is_anniversary(today, user.date_joined): flash(_("Happy registerversary!")) @impl def flaskbb_post_authenticate(user): post_auth(user) ``` -------------------------------- ### Uninstall a Plugin Source: https://flaskbb.readthedocs.io/en/latest/plugins/index.html Commands to revert database migrations and remove plugin settings. ```bash $ flaskbb db downgrade @base ``` ```bash $ flaskbb plugins uninstall ``` -------------------------------- ### AccountActivator.activate_account Source: https://flaskbb.readthedocs.io/en/latest/development/api/accountmanagement.html Handles the final activation of an account using a provided token. ```APIDOC ## activate_account(token) ### Description Used to handle the actual activation of an account by processing the serialized token provided by the user. ### Parameters - **token** (str) - Required - The raw serialized token sent to the user. ### Errors - May raise `TokenError` or `ValidationError` if the token is invalid, expired, or cannot be consumed. ``` -------------------------------- ### Implement Admin Settings Sidebar Hook Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/template.html Adds navigation links to the sidebar settings menu in the admin panel. Returns a list of tuples containing view name and display text. ```python @impl(trylast=True) def flaskbb_tpl_admin_settings_menu(): return [ ("myplugin.foobar", "Foobar") ] ``` -------------------------------- ### Define Post Menu Hooks Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/plugins/spec.html Hooks for inserting items at the beginning or end of the post menu. ```python @spec def flaskbb_tpl_post_menu_before(post): ``` ```python @spec def flaskbb_tpl_post_menu_after(post): ``` -------------------------------- ### Register a custom post markdown renderer Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/startup.html Use this hook to return a mistune renderer child class for posts and signatures. Ensure child classes call super and avoid adding new arguments to __init__. ```python class YellingRenderer(mistune.Renderer): def paragraph(self, text): return super(YellingRenderer, self).paragraph(text.upper()) @impl def flaskbb_load_post_markdown_class(): return YellingRenderer ``` -------------------------------- ### flaskbb_load_nonpost_markdown_plugins(plugins, app) Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/startup.html Hook for loading mistune renderer plugins used when rendering markdown in locations other than posts, such as category or forum descriptions. ```APIDOC ## flaskbb_load_nonpost_markdown_plugins(plugins, app) ### Description Hook for loading mistune renderer plugins used when rendering markdown in locations other than posts, for example in category or forum descriptions. Implementations should modify the plugins list directly. ### Parameters - **plugins** (list) - Required - List of mistune plugins to load. - **app** (Flask) - Required - The application object. ``` -------------------------------- ### flaskbb_registration_post_processor Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/event.html Hook for handling actions after a user has successfully registered and been persisted to the database. ```APIDOC ## flaskbb_registration_post_processor(user) ### Description Executes custom logic after a user has been successfully created in the database. ### Parameters - **user** (Object) - The user object that was successfully persisted. ``` -------------------------------- ### Define a ReauthenticateProvider Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/core/auth/authentication.html Implement a custom reauthentication provider by inheriting from ReauthenticateProvider and defining the reauthenticate method. ```python class LDAPReauthenticateProvider(ReauthenticateProvider): def __init__(self, ldap_client): self.ldap_client = ldap_client def reauthenticate(self, user, secret): user_dn = "uid={},ou=flaskbb,ou=org".format(user.username) try: self.ldap_client.bind_user(user_dn, secret) return True except Exception: return None ``` -------------------------------- ### Define New Post and Topic Form Hooks Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/plugins/spec.html Hooks for inserting fields into new post or new topic forms. ```python @spec def flaskbb_tpl_form_new_post_before(form): ``` ```python @spec def flaskbb_tpl_form_new_post_after(form): ``` ```python @spec def flaskbb_tpl_form_new_topic_before(form): ``` ```python @spec def flaskbb_tpl_form_new_topic_after(form): ``` -------------------------------- ### Registering a Blueprint via Hook Source: https://flaskbb.readthedocs.io/en/latest/development/plugin/hooks.html Implement the flaskbb_load_blueprints hook to register custom blueprints to the Flask application instance. ```python def flaskbb_load_blueprints(app): app.register_blueprint(portal, url_prefix="/portal") ``` -------------------------------- ### flaskbb_tpl_admin_settings_sidebar(user) Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/template.html Emitted in the admin panel settings tab to add navigation links to the sidebar settings menu. Implementations should return a list of tuples containing the view name and display text. ```APIDOC ## flaskbb_tpl_admin_settings_sidebar(user) ### Description This hook is emitted in the admin panels setting tab and used to add additional navigation links to the sidebar settings menu. ### Parameters - **user** (object) - Required - The current user object. ### Return Value - **list** - A list of tuples containing (view name, display text). ``` -------------------------------- ### Include Theme-Specific Templates Source: https://flaskbb.readthedocs.io/en/latest/development/theming.html Passing false as the second parameter to theme() forces the application to look only within the theme directory, disabling the fallback to default application templates. ```jinja2 {# This template, for example, does not exist in FlaskBB #} {% include theme('header.html', false) %} ``` -------------------------------- ### Configure Celery with Redis Source: https://flaskbb.readthedocs.io/en/latest/installation.html Configures Celery to use the Redis broker and result backend. ```python CELERY_BROKER_URL = REDIS_URL CELERY_RESULT_BACKEND = REDIS_URL ``` -------------------------------- ### Define Post Author Info Hooks Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/plugins/spec.html Hooks emitted before or after post author information is displayed. ```python @spec def flaskbb_tpl_post_author_info_before(user, post): ``` ```python @spec def flaskbb_tpl_post_author_info_after(user, post): ``` -------------------------------- ### Register a custom non-post markdown renderer Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/startup.html Use this hook to return a mistune renderer child class for non-post content like forum descriptions. Follow the same constraints regarding super calls and __init__ arguments as the post markdown hook. ```python class YellingRenderer(mistune.Renderer): def paragraph(self, text): return super(YellingRenderer, self).paragraph(text.upper()) @impl def flaskbb_load_nonpost_markdown_class(): return YellingRenderer ``` -------------------------------- ### Implement Registration Validators Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/event.html Use this hook to return a list of callables that validate registration info. Raise ValidationError or StopValidation to control the registration flow. ```python def cannot_be_named_fred(user_info): if user_info.username.lower() == 'fred': raise ValidationError(('username', 'Cannot name user fred')) @impl def flaskbb_gather_registration_validators(): return [cannot_be_named_fred] ``` -------------------------------- ### Remove a Plugin Source: https://flaskbb.readthedocs.io/en/latest/plugins/index.html Command to uninstall a plugin package from the environment. ```bash $ pip uninstall flaskbb-plugin-MYPLUGIN ``` -------------------------------- ### TokenSerializer.loads(raw_token) Source: https://flaskbb.readthedocs.io/en/latest/development/api/tokens.html Transforms a string representation of a token back into a Token instance. ```APIDOC ## TokenSerializer.loads(raw_token) ### Description Used to transform a string representation of a token into an actual Token instance. ### Parameters - **raw_token** (str) - Required - The string representation of the token. ### Returns - **Token** - The parsed token instance. ``` -------------------------------- ### flaskbb_cli(cli, app) Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/cli.html A hook used for registering custom CLI commands to the FlaskBB CLI group. ```APIDOC ## flaskbb_cli(cli, app) ### Description This hook allows plugins to register custom commands to the FlaskBB CLI. It receives the CLI group object and the application instance. ### Parameters - **cli** (FlaskBBGroup) - Required - The CLI group object used to register commands. - **app** (Flask) - Required - The current Flask application object. ### Example ```python @impl def flaskbb_cli(cli, app): @cli.command() def testplugin(): click.echo("Hello Testplugin") return testplugin ``` ``` -------------------------------- ### Configure Nginx for uWSGI Source: https://flaskbb.readthedocs.io/en/latest/installation.html Standard Nginx server block for FlaskBB using uWSGI. Ensure server_name, log paths, alias paths, and the uwsgi_pass socket address are updated for your environment. ```nginx server { listen 80; server_name forums.flaskbb.com; access_log /var/log/nginx/access.forums.flaskbb.log; error_log /var/log/nginx/error.forums.flaskbb.log; location / { try_files $uri @flaskbb; } # Static files location /static { alias /var/apps/flaskbb/flaskbb/static/; } location ~ ^/_themes/([^/]+)/(.*)$ { alias /var/apps/flaskbb/flaskbb/themes/$1/static/$2; } # robots.txt location /robots.txt { alias /var/apps/flaskbb/flaskbb/static/robots.txt; } location @flaskbb { uwsgi_pass 127.0.0.1:30002; include uwsgi_params; } } ``` -------------------------------- ### Define Authentication Exceptions Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/core/auth/authentication.html Custom exception classes used to control the authentication flow, such as halting attempts or forcing a logout. ```python class StopAuthentication(BaseFlaskBBError): """ Used by Authentication providers to halt any further attempts to authenticate a user. :param reason str: The reason why authentication was halted """ def __init__(self, reason): super(StopAuthentication, self).__init__(reason) self.reason = reason [docs] class ForceLogout(BaseFlaskBBError): """ Used to forcefully log a user out. :param reason str: The reason why the user was force logged out """ def __init__(self, reason): super(ForceLogout, self).__init__(reason) self.reason = reason ``` -------------------------------- ### Define Post Content Hooks Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/plugins/spec.html Hooks for modifying content before or after it is rendered. ```python @spec def flaskbb_tpl_post_content_before(post): ``` ```python @spec def flaskbb_tpl_post_content_after(post): ``` -------------------------------- ### Prevent Login via Authentication Hook Source: https://flaskbb.readthedocs.io/en/latest/development/hooks/event.html Shows how to block authentication by raising a StopAuthentication exception when specific conditions, such as too many failed attempts, are met. ```python def prevent_login_with_too_many_failed_attempts(identifier): user = User.get( db.or_( User.username == identifier, User.email == identifier ) ) if user is not None: if has_too_many_failed_logins(user): raise StopAuthentication(_( "Your account is temporarily locked due to too many" " login attempts" )) @impl(tryfirst=True) def flaskbb_authenticate(user, identifier): prevent_login_with_too_many_failed_attempts(identifier) ``` -------------------------------- ### AccountActivator Interface Definition Source: https://flaskbb.readthedocs.io/en/latest/_modules/flaskbb/core/auth/activation.html Defines the abstract base class for account activation, requiring implementations for initiating activation and processing activation tokens. ```python # -*- coding: utf-8 -*- """ flaskbb.core.auth.activation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Interfaces for handling account activation in FlaskBB :copyright: (c) 2014-2018 the FlaskBB Team :license: BSD, see LICENSE for more details """ from abc import ABC, abstractmethod [docs] class AccountActivator(ABC): """ Interface for managing account activation in installations that require a user to activate their account before using it. """ [docs] @abstractmethod def initiate_account_activation(self, user): """ This method is abstract. Used to extend an offer of activation to the user. This may take any form, but is recommended to take the form of a permanent communication such as email. This method may raise :class:`ValidationError` to communicate a failure when creating the token for the user to activate their account with (such as when a user has requested a token be sent to an email that is not registered in the installation or the account associated with that email has already been activated). :param user: The user that the activation request applies to. :type user: :class:`User` """ pass [docs] @abstractmethod def activate_account(self, token): """ This method is abstract. Used to handle the actual activation of an account. The token passed in is the serialized token communicated to the user to use for activation. This method may raise :class:`TokenError` or :class:`ValidationError` to communicate failures when parsing or consuming the token. :param str token: The raw serialized token sent to the user """ pass ```