Debian Codegraph @

docs/quickstart.rst

raw
1 Quick Start
2 ===========
3
4 There are some complete (but simple) examples available in the *examples* directory of the
5 `Flask-Security repo`_.
6
7 .. note::
8 The below quickstarts are just that - they don't enable most of the features (such as registration, reset, etc.).
9 They basically create a single user, and you can login as that user... that's it.
10 As you add more features, additional packages (e.g. Flask-Mail, Flask-Babel, qrcode) might be required
11 and will need to be added to your requirements.txt (or equivalent) file.
12 Flask-Security does some configuration validation and will output error messages to the console
13 for some missing packages.
14 .. note::
15 The sqlalchemy based quickstarts all use the pre-packaged models - because, well, that's
16 the quickest and easiest way to get started. There is NO REQUIREMENT that your application
17 use these - as long as the required fields are in your models.
18
19 .. note::
20 The default :data:`SECURITY_PASSWORD_HASH` is "argon2" - so be sure to install `argon2_cffi`_.
21 If you opt for a different hash e.g. "bcrypt" you will need to install the appropriate package.
22 .. danger::
23 The examples below place secrets in source files. Never do this for your application
24 especially if your source code is placed in a public repo. How you pass in secrets
25 securely will depend on your deployment model - however in most cases (e.g. docker, lambda)
26 using environment variables will be the easiest.
27
28 .. _argon2_cffi: https://pypi.org/project/argon2-cffi/
29
30 * :ref:`basic-flask-sqlalchemy-application`
31 * :ref:`basic-flask-sqlalchemy-lite-application`
32 * :ref:`basic-sqlalchemy-application-with-session`
33 * :ref:`basic-mongoengine-application`
34 * :ref:`basic-peewee-application`
35 * :ref:`mail-configuration`
36 * :ref:`proxy-configuration`
37 * :ref:`unit-testing`
38
39 .. _basic-flask-sqlalchemy-application:
40
41 Basic Flask-SQLAlchemy Application
42 -----------------------------------
43
44 Flask-SQLAlchemy Install requirements
45 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
46
47 ::
48
49 $ python3 -m venv pymyenv
50 $ . pymyenv/bin/activate
51 $ pip install flask-security[fsqla,common]
52
53
54 Flask-SQLAlchemy Application
55 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
56
57 The following code sample illustrates how to get started as quickly as
58 possible using Flask-SQLAlchemy and the built-in model mixins.
59
60 .. code-block:: python
61
62 import os
63
64 from flask import Flask, render_template_string
65 from flask_sqlalchemy import SQLAlchemy
66 from flask_security import Security, SQLAlchemyUserDatastore, auth_required, hash_password
67 from flask_security.models import fsqla_v3 as fsqla
68
69 # Create app
70 app = Flask(__name__)
71 app.config['DEBUG'] = True
72
73 # Generate a nice key using secrets.token_urlsafe()
74 app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw')
75 # Generate a good salt for password hashing using: secrets.SystemRandom().getrandbits(128)
76 app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", '146585145368132386173505678016728509634')
77
78 # have session and remember cookie be samesite (flask/flask_login)
79 app.config["REMEMBER_COOKIE_SAMESITE"] = "strict"
80 app.config["SESSION_COOKIE_SAMESITE"] = "strict"
81
82 # Use an in-memory db
83 app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
84 # As of Flask-SQLAlchemy 2.4.0 it is easy to pass in options directly to the
85 # underlying engine. This option makes sure that DB connections from the
86 # pool are still valid. Important for entire application since
87 # many DBaaS options automatically close idle connections.
88 app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
89 "pool_pre_ping": True,
90 }
91 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
92
93 # Create database connection object
94 db = SQLAlchemy(app)
95
96 # Define models
97 fsqla.FsModels.set_db_info(db)
98
99 class Role(db.Model, fsqla.FsRoleMixin):
100 pass
101
102 class User(db.Model, fsqla.FsUserMixin):
103 pass
104
105 # Setup Flask-Security
106 user_datastore = SQLAlchemyUserDatastore(db, User, Role)
107 security = Security(app, user_datastore)
108
109 # Views
110 @app.route("/")
111 @auth_required()
112 def home():
113 return render_template_string("Hello {{ current_user.email }}")
114
115 # one time setup
116 with app.app_context():
117 # Create User to test with
118 db.create_all()
119 if not security.datastore.find_user(email="[email protected]"):
120 security.datastore.create_user(email="[email protected]", password=hash_password("password"))
121 db.session.commit()
122
123 if __name__ == '__main__':
124 app.run()
125
126 You can run this either with::
127
128 flask run
129
130 or::
131
132 python app.py
133
134 .. _basic-flask-sqlalchemy-lite-application:
135
136 Basic Flask-SQLAlchemy-Lite Application
137 ----------------------------------------
138
139 Flask-SQLAlchemy Install requirements
140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
141
142 This requires python >= 3.10::
143
144 $ python3 -m venv pymyenv
145 $ . pymyenv/bin/activate
146 $ pip install flask-security[common] sqlalchemy flask-sqlalchemy-lite
147
148 Flask-SQLAlchemy-Lite Application
149 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
150
151 The following code sample illustrates how to get started as quickly as
152 possible using Flask-SQLAlchemy-Lite and the built-in model mixins.
153 Note that Flask-SQLAlchemy-Lite is a very thin wrapper above sqlalchemy.orm
154 and just provides session and engine initialization. Everything else is
155 pure sqlalchemy (unlike Flask-SQLAlchemy).
156
157 .. code-block:: python
158
159 import os
160
161 from sqlalchemy.orm import DeclarativeBase
162 from flask import Flask, render_template_string
163 from flask_sqlalchemy_lite import SQLAlchemy
164 from flask_security import Security, FSQLALiteUserDatastore, auth_required, hash_password
165 from flask_security.models import sqla as sqla
166
167 # Create app
168 app = Flask(__name__)
169 app.config['DEBUG'] = True
170
171 # Generate a nice key using secrets.token_urlsafe()
172 app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw')
173 # Generate a good salt for password hashing using: secrets.SystemRandom().getrandbits(128)
174 app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", '146585145368132386173505678016728509634')
175
176 # have session and remember cookie be samesite (flask/flask_login)
177 app.config["REMEMBER_COOKIE_SAMESITE"] = "strict"
178 app.config["SESSION_COOKIE_SAMESITE"] = "strict"
179
180 # Use an in-memory db
181 app.config |= {
182 "SQLALCHEMY_ENGINES": {
183 "default": {"url": "sqlite:///:memory:", "pool_pre_ping": True},
184 },
185 }
186
187 # Create database connection object
188 db = SQLAlchemy(app)
189
190 # Define models
191 class Model(DeclarativeBase):
192 pass
193
194 # NOTE: call this PRIOR to declaring models
195 sqla.FsModels.set_db_info(base_model=Model)
196
197 class Role(Model, sqla.FsRoleMixin):
198 __tablename__ = "role"
199 pass
200
201 class User(Model, sqla.FsUserMixin):
202 __tablename__ = "user"
203 pass
204
205 # Setup Flask-Security
206 user_datastore = FSQLALiteUserDatastore(db, User, Role)
207 security = Security(app, user_datastore)
208
209 # Views
210 @app.route("/")
211 @auth_required()
212 def home():
213 return render_template_string("Hello {{ current_user.email }}")
214
215 # one time setup
216 with app.app_context():
217 # Create User to test with
218 Model.metadata.create_all(db.engine)
219 if not security.datastore.find_user(email="[email protected]"):
220 security.datastore.create_user(email="[email protected]", password=hash_password("password"))
221 db.session.commit()
222
223 if __name__ == '__main__':
224 app.run()
225
226 You can run this either with::
227
228 flask run
229
230 or::
231
232 python app.py
233
234 .. _basic-sqlalchemy-application-with-session:
235
236 Basic SQLAlchemy Application with session
237 -----------------------------------------
238
239 SQLAlchemy Install requirements
240 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
241
242 This requires python >= 3.10::
243
244 $ python3 -m venv pymyenv
245 $ . pymyenv/bin/activate
246 $ pip install flask-security[common] sqlalchemy
247
248 SQLAlchemy Application (w/o Flask-SQLAlchemy)
249 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
250
251 The following code sample illustrates how to get started as quickly as
252 possible using `SQLAlchemy in a declarative way
253 <https://flask.palletsprojects.com/en/2.0.x/patterns/sqlalchemy/#declarative>`_:
254
255 This example shows how to split your application into 3 files: app.py, database.py
256 and models.py.
257
258 - app.py
259 .. code-block:: python
260
261 import os
262
263 from flask import Flask, render_template_string
264 from flask_security import Security, current_user, auth_required, hash_password, \
265 SQLAlchemySessionUserDatastore, permissions_accepted
266 from database import db_session, init_db
267 from models import User, Role
268
269 # Create app
270 app = Flask(__name__)
271 app.config['DEBUG'] = True
272
273 # Generate a nice key using secrets.token_urlsafe()
274 app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw')
275 # Generate a good salt for password hashing using: secrets.SystemRandom().getrandbits(128)
276 app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", '146585145368132386173505678016728509634')
277 # Don't worry if email has findable domain
278 app.config["SECURITY_EMAIL_VALIDATOR_ARGS"] = {"check_deliverability": False}
279
280 # manage sessions per request - make sure connections are closed and returned
281 app.teardown_appcontext(lambda exc: db_session.close())
282
283 # Setup Flask-Security
284 user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role)
285 security = Security(app, user_datastore)
286
287 # Views
288 @app.route("/")
289 @auth_required()
290 def home():
291 return render_template_string('Hello {{current_user.email}}!')
292
293 @app.route("/user")
294 @auth_required()
295 @permissions_accepted("user-read")
296 def user_home():
297 return render_template_string("Hello {{ current_user.email }} you are a user!")
298
299 # one time setup
300 with app.app_context():
301 init_db()
302 # Create a user and role to test with
303 security.datastore.find_or_create_role(
304 name="user", permissions={"user-read", "user-write"}
305 )
306 db_session.commit()
307 if not security.datastore.find_user(email="[email protected]"):
308 security.datastore.create_user(email="[email protected]",
309 password=hash_password("password"), roles=["user"])
310 db_session.commit()
311
312 if __name__ == '__main__':
313 # run application (can also use flask run)
314 app.run()
315
316 - database.py
317 .. code-block:: python
318
319 from sqlalchemy import create_engine
320 from sqlalchemy.orm import scoped_session, sessionmaker
321 from sqlalchemy.ext.declarative import declarative_base
322 from flask_security.models import sqla
323
324 engine = create_engine('sqlite:////tmp/test.db')
325 db_session = scoped_session(sessionmaker(autocommit=False,
326 autoflush=False,
327 bind=engine))
328 Base = declarative_base()
329 # This creates the RolesUser table and is where
330 # you would pass in non-standard tables names.
331 sqla.FsModels.set_db_info(base_model=Base)
332
333
334 def init_db():
335 # import all modules here that might define models so that
336 # they will be registered properly on the metadata. Otherwise
337 # you will have to import them first before calling init_db()
338 import models
339 Base.metadata.create_all(bind=engine)
340
341 - models.py
342 .. code-block:: python
343
344 from database import Base
345 from flask_security.models import sqla as sqla
346
347 class Role(Base, sqla.FsRoleMixin):
348 __tablename__ = 'role'
349
350 class User(Base, sqla.FsUserMixin):
351 __tablename__ = 'user'
352
353 You can run this either with::
354
355 flask run
356
357 or::
358
359 python app.py
360
361 .. _basic-mongoengine-application:
362
363 Basic MongoEngine Application
364 -----------------------------
365
366 MongoEngine Install requirements
367 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
368
369 ::
370
371 $ python3 -m venv pymyenv
372 $ . pymyenv/bin/activate
373 $ pip install flask-security[common] mongoengine
374
375 MongoEngine Application
376 ~~~~~~~~~~~~~~~~~~~~~~~
377
378 The following code sample illustrates how to get started as quickly as
379 possible using MongoEngine (of course you have to install and start up a
380 local MongoDB instance).
381
382 .. code-block:: python
383
384 import os
385
386 from flask import Flask, render_template_string
387 from mongoengine import Document, connect
388 from mongoengine.fields import (
389 BinaryField,
390 BooleanField,
391 DateTimeField,
392 IntField,
393 ListField,
394 ReferenceField,
395 StringField,
396 )
397 from flask_security import Security, MongoEngineUserDatastore, \
398 UserMixin, RoleMixin, auth_required, hash_password, permissions_accepted
399
400 # Create app
401 app = Flask(__name__)
402 app.config['DEBUG'] = True
403
404 # Generate a nice key using secrets.token_urlsafe()
405 app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw')
406 # Generate a good salt for password hashing using: secrets.SystemRandom().getrandbits(128)
407 app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", '146585145368132386173505678016728509634')
408 # Don't worry if email has findable domain
409 app.config["SECURITY_EMAIL_VALIDATOR_ARGS"] = {"check_deliverability": False}
410
411 # Create database connection object
412 db_name = "mydatabase"
413 db = connect(alias=db_name, db=db_name, host="mongodb://localhost", port=27017)
414
415 class Role(Document, RoleMixin):
416 name = StringField(max_length=80, unique=True)
417 description = StringField(max_length=255)
418 permissions = ListField(required=False)
419 meta = {"db_alias": db_name}
420
421 class User(Document, UserMixin):
422 email = StringField(max_length=255, unique=True)
423 password = StringField(max_length=255)
424 active = BooleanField(default=True)
425 fs_uniquifier = StringField(max_length=64, unique=True)
426 confirmed_at = DateTimeField()
427 roles = ListField(ReferenceField(Role), default=[])
428 meta = {"db_alias": db_name}
429
430 # Setup Flask-Security
431 user_datastore = MongoEngineUserDatastore(db, User, Role)
432 security = Security(app, user_datastore)
433
434 # Views
435 @app.route("/")
436 @auth_required()
437 def home():
438 return render_template_string("Hello {{ current_user.email }}")
439
440 @app.route("/user")
441 @auth_required()
442 @permissions_accepted("user-read")
443 def user_home():
444 return render_template_string("Hello {{ current_user.email }} you are a user!")
445
446 # one time setup
447 with app.app_context():
448 # Create a user and role to test with
449 security.datastore.find_or_create_role(
450 name="user", permissions={"user-read", "user-write"}
451 )
452 if not security.datastore.find_user(email="[email protected]"):
453 security.datastore.create_user(email="[email protected]",
454 password=hash_password("password"), roles=["user"])
455
456 if __name__ == '__main__':
457 # run application (can also use flask run)
458 app.run()
459
460
461 .. _basic-peewee-application:
462
463 Basic Peewee Application
464 ------------------------
465
466 Peewee Install requirements
467 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
468
469 ::
470
471 $ python3 -m venv pymyenv
472 $ . pymyenv/bin/activate
473 $ pip install flask-security[common] peewee
474
475 Peewee Application
476 ~~~~~~~~~~~~~~~~~~
477
478 The following code sample illustrates how to get started as quickly as
479 possible using Peewee.
480
481 .. code-block:: python
482
483 import os
484
485 from flask import Flask, render_template_string
486 from playhouse.flask_utils import FlaskDB
487 from peewee import *
488 from flask_security import Security, PeeweeUserDatastore, \
489 UserMixin, RoleMixin, auth_required, hash_password
490
491 # Create app
492 app = Flask(__name__)
493 app.config['DEBUG'] = True
494
495 # Generate a nice key using secrets.token_urlsafe()
496 app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw')
497 # Generate a good salt for password hashing using: secrets.SystemRandom().getrandbits(128)
498 app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", '146585145368132386173505678016728509634')
499
500 app.config['DATABASE'] = {
501 'name': 'example.db',
502 'engine': 'peewee.SqliteDatabase',
503 }
504
505 # Create database connection object
506 db = FlaskDB(app)
507
508 class Role(RoleMixin, db.Model):
509 name = CharField(unique=True)
510 description = TextField(null=True)
511 permissions = TextField(null=True)
512
513 # N.B. order is important since db.Model also contains a get_id() -
514 # we need the one from UserMixin.
515 class User(UserMixin, db.Model):
516 email = TextField()
517 password = TextField()
518 active = BooleanField(default=True)
519 fs_uniquifier = TextField(null=False)
520 confirmed_at = DateTimeField(null=True)
521
522 class UserRoles(db.Model):
523 # Because peewee does not come with built-in many-to-many
524 # relationships, we need this intermediary class to link
525 # user to roles.
526 user = ForeignKeyField(User, related_name='roles')
527 role = ForeignKeyField(Role, related_name='users')
528 name = property(lambda self: self.role.name)
529 description = property(lambda self: self.role.description)
530
531 def get_permissions(self):
532 return self.role.get_permissions()
533
534 # Setup Flask-Security
535 user_datastore = PeeweeUserDatastore(db, User, Role, UserRoles)
536 security = Security(app, user_datastore)
537
538 # Views
539 @app.route('/')
540 @auth_required()
541 def home():
542 return render_template_string("Hello {{ current_user.email }}")
543
544 # one time setup
545 with app.app_context():
546 # Create a user to test with
547 for Model in (Role, User, UserRoles):
548 Model.drop_table(fail_silently=True)
549 Model.create_table(fail_silently=True)
550 if not security.datastore.find_user(email="[email protected]"):
551 security.datastore.create_user(email="[email protected]", password=hash_password("password"))
552
553 if __name__ == '__main__':
554 app.run()
555
556
557 .. _mail-configuration:
558
559 Mail Configuration
560 ------------------
561
562 Flask-Security integrates with an outgoing mail service via the ``mail_util_cls`` which
563 is part of initial configuration. The default class :class:`flask_security.MailUtil` utilizes the
564 `Flask-Mail <https://pypi.org/project/flask-mail/>`_ package. Be sure to add flask_mail to
565 your requirements.txt. The Django inspired package `Flask-Mailman <https://pypi.org/project/Flask-Mailman/>`_
566 is also supported.
567
568 The following code illustrates a basic setup, which could be added to
569 the basic application code in the previous section::
570
571 # At top of file
572 from flask_mail import Mail
573
574 # After 'Create app'
575 app.config['MAIL_SERVER'] = 'smtp.example.com'
576 app.config['MAIL_PORT'] = 587
577 app.config['MAIL_USE_TLS'] = True
578 app.config['MAIL_USERNAME'] = 'username'
579 app.config['MAIL_PASSWORD'] = 'password'
580 mail = Mail(app)
581
582 To learn more about the various Flask-Mail settings to configure it to
583 work with your particular email server configuration, please see the
584 `Flask-Mail documentation <https://flask-mail.readthedocs.io/en/latest/>`_.
585
586 .. _proxy-configuration:
587
588 Proxy Configuration
589 -------------------
590
591 The user tracking features need an additional configuration
592 in HTTP proxy environment. The following code illustrates a setup
593 with a single HTTP proxy in front of the web application::
594
595 # At top of file
596 from werkzeug.middleware.proxy_fix import ProxyFix
597
598 # After 'Create app'
599 app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
600
601 To learn more about the ``ProxyFix`` middleware, please see the
602 `Werkzeug documentation <https://werkzeug.palletsprojects.com/en/2.0.x/middleware/proxy_fix/#module-werkzeug.middleware.proxy_fix>`_.
603
604 .. _unit-testing:
605
606 Unit Testing Your Application
607 -----------------------------
608
609 As soon as you add any of the Flask-Security decorators to your API endpoints, it can
610 be frustrating to unit test your basic routing (and roles and permissions). Without getting
611 into the argument of the difference between unit tests and integration tests - you can approach testing
612 in 2 ways:
613
614 * 'Pure' unit test - mocking out all lower level objects (such as the data store)
615 * Complete app with in-memory/temporary DB (with little or no mocking).
616
617 Look in the `Flask-Security repo`_ *examples* directory for actual code that implements the
618 second approach which is much simpler and with an in-memory DB fairly fast.
619
620 You also might want to set the following configurations in your conftest.py:
621
622 .. code-block:: python
623
624 app.config["WTF_CSRF_ENABLED"] = False
625 # Our test emails/domain isn't necessarily valid
626 app.config["SECURITY_EMAIL_VALIDATOR_ARGS"] = {"check_deliverability": False}
627 # Make this plaintext for most tests - reduces unit test time by 50%
628 app.config["SECURITY_PASSWORD_HASH"] = "plaintext"
629
630 .. _Flask-Security repo: https://github.com/pallets-eco/flask-security