Debian Codegraph @

tests/view_scaffold.py

raw
1 # :copyright: (c) 2019-2025 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 from flask_wtf import CSRFProtect
35
36 from flask_security import (
37 MailUtil,
38 Security,
39 UserDatastore,
40 UserMixin,
41 WebauthnUtil,
42 auth_required,
43 current_user,
44 SQLAlchemyUserDatastore,
45 FSQLALiteUserDatastore,
46 )
47 from flask_security.signals import (
48 us_security_token_sent,
49 tf_security_token_sent,
50 reset_password_instructions_sent,
51 user_not_registered,
52 user_registered,
53 )
54 from flask_security.utils import (
55 hash_password,
56 naive_utcnow,
57 uia_email_mapper,
58 uia_phone_mapper,
59 )
60
61
62 def _find_bool(v):
63 if str(v).lower() in ["true"]:
64 return True
65 elif str(v).lower() in ["false"]:
66 return False
67 return v
68
69
70 class FlashMailUtil(MailUtil):
71 def send_mail(
72 self,
73 template: str,
74 subject: str,
75 recipient: str,
76 sender: str | tuple,
77 body: str,
78 html: str | None,
79 **kwargs: t.Any,
80 ) -> None:
81 flash(f"Email body: {body}")
82 if html:
83 hb = html.encode()
84 url = "data:text/html;base64," + base64.b64encode(hb).decode()
85 webbrowser.open(url, new=1)
86
87
88 SET_LANG = False
89
90
91 def fsqla_datastore(app):
92 from flask_sqlalchemy import SQLAlchemy
93 from flask_security.models import fsqla_v3 as fsqla
94 from sqlalchemy_utils import database_exists, create_database
95
96 # Create database models and hook up.
97 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
98 app.config.setdefault("SQLALCHEMY_DATABASE_URI", "sqlite:///:memory:")
99 db = SQLAlchemy(app)
100 fsqla.FsModels.set_db_info(db)
101
102 class Role(db.Model, fsqla.FsRoleMixin):
103 pass
104
105 class User(db.Model, fsqla.FsUserMixin):
106 pass
107
108 class WebAuthn(db.Model, fsqla.FsWebAuthnMixin):
109 pass
110
111 with app.app_context():
112 if not database_exists(db.engine.url):
113 create_database(db.engine.url)
114 db.create_all()
115 return SQLAlchemyUserDatastore(db, User, Role, WebAuthn)
116
117
118 def fsqla_lite_datastore(app: Flask) -> FSQLALiteUserDatastore:
119 from sqlalchemy.orm import DeclarativeBase
120 from flask_sqlalchemy_lite import SQLAlchemy
121 from flask_security.models import sqla as sqla
122 from sqlalchemy_utils import database_exists, create_database
123
124 # Create database models and hook up.
125 app.config.setdefault("SQLALCHEMY_DATABASE_URI", "sqlite:///:memory:")
126
127 app.config |= {
128 "SQLALCHEMY_ENGINES": {
129 "default": {
130 "url": app.config["SQLALCHEMY_DATABASE_URI"],
131 "pool_pre_ping": True,
132 },
133 },
134 }
135 db = SQLAlchemy(app)
136
137 class Model(DeclarativeBase):
138 pass
139
140 sqla.FsModels.set_db_info(base_model=Model)
141
142 class Role(Model, sqla.FsRoleMixin):
143 __tablename__ = "role"
144 pass
145
146 class User(Model, sqla.FsUserMixin):
147 __tablename__ = "user"
148 pass
149
150 class WebAuthn(Model, sqla.FsWebAuthnMixin):
151 __tablename__ = "web_authn" # N.B. this is name that Flask-SQLAlchemy gives.
152 pass
153
154 with app.app_context():
155 if not database_exists(db.engine.url):
156 create_database(db.engine.url)
157 Model.metadata.create_all(db.engine)
158 return FSQLALiteUserDatastore(db, User, Role, WebAuthn)
159
160
161 def create_app() -> Flask:
162 # Use real templates - not test templates...
163 app = Flask("view_scaffold", template_folder="../")
164 app.config["SERVER_NAME"] = "localhost"
165 app.config["DEBUG"] = True
166 # SECRET_KEY generated using: secrets.token_urlsafe()
167 app.config["SECRET_KEY"] = "pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw"
168 # PASSWORD_SALT secrets.SystemRandom().getrandbits(128)
169 app.config["SECURITY_PASSWORD_SALT"] = "156043940537155509276282232127182067465"
170
171 app.config["LOGIN_DISABLED"] = False
172 app.config["WTF_CSRF_ENABLED"] = True
173 app.config["REMEMBER_COOKIE_SAMESITE"] = "strict"
174 # 'strict' causes redirect after OAuth to fail since session cookie not sent
175 # this just happens on first 'register' with e.g. github
176 # app.config["SESSION_COOKIE_SAMESITE"] = "strict"
177 app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"] = [
178 {"email": {"mapper": uia_email_mapper, "case_insensitive": True}},
179 {"us_phone_number": {"mapper": uia_phone_mapper}},
180 ]
181 # app.config["SECURITY_US_ENABLED_METHODS"] = ["password"]
182 # app.config["SECURITY_US_ENABLED_METHODS"] = ["authenticator", "password"]
183 # app.config["SECURITY_US_SIGNIN_REPLACES_LOGIN"] = True
184 # app.config["SECURITY_WAN_ALLOW_USER_HINTS"] = False
185
186 # Setup script nonces and test with nonce-based content-security policy
187 app.config["SECURITY_SCRIPT_NONCE_KEY"] = "csp_nonce"
188
189 @app.before_request
190 def set_nonce():
191 g.csp_nonce = secrets.token_urlsafe(16)
192
193 @app.after_request
194 def inject_csp_header(response):
195 response.headers["Content-Security-Policy"] = (
196 f"script-src 'nonce-{g.csp_nonce}'"
197 )
198 return response
199
200 app.config["SECURITY_TOTP_SECRETS"] = {
201 "1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B"
202 }
203 app.config["SECURITY_TOTP_ISSUER"] = "me"
204 app.config["SECURITY_FRESHNESS"] = timedelta(minutes=10)
205 app.config["SECURITY_FRESHNESS_GRACE_PERIOD"] = timedelta(minutes=20)
206 app.config["SECURITY_USERNAME_ENABLE"] = True
207 app.config["SECURITY_USERNAME_REQUIRED"] = True
208 app.config["SECURITY_PASSWORD_REQUIRED"] = False # allow registration w/o password
209 app.config["SECURITY_RETURN_GENERIC_RESPONSES"] = False
210 # enable OAuth - note that this assumes that app is passes XXX_CLIENT_ID and
211 # XXX_CLIENT_SECRET as environment variables.
212 app.config["SECURITY_OAUTH_ENABLE"] = True
213 # app.config["SECURITY_URL_PREFIX"] = "/fs"
214
215 class TestWebauthnUtil(WebauthnUtil):
216 def generate_challenge(self, nbytes: int | None = None) -> str:
217 # Use a constant Challenge so we can use this app to generate gold
218 # responses for use in unit testing. See test_webauthn.
219 # NEVER NEVER NEVER do this in production
220 return "smCCiy_k2CqQydSQ_kPEjV5a2d0ApfatcpQ1aXDmQPo"
221
222 def origin(self) -> str:
223 # Return the RP origin - normally this is just the URL of the application.
224 # To test with ngrok - we need the https address that the browser originally
225 # sent - it is sent as the ORIGIN header - not sure if this should be
226 # default or just for testing.
227 return request.origin if request.origin else request.host_url.rstrip("/")
228
229 # Turn on all features (except passwordless since that removes normal login)
230 for opt in [
231 "changeable",
232 "change_email",
233 "change_username",
234 "recoverable",
235 "registerable",
236 "trackable",
237 "NOTpasswordless",
238 "confirmable",
239 "two_factor",
240 "username_recovery",
241 "unified_signin",
242 "webauthn",
243 "multi_factor_recovery_codes",
244 ]:
245 app.config["SECURITY_" + opt.upper()] = True
246
247 if os.environ.get("SETTINGS"):
248 # Load settings from a file pointed to by SETTINGS
249 app.config.from_envvar("SETTINGS")
250 # Allow any SECURITY_, SQLALCHEMY, Authlib config to be set in environment.
251 for ev in os.environ:
252 if (
253 ev.startswith("SECURITY_")
254 or ev.startswith("SQLALCHEMY_")
255 or "_CLIENT_" in ev
256 ):
257 app.config[ev] = _find_bool(os.environ.get(ev))
258
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 {% include 'security/_messages.html' %}
344 {{ _fsdomain('Welcome') }} {{email}} !
345 {% include "security/_menu.html" %}
346 """,
347 email=current_user.email,
348 security=security,
349 )
350
351 @app.route("/basicauth")
352 @auth_required("basic")
353 def basic():
354 return render_template_string("Basic auth success")
355
356 @app.route("/protected")
357 @auth_required()
358 def protected():
359 return render_template_string("Protected endpoint")
360
361 return app
362
363
364 def add_user(
365 ds: UserDatastore, email: str, password: str, role_names: list[str]
366 ) -> None:
367 pw = hash_password(password)
368 roles = [ds.find_or_create_role(rn) for rn in role_names]
369 ds.commit()
370 user = ds.create_user(
371 email=email, password=pw, active=True, confirmed_at=naive_utcnow()
372 )
373 ds.commit()
374 for role in roles:
375 ds.add_role_to_user(user, role)
376 ds.commit()
377
378
379 if __name__ == "__main__":
380 myapp = create_app()
381 security: Security = myapp.extensions["security"]
382
383 with myapp.app_context():
384 test_acct = "[email protected]"
385 if not security.datastore.find_user(email=test_acct):
386 add_user(security.datastore, test_acct, "password", ["admin"])
387 print("Created User: {} with password {}".format(test_acct, "password"))
388
389 myapp.run(port=5001)