| 1 |
""" |
| 2 |
Copyright 2019-2022 by J. Christopher Wagner (jwag). All rights reserved. |
| 3 |
:license: MIT, see LICENSE for more details. |
| 4 |
|
| 5 |
Very simple application. |
| 6 |
Uses built-in models. |
| 7 |
Shows using roles and permissions to protect endpoints. |
| 8 |
|
| 9 |
You can run the flask cli against this as well (once you have first created a |
| 10 |
real DB) (from top level directory): |
| 11 |
PYTHONPATH=. SQLALCHEMY_DATABASE_URI="sqlite:////var/tmp/test.db" \ |
| 12 |
FLASK_APP=examples/fsqlalchemy1/app.py \ |
| 13 |
flask users create -a [email protected] |
| 14 |
""" |
| 15 |
|
| 16 |
import os |
| 17 |
import typing as t |
| 18 |
|
| 19 |
from flask import Flask, abort, current_app, render_template_string |
| 20 |
from flask_sqlalchemy import SQLAlchemy |
| 21 |
from flask_babel import Babel |
| 22 |
from sqlalchemy import Column, ForeignKey, Integer, Text, UnicodeText |
| 23 |
from flask_security import ( |
| 24 |
Security, |
| 25 |
SQLAlchemyUserDatastore, |
| 26 |
auth_required, |
| 27 |
current_user, |
| 28 |
hash_password, |
| 29 |
permissions_accepted, |
| 30 |
permissions_required, |
| 31 |
roles_accepted, |
| 32 |
) |
| 33 |
from flask_security.models import fsqla_v2 as fsqla |
| 34 |
|
| 35 |
# Create database connection object |
| 36 |
db = SQLAlchemy() |
| 37 |
|
| 38 |
# Define models - for this example - we change the default table names |
| 39 |
fsqla.FsModels.set_db_info(db, user_table_name="myuser", role_table_name="myrole") |
| 40 |
|
| 41 |
|
| 42 |
class Role(db.Model, fsqla.FsRoleMixin): |
| 43 |
__tablename__ = "myrole" |
| 44 |
|
| 45 |
|
| 46 |
class User(db.Model, fsqla.FsUserMixin): |
| 47 |
__tablename__ = "myuser" |
| 48 |
blogs: db.Mapped[t.List["Blog"]] = db.relationship( |
| 49 |
"Blog", back_populates="user", lazy="dynamic", cascade_backrefs=False |
| 50 |
) |
| 51 |
|
| 52 |
|
| 53 |
class Blog(db.Model): |
| 54 |
id = Column(Integer, primary_key=True) |
| 55 |
user_id = Column(Integer, ForeignKey("myuser.id"), nullable=False) |
| 56 |
user: db.Mapped["User"] = db.relationship( |
| 57 |
"User", back_populates="blogs", cascade_backrefs=False |
| 58 |
) |
| 59 |
title = Column(Text) |
| 60 |
text = Column(UnicodeText) |
| 61 |
|
| 62 |
|
| 63 |
# Create app |
| 64 |
def create_app(): |
| 65 |
app = Flask(__name__) |
| 66 |
app.config["DEBUG"] = True |
| 67 |
# generated using: secrets.token_urlsafe() |
| 68 |
app.config["SECRET_KEY"] = "pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw" |
| 69 |
app.config["SECURITY_PASSWORD_HASH"] = "argon2" |
| 70 |
# argon2 uses double hashing by default - so provide key. |
| 71 |
# For python3: secrets.SystemRandom().getrandbits(128) |
| 72 |
app.config["SECURITY_PASSWORD_SALT"] = "146585145368132386173505678016728509634" |
| 73 |
|
| 74 |
# Take password complexity seriously |
| 75 |
app.config["SECURITY_PASSWORD_COMPLEXITY_CHECKER"] = "zxcvbn" |
| 76 |
|
| 77 |
# Allow registration of new users without confirmation |
| 78 |
app.config["SECURITY_REGISTERABLE"] = True |
| 79 |
|
| 80 |
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( |
| 81 |
"SQLALCHEMY_DATABASE_URI", "sqlite://" |
| 82 |
) |
| 83 |
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False |
| 84 |
|
| 85 |
# As of Flask-SQLAlchemy 2.4.0 it is easy to pass in options directly to the |
| 86 |
# underlying engine. This option makes sure that DB connections from the pool |
| 87 |
# are still valid. Important for entire application since many DBaaS options |
| 88 |
# automatically close idle connections. |
| 89 |
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"pool_pre_ping": True} |
| 90 |
|
| 91 |
# Setup Flask-Security |
| 92 |
db.init_app(app) |
| 93 |
user_datastore = SQLAlchemyUserDatastore(db, User, Role) |
| 94 |
app.security = Security(app, user_datastore) |
| 95 |
|
| 96 |
# Setup Babel - not strictly necessary but since our virtualenv has Flask-Babel |
| 97 |
# we need to initialize it |
| 98 |
Babel(app) |
| 99 |
|
| 100 |
# Set this so unit tests can mock out. |
| 101 |
app.blog_cls = Blog |
| 102 |
|
| 103 |
# Views |
| 104 |
# Note that we always add @auth_required so that if a client isn't logged in |
| 105 |
# we will get a proper '401' and redirected to login page. |
| 106 |
@app.route("/") |
| 107 |
@auth_required() |
| 108 |
def home(): |
| 109 |
return render_template_string("Hello {{ current_user.email }}") |
| 110 |
|
| 111 |
@app.route("/admin") |
| 112 |
@auth_required() |
| 113 |
@permissions_accepted("admin-read", "admin-write") |
| 114 |
def admin(): |
| 115 |
return render_template_string( |
| 116 |
"Hello on admin page. Current user {} password is {}".format( |
| 117 |
current_user.email, current_user.password |
| 118 |
) |
| 119 |
) |
| 120 |
|
| 121 |
@app.route("/ops") |
| 122 |
@auth_required() |
| 123 |
@roles_accepted("monitor") |
| 124 |
def monitor(): |
| 125 |
# Example of using just a role. Note that 'admin' can't access this |
| 126 |
# since it doesn't have the 'monitor' role - even though it has |
| 127 |
# all the permissions that the 'monitor' role has. |
| 128 |
return render_template_string("Hello OPS") |
| 129 |
|
| 130 |
@app.route("/blog/<bid>", methods=["GET", "POST"]) |
| 131 |
@auth_required() |
| 132 |
@permissions_required("user-write") |
| 133 |
def update_blog(bid): |
| 134 |
# Yes caller has write permission - but do they OWN this blog? |
| 135 |
blog = current_app.blog_cls.query.filter_by(id=bid).first() |
| 136 |
if not blog: |
| 137 |
abort(404) |
| 138 |
if current_user != blog.user: |
| 139 |
abort(403) |
| 140 |
return render_template_string("Yes, {{ current_user.email }} can update blog") |
| 141 |
|
| 142 |
@app.route("/myblogs", methods=["GET"]) |
| 143 |
@auth_required() |
| 144 |
@permissions_accepted("user-read") |
| 145 |
def list_my_blogs(): |
| 146 |
blogs = current_user.blogs |
| 147 |
blist = "" |
| 148 |
cnt = 0 |
| 149 |
for blog in blogs: |
| 150 |
blist += f" {blog.title}" |
| 151 |
cnt += 1 |
| 152 |
if not blogs: |
| 153 |
abort(404) |
| 154 |
return render_template_string(f"Found {cnt} of yours with titles {blist}") |
| 155 |
|
| 156 |
return app |
| 157 |
|
| 158 |
|
| 159 |
# Create users and roles (and first blog!) |
| 160 |
def create_users(): |
| 161 |
if current_app.testing: |
| 162 |
return |
| 163 |
with current_app.app_context(): |
| 164 |
security = current_app.security |
| 165 |
security.datastore.db.create_all() |
| 166 |
security.datastore.find_or_create_role( |
| 167 |
name="admin", |
| 168 |
permissions={"admin-read", "admin-write", "user-read", "user-write"}, |
| 169 |
) |
| 170 |
security.datastore.find_or_create_role( |
| 171 |
name="monitor", permissions={"admin-read", "user-read"} |
| 172 |
) |
| 173 |
security.datastore.find_or_create_role( |
| 174 |
name="user", permissions={"user-read", "user-write"} |
| 175 |
) |
| 176 |
security.datastore.find_or_create_role(name="reader", permissions={"user-read"}) |
| 177 |
|
| 178 |
if not security.datastore.find_user(email="[email protected]"): |
| 179 |
security.datastore.create_user( |
| 180 |
email="[email protected]", |
| 181 |
password=hash_password("password"), |
| 182 |
roles=["admin"], |
| 183 |
) |
| 184 |
if not security.datastore.find_user(email="[email protected]"): |
| 185 |
security.datastore.create_user( |
| 186 |
email="[email protected]", |
| 187 |
password=hash_password("password"), |
| 188 |
roles=["monitor"], |
| 189 |
) |
| 190 |
real_user = security.datastore.find_user(email="[email protected]") |
| 191 |
if not real_user: |
| 192 |
real_user = security.datastore.create_user( |
| 193 |
email="[email protected]", password=hash_password("password"), roles=["user"] |
| 194 |
) |
| 195 |
if not security.datastore.find_user(email="[email protected]"): |
| 196 |
security.datastore.create_user( |
| 197 |
email="[email protected]", |
| 198 |
password=hash_password("password"), |
| 199 |
roles=["reader"], |
| 200 |
) |
| 201 |
|
| 202 |
# create initial blog |
| 203 |
blog = current_app.blog_cls( |
| 204 |
title="First Blog", text="my first blog is short", user=real_user |
| 205 |
) |
| 206 |
security.datastore.db.session.add(blog) |
| 207 |
security.datastore.db.session.commit() |
| 208 |
print(f"First blog id {blog.id}") |
| 209 |
|
| 210 |
|
| 211 |
if __name__ == "__main__": |
| 212 |
myapp = create_app() |
| 213 |
with myapp.app_context(): |
| 214 |
create_users() |
| 215 |
myapp.run(port=5003) |