Debian Codegraph @

tests/view_scaffold.py

raw
1 # :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
2 # :license: MIT, see LICENSE for more details.
3
4 """
5 This is a simple scaffold that can be run as an app and manually test
6 various views using a browser.
7 It can be used to test translations by adding ?lang=xx. You might need to
8 delete the session cookie if you need to switch between languages (it is easy to
9 do this with your browser development tools).
10
11 Configurations can be set via environment variables.
12
13 Runs on port 5001
14
15 An initial user: [email protected]/password is created.
16 If you want to register a new user - you will receive a 'flash' that has the
17 confirm URL (with token) you need to enter into your browser address bar.
18
19 Since we don't actually send email - we have signal handlers flash the required
20 data and a mail sender that flashes what mail would be sent!
21
22 """
23
24 from __future__ import annotations
25
26 import base64
27 import secrets
28 from datetime import timedelta
29 import os
30 import typing as t
31 import webbrowser
32
33 from flask import Flask, flash, render_template_string, request, session, g
34
35 from flask_security import (
36 MailUtil,
37 Security,
38 UserDatastore,
39 UserMixin,
40 WebauthnUtil,
41 auth_required,
42 current_user,
43 SQLAlchemyUserDatastore,
44 FSQLALiteUserDatastore,
45 )
46 from flask_security.signals import (
47 us_security_token_sent,
48 tf_security_token_sent,
49 reset_password_instructions_sent,
50 user_not_registered,
51 user_registered,
52 )
53 from flask_security.utils import (
54 hash_password,
55 naive_utcnow,
56 uia_email_mapper,
57 uia_phone_mapper,
58 )
59
60
61 def _find_bool(v):
62 if str(v).lower() in ["true"]:
63 return True
64 elif str(v).lower() in ["false"]:
65 return False
66 return v
67
68
69 class FlashMailUtil(MailUtil):
70 def send_mail(
71 self,
72 template: str,
73 subject: str,
74 recipient: str | tuple[str, str],
75 sender: str | tuple[str, str],
76 body: str | None,
77 html: str | None,
78 **kwargs: t.Any,
79 ) -> None:
80 flash(f"Email body: {body}")
81 if html:
82 hb = html.encode()
83 url = "data:text/html;base64," + base64.b64encode(hb).decode()
84 webbrowser.open(url, new=1)
85
86
87 SET_LANG = False
88
89
90 def fsqla_datastore(app):
91 from flask_sqlalchemy import SQLAlchemy
92 from flask_security.models import fsqla_v3 as fsqla
93 from sqlalchemy_utils import database_exists, create_database
94
95 # Create database models and hook up.
96 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
97 app.config.setdefault("SQLALCHEMY_DATABASE_URI", "sqlite:///:memory:")
98 db = SQLAlchemy(app)
99 fsqla.FsModels.set_db_info(db)
100
101 class Role(db.Model, fsqla.FsRoleMixin):
102 pass
103
104 class User(db.Model, fsqla.FsUserMixin):
105 pass
106
107 class WebAuthn(db.Model, fsqla.FsWebAuthnMixin):
108 pass
109
110 with app.app_context():
111 if not database_exists(db.engine.url):
112 create_database(db.engine.url)
113 db.create_all()
114 return SQLAlchemyUserDatastore(db, User, Role, WebAuthn)
115
116
117 def fsqla_lite_datastore(app: Flask) -> FSQLALiteUserDatastore:
118 from sqlalchemy.orm import DeclarativeBase
119 from flask_sqlalchemy_lite import SQLAlchemy
120 from flask_security.models import sqla as sqla
121 from sqlalchemy_utils import database_exists, create_database
122
123 # Create database models and hook up.
124 app.config.setdefault("SQLALCHEMY_DATABASE_URI", "sqlite:///:memory:")
125
126 app.config |= {
127 "SQLALCHEMY_ENGINES": {
128 "default": {
129 "url": app.config["SQLALCHEMY_DATABASE_URI"],
130 "pool_pre_ping": True,
131 },
132 },
133 }
134 db = SQLAlchemy(app)
135
136 class Model(DeclarativeBase):
137 pass
138
139 sqla.FsModels.set_db_info(base_model=Model)
140
141 class Role(Model, sqla.FsRoleMixin):
142 __tablename__ = "role"
143 pass
144
145 class User(Model, sqla.FsUserMixin):
146 __tablename__ = "user"
147 pass
148
149 class WebAuthn(Model, sqla.FsWebAuthnMixin):
150 __tablename__ = "web_authn" # N.B. this is name that Flask-SQLAlchemy gives.
151 pass
152
153 with app.app_context():
154 if not database_exists(db.engine.url):
155 create_database(db.engine.url)
156 Model.metadata.create_all(db.engine)
157 return FSQLALiteUserDatastore(db, User, Role, WebAuthn)
158
159
160 def create_app() -> Flask:
161 # Use real templates - not test templates...
162 app = Flask("view_scaffold", template_folder="../")
163 app.config["SERVER_NAME"] = "localhost"
164 app.config["DEBUG"] = True
165 # SECRET_KEY generated using: secrets.token_urlsafe()
166 app.config["SECRET_KEY"] = "pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw"
167 # PASSWORD_SALT secrets.SystemRandom().getrandbits(128)
168 app.config["SECURITY_PASSWORD_SALT"] = "156043940537155509276282232127182067465"
169
170 app.config["LOGIN_DISABLED"] = False
171 app.config["REMEMBER_COOKIE_SAMESITE"] = "strict"
172 # 'strict' causes redirect after OAuth to fail since session cookie not sent
173 # this just happens on first 'register' with e.g. github
174 # app.config["SESSION_COOKIE_SAMESITE"] = "strict"
175 app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"] = [
176 {"email": {"mapper": uia_email_mapper, "case_insensitive": True}},
177 {"us_phone_number": {"mapper": uia_phone_mapper}},
178 ]
179 # app.config["SECURITY_US_ENABLED_METHODS"] = ["password"]
180 # app.config["SECURITY_US_ENABLED_METHODS"] = ["authenticator", "password"]
181 # app.config["SECURITY_US_SIGNIN_REPLACES_LOGIN"] = True
182 # app.config["SECURITY_WAN_ALLOW_USER_HINTS"] = False
183
184 # Setup script nonces and test with nonce-based content-security policy
185 app.config["SECURITY_SCRIPT_NONCE_KEY"] = "csp_nonce"
186
187 @app.before_request
188 def set_nonce():
189 g.csp_nonce = secrets.token_urlsafe(16)
190
191 @app.after_request
192 def inject_csp_header(response):
193 response.headers["Content-Security-Policy"] = (
194 f"script-src 'nonce-{g.csp_nonce}'"
195 )
196 return response
197
198 app.config["SECURITY_TOTP_SECRETS"] = {
199 "1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B"
200 }
201 app.config["SECURITY_TOTP_ISSUER"] = "me"
202 app.config["SECURITY_FRESHNESS"] = timedelta(minutes=10)
203 app.config["SECURITY_FRESHNESS_GRACE_PERIOD"] = timedelta(minutes=20)
204 app.config["SECURITY_USERNAME_ENABLE"] = True
205 app.config["SECURITY_USERNAME_REQUIRED"] = True
206 app.config["SECURITY_PASSWORD_REQUIRED"] = False # allow registration w/o password
207 app.config["SECURITY_RETURN_GENERIC_RESPONSES"] = False
208 # enable OAuth - note that this assumes that app is passes XXX_CLIENT_ID and
209 # XXX_CLIENT_SECRET as environment variables.
210 app.config["SECURITY_OAUTH_ENABLE"] = True
211 # app.config["SECURITY_URL_PREFIX"] = "/fs"
212
213 class TestWebauthnUtil(WebauthnUtil):
214 def generate_challenge(self, nbytes: int | None = None) -> str:
215 # Use a constant Challenge so we can use this app to generate gold
216 # responses for use in unit testing. See test_webauthn.
217 # NEVER NEVER NEVER do this in production
218 return "smCCiy_k2CqQydSQ_kPEjV5a2d0ApfatcpQ1aXDmQPo"
219
220 def origin(self) -> str:
221 # Return the RP origin - normally this is just the URL of the application.
222 # To test with ngrok - we need the https address that the browser originally
223 # sent - it is sent as the ORIGIN header - not sure if this should be
224 # default or just for testing.
225 return request.origin if request.origin else request.host_url.rstrip("/")
226
227 # Turn on all features (except passwordless since that removes normal login)
228 for opt in [
229 "changeable",
230 "change_email",
231 "change_username",
232 "recoverable",
233 "registerable",
234 "trackable",
235 "NOTpasswordless",
236 "confirmable",
237 "two_factor",
238 "username_recovery",
239 "unified_signin",
240 "webauthn",
241 "multi_factor_recovery_codes",
242 ]:
243 app.config["SECURITY_" + opt.upper()] = True
244
245 if os.environ.get("SETTINGS"):
246 # Load settings from a file pointed to by SETTINGS
247 app.config.from_envvar("SETTINGS")
248 # Allow any SECURITY_, SQLALCHEMY, Authlib config to be set in environment.
249 for ev in os.environ:
250 if (
251 ev.startswith("SECURITY_")
252 or ev.startswith("SQLALCHEMY_")
253 or "_CLIENT_" in ev
254 ):
255 app.config[ev] = _find_bool(os.environ.get(ev))
256
257 app.config["SECURITY_LOGOUT_CSRF"] = True
258 # app.config["WTF_CSRF_CHECK_DEFAULT"] = False
259 # CSRFProtect(app)
260
261 # Setup Flask-Security
262 # user_datastore = fsqla_datastore(app)
263 user_datastore = fsqla_lite_datastore(app)
264
265 security = Security(
266 app,
267 user_datastore,
268 webauthn_util_cls=TestWebauthnUtil,
269 mail_util_cls=FlashMailUtil,
270 )
271
272 # Setup Babel
273 def get_locale():
274 # For a given session - set lang based on first request.
275 # Honor explicit url request first
276 if not session: # if running CLI
277 return
278 global SET_LANG
279 if not SET_LANG:
280 session.pop("lang", None)
281 SET_LANG = True
282 if "lang" not in session:
283 locale = request.args.get("lang", None)
284 if not locale:
285 locale = request.accept_languages.best
286 if not locale:
287 locale = "en"
288 if locale:
289 session["lang"] = locale
290 return session.get("lang", None).replace("-", "_")
291
292 try:
293 import flask_babel
294
295 flask_babel.Babel(app, locale_selector=get_locale)
296 except ImportError:
297 pass
298
299 @user_registered.connect_via(app)
300 def on_user_registered(
301 myapp: Flask, user: UserMixin, confirm_token: str, **extra: dict[str, t.Any]
302 ) -> None:
303 flash(f"To confirm {user.email} - go to /confirm/{confirm_token}")
304
305 @user_not_registered.connect_via(app)
306 def on_user_not_registered(myapp, **extra):
307 if extra.get("existing_email"):
308 flash(f"Tried to register existing email: {extra['user'].email}")
309 elif extra.get("existing_username"):
310 flash(
311 f"Tried to register email: {extra['form_data'].email.data}"
312 f" with username: {extra['form_data'].username.data}"
313 )
314 else:
315 flash("Not registered response - but ??")
316
317 @reset_password_instructions_sent.connect_via(app)
318 def on_reset(myapp, user, token, **extra):
319 flash(f"Go to /reset/{token}")
320
321 @tf_security_token_sent.connect_via(app)
322 def on_token_sent(myapp, user, token, method, **extra):
323 flash(
324 "User {} was sent two factor token {} via {}".format(
325 user.calc_username(), token, method
326 )
327 )
328
329 @us_security_token_sent.connect_via(app)
330 def on_us_token_sent(myapp, user, token, method, **extra):
331 flash(
332 "User {} was sent sign in code {} via {}".format(
333 user.calc_username(), token, method
334 )
335 )
336
337 # Views
338 @app.route("/")
339 @auth_required()
340 def home():
341 return render_template_string(
342 """
343 {% extends "security/base.html" %}
344 {% block content %}
345 {% include 'security/_messages.html' %}
346 {{ _fsdomain('Welcome') }} {{email}} !
347 {% include "security/_menu.html" %}
348 {% endblock content %}
349 """,
350 email=current_user.email,
351 security=security,
352 )
353
354 @app.route("/basicauth")
355 @auth_required("basic")
356 def basic():
357 return render_template_string("Basic auth success")
358
359 @app.route("/protected")
360 @auth_required()
361 def protected():
362 return render_template_string("Protected endpoint")
363
364 return app
365
366
367 def add_user(
368 ds: UserDatastore, email: str, password: str, role_names: list[str]
369 ) -> None:
370 pw = hash_password(password)
371 roles = [ds.find_or_create_role(rn) for rn in role_names]
372 ds.commit()
373 user = ds.create_user(
374 email=email, password=pw, active=True, confirmed_at=naive_utcnow()
375 )
376 ds.commit()
377 for role in roles:
378 ds.add_role_to_user(user, role)
379 ds.commit()
380
381
382 if __name__ == "__main__":
383 myapp = create_app()
384 security: Security = myapp.extensions["security"]
385
386 with myapp.app_context():
387 test_acct = "[email protected]"
388 if not security.datastore.find_user(email=test_acct):
389 add_user(security.datastore, test_acct, "password", ["admin"])
390 print("Created User: {} with password {}".format(test_acct, "password"))
391
392 myapp.run(port=5001)