| 1 |
""" |
| 2 |
Copyright 2020-2024 by J. Christopher Wagner (jwag). All rights reserved. |
| 3 |
:license: MIT, see LICENSE for more details. |
| 4 |
|
| 5 |
A simple example of server and client utilizing unified sign in and other |
| 6 |
features of Flask-Security. |
| 7 |
|
| 8 |
In order to be self contained, to support things like email confirmation and |
| 9 |
unified sign in with email, we hack a Mail handler that stores the email link |
| 10 |
and an un-protected API to fetch it! |
| 11 |
|
| 12 |
This example is designed for a JSON and session cookie based client. |
| 13 |
|
| 14 |
""" |
| 15 |
|
| 16 |
import os |
| 17 |
|
| 18 |
from flask import Flask |
| 19 |
from flask_babel import Babel |
| 20 |
from flask_security import ( |
| 21 |
Security, |
| 22 |
SmsSenderFactory, |
| 23 |
SmsSenderBaseClass, |
| 24 |
uia_phone_mapper, |
| 25 |
uia_email_mapper, |
| 26 |
) |
| 27 |
from flask_wtf import CSRFProtect |
| 28 |
|
| 29 |
from models import db, user_datastore |
| 30 |
|
| 31 |
|
| 32 |
class CaptureMail: |
| 33 |
# A hack Mail service that simply captures what would be sent. |
| 34 |
def __init__(self, app): |
| 35 |
app.extensions["mail"] = self |
| 36 |
self.sent = list() |
| 37 |
|
| 38 |
def send(self, msg): |
| 39 |
self.sent.append(msg.body) |
| 40 |
|
| 41 |
def pop(self): |
| 42 |
if len(self.sent): |
| 43 |
return self.sent.pop(0) |
| 44 |
return None |
| 45 |
|
| 46 |
|
| 47 |
class SmsCaptureSender(SmsSenderBaseClass): |
| 48 |
# A hack SMS service that records SMS messages |
| 49 |
SmsSenderBaseClass.messages = [] |
| 50 |
|
| 51 |
def __init__(self): |
| 52 |
super().__init__() |
| 53 |
SmsSenderBaseClass.messages = [] |
| 54 |
|
| 55 |
def send_sms(self, from_number, to_number, msg): |
| 56 |
SmsSenderBaseClass.messages.append(msg) |
| 57 |
return |
| 58 |
|
| 59 |
@classmethod |
| 60 |
def pop(cls): |
| 61 |
if len(SmsSenderBaseClass.messages): |
| 62 |
return SmsSenderBaseClass.messages.pop(0) |
| 63 |
return None |
| 64 |
|
| 65 |
|
| 66 |
def create_app(): |
| 67 |
app = Flask(__name__) |
| 68 |
app.config["DEBUG"] = True |
| 69 |
# SECRET_KEY generated using: secrets.token_urlsafe() |
| 70 |
app.config["SECRET_KEY"] = "pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw" |
| 71 |
# PASSWORD_SALT secrets.SystemRandom().getrandbits(128) |
| 72 |
app.config["SECURITY_PASSWORD_SALT"] = "156043940537155509276282232127182067465" |
| 73 |
|
| 74 |
# We aren't interested in form-based APIs - so no need for flashing. |
| 75 |
app.config["SECURITY_FLASH_MESSAGES"] = False |
| 76 |
|
| 77 |
app.config["SECURITY_AUTO_LOGIN_AFTER_CONFIRM"] = True |
| 78 |
|
| 79 |
# Allow signing in with a phone number or email |
| 80 |
app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"] = [ |
| 81 |
{"email": {"mapper": uia_email_mapper, "case_insensitive": True}}, |
| 82 |
{"us_phone_number": {"mapper": uia_phone_mapper}}, |
| 83 |
] |
| 84 |
app.config["SECURITY_US_ENABLED_METHODS"] = ["password", "email", "sms"] |
| 85 |
|
| 86 |
app.config["SECURITY_TOTP_SECRETS"] = { |
| 87 |
"1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B" |
| 88 |
} |
| 89 |
|
| 90 |
# These need to be defined to handle redirects |
| 91 |
# As defined in the API documentation - they will receive the relevant context |
| 92 |
app.config["SECURITY_LOGIN_ERROR_VIEW"] = "/redir/login-error" |
| 93 |
app.config["SECURITY_POST_CONFIRM_VIEW"] = "/redir/confirmed" |
| 94 |
app.config["SECURITY_CONFIRM_ERROR_VIEW"] = "/redir/confirm-error" |
| 95 |
app.config["SECURITY_RESET_VIEW"] = "/redir/reset-password" |
| 96 |
app.config["SECURITY_RESET_ERROR_VIEW"] = "/redir/reset-password-error" |
| 97 |
app.config["SECURITY_REDIRECT_BEHAVIOR"] = "spa" |
| 98 |
|
| 99 |
# CSRF protection is critical for all session-based browser UIs |
| 100 |
# In general, most applications don't need CSRF on unauthenticated endpoints |
| 101 |
app.config["SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS"] = True |
| 102 |
|
| 103 |
# Send Cookie with csrf-token. This is the default for Axios and Angular. |
| 104 |
app.config["SECURITY_CSRF_COOKIE_NAME"] = "XSRF-TOKEN" |
| 105 |
app.config["WTF_CSRF_CHECK_DEFAULT"] = False |
| 106 |
app.config["WTF_CSRF_TIME_LIMIT"] = None |
| 107 |
|
| 108 |
# have session and remember cookie be samesite (flask/flask_login) |
| 109 |
app.config["REMEMBER_COOKIE_SAMESITE"] = "strict" |
| 110 |
app.config["SESSION_COOKIE_SAMESITE"] = "strict" |
| 111 |
|
| 112 |
# As of Flask-SQLAlchemy 2.4.0 it is easy to pass in options directly to the |
| 113 |
# underlying engine. This option makes sure that DB connections from the pool |
| 114 |
# are still valid. Important for entire application since many DBaaS options |
| 115 |
# automatically close idle connections. |
| 116 |
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"pool_pre_ping": True} |
| 117 |
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False |
| 118 |
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:" |
| 119 |
|
| 120 |
# Initialize a fake SMS service that captures SMS messages |
| 121 |
app.config["SECURITY_SMS_SERVICE"] = "capture" |
| 122 |
SmsSenderFactory.senders["capture"] = SmsCaptureSender |
| 123 |
|
| 124 |
# Turn on all features (except passwordless since that removes normal login) |
| 125 |
for opt in [ |
| 126 |
"changeable", |
| 127 |
"recoverable", |
| 128 |
"registerable", |
| 129 |
"trackable", |
| 130 |
"confirmable", |
| 131 |
"two_factor", |
| 132 |
"unified_signin", |
| 133 |
]: |
| 134 |
app.config["SECURITY_" + opt.upper()] = True |
| 135 |
|
| 136 |
if os.environ.get("SETTINGS"): |
| 137 |
# Load settings from a file pointed to by SETTINGS |
| 138 |
app.config.from_envvar("SETTINGS") |
| 139 |
|
| 140 |
# Initialize standard Flask extensions |
| 141 |
CaptureMail(app) |
| 142 |
Babel(app) |
| 143 |
# Enable CSRF on all api endpoints. |
| 144 |
CSRFProtect(app) |
| 145 |
db.init_app(app) |
| 146 |
# Setup Flask-Security |
| 147 |
app.security = Security(app, user_datastore) |
| 148 |
|
| 149 |
# Init our API |
| 150 |
from api import api |
| 151 |
|
| 152 |
app.register_blueprint(api, url_prefix="/api") |
| 153 |
return app |
| 154 |
|
| 155 |
|
| 156 |
if __name__ == "__main__": |
| 157 |
myapp = create_app() |
| 158 |
with myapp.app_context(): |
| 159 |
db.create_all() |
| 160 |
|
| 161 |
myapp.run(port=5002) |