-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 9423154
Showing
14 changed files
with
2,878 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
|
||
.DS_Store |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,178 @@ | ||
|
||
Apache License | ||
Version 2.0, January 2004 | ||
http://www.apache.org/licenses/ | ||
|
||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION | ||
|
||
1. Definitions. | ||
|
||
"License" shall mean the terms and conditions for use, reproduction, | ||
and distribution as defined by Sections 1 through 9 of this document. | ||
|
||
"Licensor" shall mean the copyright owner or entity authorized by | ||
the copyright owner that is granting the License. | ||
|
||
"Legal Entity" shall mean the union of the acting entity and all | ||
other entities that control, are controlled by, or are under common | ||
control with that entity. For the purposes of this definition, | ||
"control" means (i) the power, direct or indirect, to cause the | ||
direction or management of such entity, whether by contract or | ||
otherwise, or (ii) ownership of fifty percent (50%) or more of the | ||
outstanding shares, or (iii) beneficial ownership of such entity. | ||
|
||
"You" (or "Your") shall mean an individual or Legal Entity | ||
exercising permissions granted by this License. | ||
|
||
"Source" form shall mean the preferred form for making modifications, | ||
including but not limited to software source code, documentation | ||
source, and configuration files. | ||
|
||
"Object" form shall mean any form resulting from mechanical | ||
transformation or translation of a Source form, including but | ||
not limited to compiled object code, generated documentation, | ||
and conversions to other media types. | ||
|
||
"Work" shall mean the work of authorship, whether in Source or | ||
Object form, made available under the License, as indicated by a | ||
copyright notice that is included in or attached to the work | ||
(an example is provided in the Appendix below). | ||
|
||
"Derivative Works" shall mean any work, whether in Source or Object | ||
form, that is based on (or derived from) the Work and for which the | ||
editorial revisions, annotations, elaborations, or other modifications | ||
represent, as a whole, an original work of authorship. For the purposes | ||
of this License, Derivative Works shall not include works that remain | ||
separable from, or merely link (or bind by name) to the interfaces of, | ||
the Work and Derivative Works thereof. | ||
|
||
"Contribution" shall mean any work of authorship, including | ||
the original version of the Work and any modifications or additions | ||
to that Work or Derivative Works thereof, that is intentionally | ||
submitted to Licensor for inclusion in the Work by the copyright owner | ||
or by an individual or Legal Entity authorized to submit on behalf of | ||
the copyright owner. For the purposes of this definition, "submitted" | ||
means any form of electronic, verbal, or written communication sent | ||
to the Licensor or its representatives, including but not limited to | ||
communication on electronic mailing lists, source code control systems, | ||
and issue tracking systems that are managed by, or on behalf of, the | ||
Licensor for the purpose of discussing and improving the Work, but | ||
excluding communication that is conspicuously marked or otherwise | ||
designated in writing by the copyright owner as "Not a Contribution." | ||
|
||
"Contributor" shall mean Licensor and any individual or Legal Entity | ||
on behalf of whom a Contribution has been received by Licensor and | ||
subsequently incorporated within the Work. | ||
|
||
2. Grant of Copyright License. Subject to the terms and conditions of | ||
this License, each Contributor hereby grants to You a perpetual, | ||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable | ||
copyright license to reproduce, prepare Derivative Works of, | ||
publicly display, publicly perform, sublicense, and distribute the | ||
Work and such Derivative Works in Source or Object form. | ||
|
||
3. Grant of Patent License. Subject to the terms and conditions of | ||
this License, each Contributor hereby grants to You a perpetual, | ||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable | ||
(except as stated in this section) patent license to make, have made, | ||
use, offer to sell, sell, import, and otherwise transfer the Work, | ||
where such license applies only to those patent claims licensable | ||
by such Contributor that are necessarily infringed by their | ||
Contribution(s) alone or by combination of their Contribution(s) | ||
with the Work to which such Contribution(s) was submitted. If You | ||
institute patent litigation against any entity (including a | ||
cross-claim or counterclaim in a lawsuit) alleging that the Work | ||
or a Contribution incorporated within the Work constitutes direct | ||
or contributory patent infringement, then any patent licenses | ||
granted to You under this License for that Work shall terminate | ||
as of the date such litigation is filed. | ||
|
||
4. Redistribution. You may reproduce and distribute copies of the | ||
Work or Derivative Works thereof in any medium, with or without | ||
modifications, and in Source or Object form, provided that You | ||
meet the following conditions: | ||
|
||
(a) You must give any other recipients of the Work or | ||
Derivative Works a copy of this License; and | ||
|
||
(b) You must cause any modified files to carry prominent notices | ||
stating that You changed the files; and | ||
|
||
(c) You must retain, in the Source form of any Derivative Works | ||
that You distribute, all copyright, patent, trademark, and | ||
attribution notices from the Source form of the Work, | ||
excluding those notices that do not pertain to any part of | ||
the Derivative Works; and | ||
|
||
(d) If the Work includes a "NOTICE" text file as part of its | ||
distribution, then any Derivative Works that You distribute must | ||
include a readable copy of the attribution notices contained | ||
within such NOTICE file, excluding those notices that do not | ||
pertain to any part of the Derivative Works, in at least one | ||
of the following places: within a NOTICE text file distributed | ||
as part of the Derivative Works; within the Source form or | ||
documentation, if provided along with the Derivative Works; or, | ||
within a display generated by the Derivative Works, if and | ||
wherever such third-party notices normally appear. The contents | ||
of the NOTICE file are for informational purposes only and | ||
do not modify the License. You may add Your own attribution | ||
notices within Derivative Works that You distribute, alongside | ||
or as an addendum to the NOTICE text from the Work, provided | ||
that such additional attribution notices cannot be construed | ||
as modifying the License. | ||
|
||
You may add Your own copyright statement to Your modifications and | ||
may provide additional or different license terms and conditions | ||
for use, reproduction, or distribution of Your modifications, or | ||
for any such Derivative Works as a whole, provided Your use, | ||
reproduction, and distribution of the Work otherwise complies with | ||
the conditions stated in this License. | ||
|
||
5. Submission of Contributions. Unless You explicitly state otherwise, | ||
any Contribution intentionally submitted for inclusion in the Work | ||
by You to the Licensor shall be under the terms and conditions of | ||
this License, without any additional terms or conditions. | ||
Notwithstanding the above, nothing herein shall supersede or modify | ||
the terms of any separate license agreement you may have executed | ||
with Licensor regarding such Contributions. | ||
|
||
6. Trademarks. This License does not grant permission to use the trade | ||
names, trademarks, service marks, or product names of the Licensor, | ||
except as required for reasonable and customary use in describing the | ||
origin of the Work and reproducing the content of the NOTICE file. | ||
|
||
7. Disclaimer of Warranty. Unless required by applicable law or | ||
agreed to in writing, Licensor provides the Work (and each | ||
Contributor provides its Contributions) on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | ||
implied, including, without limitation, any warranties or conditions | ||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A | ||
PARTICULAR PURPOSE. You are solely responsible for determining the | ||
appropriateness of using or redistributing the Work and assume any | ||
risks associated with Your exercise of permissions under this License. | ||
|
||
8. Limitation of Liability. In no event and under no legal theory, | ||
whether in tort (including negligence), contract, or otherwise, | ||
unless required by applicable law (such as deliberate and grossly | ||
negligent acts) or agreed to in writing, shall any Contributor be | ||
liable to You for damages, including any direct, indirect, special, | ||
incidental, or consequential damages of any character arising as a | ||
result of this License or out of the use or inability to use the | ||
Work (including but not limited to damages for loss of goodwill, | ||
work stoppage, computer failure or malfunction, or any and all | ||
other commercial damages or losses), even if such Contributor | ||
has been advised of the possibility of such damages. | ||
|
||
9. Accepting Warranty or Additional Liability. While redistributing | ||
the Work or Derivative Works thereof, You may choose to offer, | ||
and charge a fee for, acceptance of support, warranty, indemnity, | ||
or other liability obligations and/or rights consistent with this | ||
License. However, in accepting such obligations, You may act only | ||
on Your own behalf and on Your sole responsibility, not on behalf | ||
of any other Contributor, and only if You agree to indemnify, | ||
defend, and hold each Contributor harmless for any liability | ||
incurred by, or claims asserted against, such Contributor by reason | ||
of your accepting any such warranty or additional liability. | ||
|
||
END OF TERMS AND CONDITIONS | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
# flask-fga - An example OpenFGA project using Python-Flask | ||
|
||
This project was created as a learning exercise to gain familiarity with [OpenFGA](https://openfga.dev). It provides a basic multi-user environment where users can create folders and text files, create and add users to groups, and share files and folders with other users and groups. This is not a production ready codebase and is intended as a learning aid and starting point to improve and build on. It provides an example implementation of OpenFGA with Python-Flask and SQLAlchemy. | ||
|
||
## Components | ||
|
||
### Flask | ||
Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. | ||
|
||
### Python-dotenv | ||
Python-dotenv reads key-value pairs from a .env file and can set them as environment variables. It is used in this project to store sensitive variables such as the OpenFGA connection details and store id as well as the Auth0 credentials. | ||
|
||
### authlib | ||
Python library in building OAuth and OpenID Connect servers. Used in this example to utilize Auth0 services but easily adaptable for other OAuth or OpenID Connect services. | ||
|
||
### requests | ||
Requests is a simple, yet elegant, HTTP library for Python. Required along with autlib to interact with the Auth0 authentication service. | ||
|
||
### SQLAlchemy | ||
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language. | ||
|
||
### Flask-SQLAlchemy | ||
Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. | ||
|
||
### openfga_sdk | ||
OpenFGA is an open source Fine-Grained Authorization solution inspired by Google's Zanzibar paper. | ||
|
||
## Authentication | ||
|
||
Auth0 is used for authentication for simplicity but can easily be swapped out for another authentication solution. Auth0 is initialized in app/__init__.py and utilized in app/routes.py in the route handlers for `/login`, `/logout`, and `/callback`. The `loadSession()` function uses the information returned during authentication to set session variables which are used throughout the rest of the app and the `registerUser()` function is used to create a new user in the database after they are first authenticated. | ||
|
||
## Database | ||
|
||
This project uses the Flask SQLAlchemy library to simplify interactions with the application database and allow flexibility in the database solution used. This project has been tested with sqlite but should be compatible with MySQL or PostgreSQL though minor tweaks to app/models.py could be required if errors are encountered. | ||
|
||
## OpenFGA | ||
|
||
This project was created as an example of the capabilities of OpenFGA you can learn more about OpenFGA here. | ||
|
||
### Synchronous Mode | ||
|
||
Due to limitations using SQLAlchemy in asynchronous functions this app uses OpenFGA in synchronous mode which varies from the examples shown in the official OpenFGA documentation at openfga.dev. You can learn more about using openfga_sdk in synchronous mode here. | ||
|
||
# Installation and Setup | ||
|
||
## Install OpenFGA | ||
If you are using an existing OpenFGA server instance or SaaS service you can skip this step. Using Docker locally is recommended as the simplest self-hosted option to get started with this project. Follow the instructions found in [this guide](https://openfga.dev/docs/getting-started/setup-openfga/docker) to run OpenFGA in Docker. | ||
|
||
### Note | ||
Because the OpenFGA Playground uses the same default port as Python-Flask you will need to modify the docker run command provided in the documentation | ||
|
||
Instead of: | ||
`docker run -p 8080:8080 -p 8081:8081 -p 3000:3000 openfga/openfga run` | ||
|
||
You will use: | ||
`docker run -p 8080:8080 -p 8081:8081 -p 3000:3001 openfga/openfga run` | ||
|
||
This will expose the playground service on port 3001 instead of 3000 to prevent a conflict. | ||
|
||
## Set up your OpenFGA Store and Model | ||
Before you can use this app you will need to create a store in your OpenFGA instance and create the model used by this app. | ||
|
||
### Using the OpenFGA Playground | ||
By default your OpenFGA instance will allow you to manage your stores and models through a browser using the OpenFGA Playground UI. The playground can be accessed (when running OpenFGA locally) at `http://localhost:3001/playground`. In the playground, create a new store. Then copy the content of `model.fga` into the model view and save it. | ||
|
||
Once you have saved your model you can copy the store id and model id that were created for it. These can be found in the menu in the top right corner of the page. You will need these when configuring the app. | ||
|
||
### Using the OpenFGA CLI | ||
You can also use the OpenFGA CLI client to connect with your OpenFGA instance and create your store and model. You can learn more about the OpenFGA CLI [here](https://openfga.dev/docs/getting-started/cli). If you are running OpenFGA locally it's default configuration will connect with your local instance. If you are using a remote FGA service you will need to configure the client with your credentials and connection details before you can proceed. | ||
|
||
From this project's main directory run | ||
|
||
`fga store create --model model.fga` | ||
|
||
You will receive a response that looks like this: | ||
|
||
``` | ||
{ | ||
"store": { | ||
"created_at":"2024-02-09T23:20:28.637533296Z", | ||
"id":"01HP82R96XEJX1Q9YWA9XRQ4PM", | ||
"name":"docs", | ||
"updated_at":"2024-02-09T23:20:28.637533296Z" | ||
}, | ||
"model": { | ||
"authorization_model_id":"01HP82R97B448K89R45PW7NXD8" | ||
} | ||
} | ||
``` | ||
|
||
The "id" in the first section is your `Store ID` and your `Model ID` is the value in the "model" section. Save these values as you will need them to configure the application. | ||
|
||
## Configure Authentication | ||
This app was built using Auth0 for authentication but uses standard librarires for OAuth so modifying it to use another provider should not be overly complicated. For simplicity this guide will only cover the use of Auth0. | ||
|
||
### Create an Auth0 Account | ||
If you do not have an Auth0 account, create one [here](https://auth0.com/signup). This app can be used with a free plan. | ||
|
||
### Configure an application | ||
Use the interactive selector to create a new Auth0 application. | ||
|
||
#### Application Type | ||
For Application Type select "Single Page Application" | ||
|
||
#### Allowed Callback URLs | ||
Enter `http://localhost:3000/callback` in "Allowed Callback URLs" | ||
|
||
#### Allowed Logout URLs | ||
Enter `http://localhost:3000/` in "Allowed Logout URLs" | ||
|
||
#### Allowed Web Origins | ||
Enter `http://localhost:3000` in "Allowed Web Origins" | ||
|
||
By default your app will have two "Connections" enabled for providing user authentication data. | ||
|
||
- google-oauth2 - This option allows users to log in with Google. There is no need to configure user accounts with this option | ||
|
||
- Username-Password-Authentication - This option allows you to create user accounts in the Auth0 dashboard by specifying usernames and passwords | ||
|
||
### Collect required credentials | ||
From your application's page in the Auth0 Dashboard copy your app's `Domain`, `Client ID`, and `Client Secret` | ||
|
||
## Create a Python Virtual Environment (optional) | ||
While not required it is recommended to use a virtual environment for your Python apps. | ||
|
||
From the main directory for this app run: | ||
|
||
`python3 -m venv venv` | ||
|
||
Then you can begin working in your virutal environment with: | ||
|
||
Linux/Mac: | ||
`source venv/bin/activate` | ||
|
||
Windows: | ||
`venv\Scripts\activate.bat` | ||
|
||
## Install prerequisites | ||
Install the required python prerequisites with: | ||
|
||
`pip3 install -r requirements.txt` | ||
|
||
## Configure your application | ||
Next, make a copy of `env.example` named `.env` in the main directory of the app. Open this file and fill in the needed values. | ||
|
||
``` | ||
AUTH0_CLIENT_ID=<Client ID from your Auth0 App> | ||
AUTH0_CLIENT_SECRET=<Client Secret from your Auth0 App> | ||
AUTH0_DOMAIN=<Domain from your Auth0 App> | ||
APP_SECRET_KEY=<A unique string used as your app's secret key> | ||
SQLALCHEMY_DATABASE_URI=sqlite:///db.sqlite3 | ||
PORT=3000 | ||
FGA_API_URL=http://localhost:8080 | ||
FGA_STORE_ID=<The Store ID you got from OpenFGA> | ||
FGA_MODEL_ID=<The Model ID from the model you created in OpenFGA> | ||
``` | ||
|
||
## Launch the app | ||
Now that everything is set up you can launch your app. From the main directory of the app run `python3 run.py` | ||
|
||
You can now access your app at `http://localhost:3000/` and log in either with a Google account or with a user and password combination you created in the Auth0 dashboard. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
from flask import Flask | ||
from flask_sqlalchemy import SQLAlchemy | ||
from authlib.integrations.flask_client import OAuth | ||
from dotenv import load_dotenv | ||
import os | ||
import asyncio | ||
|
||
|
||
|
||
# Load .env for configuration values | ||
load_dotenv() | ||
|
||
# init sqlalchemy and OAuth libs | ||
db = SQLAlchemy() | ||
oauth = OAuth() | ||
|
||
|
||
def create_app(): | ||
app = Flask(__name__) | ||
|
||
app.config.from_object('config.Config') | ||
db.init_app(app) | ||
|
||
oauth.init_app(app) | ||
|
||
# Configure and initialize the Auth0 Client | ||
oauth.register( | ||
"auth0", | ||
client_id=os.getenv("AUTH0_CLIENT_ID"), | ||
client_secret=os.getenv("AUTH0_CLIENT_SECRET"), | ||
client_kwargs={ | ||
"scope":"openid profile email", | ||
}, | ||
server_metadata_url=f'https://{os.getenv("AUTH0_DOMAIN")}/.well-known/openid-configuration' | ||
) | ||
|
||
|
||
# Register the blueprint. This app is configured to use blueprints but only includes a single blueprint | ||
from .routes import main as main_blueprint | ||
app.register_blueprint(main_blueprint) | ||
|
||
# Create our database schema if it doesn't exist | ||
with app.app_context(): | ||
db.create_all() | ||
|
||
|
||
|
||
return app | ||
|
||
__all__ = ['oauth'] |
Oops, something went wrong.