diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9bea433 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e454a52 --- /dev/null +++ b/LICENSE @@ -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 + diff --git a/README.md b/README.md new file mode 100644 index 0000000..d66afee --- /dev/null +++ b/README.md @@ -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= +AUTH0_CLIENT_SECRET= +AUTH0_DOMAIN= +APP_SECRET_KEY= +SQLALCHEMY_DATABASE_URI=sqlite:///db.sqlite3 +PORT=3000 +FGA_API_URL=http://localhost:8080 +FGA_STORE_ID= +FGA_MODEL_ID= +``` + +## 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. \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..f912f24 --- /dev/null +++ b/app/__init__.py @@ -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'] \ No newline at end of file diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..4ee1047 --- /dev/null +++ b/app/models.py @@ -0,0 +1,43 @@ +from . import db +import datetime + +# The classes in this file represent our database table and schemas for SQLAlchemy + +class User(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + uuid = db.Column(db.Uuid, unique=True, nullable=False) + email = db.Column(db.String(120), unique=True, nullable=False) + name = db.Column(db.String(80), nullable=False) + image = db.Column(db.String(255)) + created = db.Column(db.DateTime, default=datetime.datetime.utcnow) + +class Group(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String(255)) + uuid = db.Column(db.Uuid, unique=True, nullable=False) + creator = db.Column(db.Integer) + +class UserGroup(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + user_id = db.Column(db.Integer, nullable=False) + group_id = db.Column(db.Integer, nullable=False) + +class File(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + uuid = db.Column(db.Uuid, unique=True, nullable=False) + folder = db.Column(db.Uuid, nullable=False) + name = db.Column(db.String(128), nullable=True) + text_content = db.Column(db.Text, nullable=True) + creator = db.Column(db.Integer) + created = db.Column(db.DateTime, default=datetime.datetime.utcnow) + updated = db.Column(db.DateTime, default=datetime.datetime.utcnow) + +class Folder(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + uuid = db.Column(db.Uuid, unique=True, nullable=False) + creator = db.Column(db.Integer) + name = db.Column(db.String(128)) + default_folder = db.Column(db.Boolean, default=False) + parent = db.Column(db.Uuid, nullable=True) + created = db.Column(db.DateTime, default=datetime.datetime.utcnow) + updated = db.Column(db.DateTime, default=datetime.datetime.utcnow) diff --git a/app/routes.py b/app/routes.py new file mode 100644 index 0000000..41011dd --- /dev/null +++ b/app/routes.py @@ -0,0 +1,1147 @@ +from flask import Blueprint, render_template, session, redirect, url_for, request, jsonify +from urllib.parse import quote_plus, urlencode +from os import environ as env +import json +from app import oauth, db +from app.models import User, Group, File, Folder, UserGroup +import uuid +import os +from openfga_sdk.client import ClientConfiguration +from openfga_sdk.sync import OpenFgaClient +from openfga_sdk.client.models import ClientTuple, ClientWriteRequest, ClientCheckRequest, ClientListObjectsRequest +from functools import wraps +import datetime + + +# This app uses a single Blueprint called "main" +main = Blueprint('main', __name__) + +# We default fga_client to None until it is initialized +fga_client = None + +def initialize_fga_client(): + # This function is called to initialize our FGA Client instance if it is not already available + print("Initializing OpenFGA Client SDK") + configuration = ClientConfiguration( + api_url = os.getenv('FGA_API_URL'), + store_id = os.getenv('FGA_STORE_ID'), + authorization_model_id = os.getenv('FGA_MODEL_ID'), + ) + + global fga_client + fga_client = OpenFgaClient(configuration) + fga_client.read_authorization_models() + print("FGA Client initialized.") + +def fga_relate_user_object(user_uuid,object_uuid,object_type,relation): + # This function creates a tuple in our OpenFGA store which relates a "user" with an "object" using the provided relation + # The relation and object types used must be specified in the OpenFGA model + if fga_client is None: + initialize_fga_client() + + body = ClientWriteRequest( + writes=[ + ClientTuple( + user=f"user:{user_uuid}", + relation=relation, + object=f"{object_type}:{object_uuid}", + ), + ], + ) + response = fga_client.write(body) + print(f"Write Success: {response.writes[0].success}") + return response + +def fga_delete_user_tuple(user_uuid,object_uuid,object_type,relation): + # This function will delete a tuple that defines a user to object relation in our OpenFGA store + # The function will fail if a tuple matching the definition provided does not exist + if fga_client is None: + initialize_fga_client() + + body = ClientWriteRequest( + deletes=[ + ClientTuple( + user=f"user:{user_uuid}", + relation=relation, + object=f"{object_type}:{object_uuid}", + ), + ], + ) + response = fga_client.write(body) + return response + +def fga_relate_objects(object1_type,object1_uuid,object2_type,object2_uuid,relation): + # This function creates a tuple in our OpenFGA instance that relates two objects with the relation specified + # The object types and relation specified must exist in the OpenFGA model + if fga_client is None: + initialize_fga_client() + + body = ClientWriteRequest( + writes=[ + ClientTuple( + user=f"{object1_type}:{object1_uuid}", + relation=relation, + object=f"{object2_type}:{object2_uuid}", + ), + ], + ) + response = fga_client.write(body) + return response + +def fga_delete_object_tuple(object1_type,object1_uuid,object2_type,object2_uuid,relation): + # This function will delete a tuple which associates two objects in our OpenFGA store + # If a tuple matching the passed values does not exist this function will fail. + if fga_client is None: + initialize_fga_client() + + body = ClientWriteRequest( + deletes=[ + ClientTuple( + user=f"{object1_type}:{object1_uuid}", + relation=relation, + object=f"{object2_type}:{object2_uuid}", + ), + ], + ) + response = fga_client.write(body) + return response + +def fga_check_user_access(user_uuid,action,object_type,object_uuid): + # This function will check whether a user is authorized to perform the specified action on an object + # It will return a boolean value + if fga_client is None: + initialize_fga_client() + + print(f"Checking user: {user_uuid} for {action} permission on the {object_type} {object_uuid}") + + body = ClientCheckRequest( + user=f"user:{user_uuid}", + relation=action, + object=f"{object_type}:{object_uuid}", + ) + + response = fga_client.check(body) + return response.allowed + +def fga_list_objects(user_uuid,action,object_type): + # This function will return a list of objects for which the specified user can perform the specified action + if fga_client is None: + initialize_fga_client() + + print(f"Getting objects of type {object_type} where user {user_uuid} has a {action} relationship.") + + body = ClientListObjectsRequest( + user=f"user:{user_uuid}", + relation=action, + type=object_type, + ) + + response = fga_client.list_objects(body) + + return response.objects + +def relateUserObject(user_uuid,object_uuid,object_type,relation): + #Wrapper function, can likely be removed + + result = fga_relate_user_object(user_uuid,object_uuid,object_type,relation) + + return result + + + +def require_auth(f): + @wraps(f) + def decorated_function(*args, **kwargs): + # This decorated function can be applied to route handers and will ensure that a valid user session is active. + # If the requestor is not logged in it will redirect their browser to the home page + if 'user' not in session: + return redirect(url_for('main.home')) + return f(*args, **kwargs) + return decorated_function + +def api_require_auth(f): + @wraps(f) + def decorated_function(*args, **kwargs): + # This decorated function provides similar functionality to the one above but is used for API routes. + # Instead of redirecting the user it instead returns a 403 with a permission denied message in JSON to + # the client if there is not a valid session + if 'user' not in session: + return jsonify({"error": "Permission denied - no authenticated user"}), 403 + return f(*args,**kwargs) + return decorated_function + +def loadSession(email): + # This function is used after a user has authenticated to set the needed session variables so they can + # be accessed by other route handlers in the application + print(f"Loading User Info from database for {email}") + user = User.query.filter_by(email=email).first() + + if user is None: + return False + + session["user_id"] = user.id + session["uuid"] = user.uuid + session["name"] = user.name + session["image"] = user.image + + home_folder = Folder.query.filter_by(creator=user.id,default_folder=True).first() + + session["home_folder"] = home_folder.uuid + session["home_folder_name"] = home_folder.name + session['pwd'] = home_folder.uuid + + return True + +def registerUser(user_info): + # This function is used when a user logs into the app for the first time. + # It creates an entry in the database for the user and creates a default folder for them + email = user_info['email'] + name = user_info['name'] + image = user_info['picture'] + + new_uuid = uuid.uuid4() + print(f"Registering New User {new_uuid} in Database") + + user = User(email=email, name=name, uuid=new_uuid, image=image) + db.session.add(user) + db.session.commit() + print("User Registered in database") + + #Create Default Folder for new user + folder_id = createDefaultFolder(user.id) + + createDefaultFile(user.id,folder_id) + + return True + +def createDefaultFolder(user_id): + # This function creates a user's default folder. Each user has one default folder, it is the root for all the + # Files and folders they create in the app (other than those created in a folder shared by another user) + user = User.query.filter_by(id=user_id).first() + + if user is None: + return False + + folder_name = f"{user.name}'s Folder" + new_uuid = uuid.uuid4() + folder = Folder(uuid=new_uuid, creator=user.id, name=folder_name, default_folder=True) + db.session.add(folder) + db.session.commit() + + fga_relate_user_object(user.uuid, new_uuid, "folder", "owner") + + + return folder.id + +def createDefaultFile(user_id, folder_id): + # When we create a user's default folder this function creates a readme.txt file in their folder + user = User.query.filter_by(id=user_id).first() + folder = Folder.query.filter_by(id=folder_id).first() + + if user is None or folder is None: + return False + + file_name = "Readme.txt" + file_content = "Welcome to your folder. You can create and share text files here." + new_uuid = uuid.uuid4() + + file = File(uuid=new_uuid, folder=folder.uuid, name=file_name, text_content=file_content, creator=user.id) + db.session.add(file) + db.session.commit() + + print("Default file created, updating authorization tuple") + + fga_relate_user_object(user.uuid, new_uuid, "file", "owner") + + return True + +def createNewFolder(parent_uuid,name,user_id): + # This function creates a new folder with the name and parent folder specified and applies relevant ownership permissions + user = User.query.filter_by(id=user_id).first() + + if user is None: + return False + + new_uuid = uuid.uuid4() + folder = Folder(uuid=new_uuid, parent=parent_uuid, default_folder=False, creator=user_id, name=name) + db.session.add(folder) + db.session.commit() + + print(f"New folder {name} created, creating new authorization tuples") + + fga_relate_user_object(user.uuid, new_uuid, "folder", "owner") + + print(f"Created ownership. Now creating parent-child relationship between {parent_uuid} and {new_uuid}") + + fga_relate_objects("folder", parent_uuid, "folder", new_uuid, "parent") + + return True + +def createNewFile(parent_uuid, name, user_id, content): + # This function creates a new file with a title and content, owned by the user specified + user = User.query.filter_by(id=user_id).first() + + if user is None: + return False + + new_uuid = uuid.uuid4() + + print(f"Creating a new file named {name} in directory {parent_uuid} for user_id {user_id}") + + file = File(uuid=new_uuid, folder=parent_uuid, creator=user_id, name=name, text_content=content) + db.session.add(file) + db.session.commit() + + print(f"New File {name} created, creating new authorization tuples") + + fga_relate_user_object(user.uuid, new_uuid, "file", "owner") + fga_relate_objects("folder", parent_uuid, "file", new_uuid, "parent") + + return new_uuid + +def createNewGroup(name, user_uuid): + # This function creates a new user group with the name specified and sets the specified user as it's owner + user = User.query.filter_by(uuid=user_uuid).first() + + if user is None: + return False + + new_uuid = uuid.uuid4() + + # Create Group db entry + group = Group(uuid=new_uuid,creator=user.id, name=name) + db.session.add(group) + db.session.commit() + + # Make user creator of group + assoc = UserGroup(user_id=user.id, group_id=group.id) + db.session.add(assoc) + db.session.commit() + + # Create FGA Tuple + fga_relate_user_object(user_uuid,new_uuid,"group","owner") + fga_relate_user_object(user_uuid,new_uuid,"group","member") + + return new_uuid + +# Route Handers + + +@main.route("/login") +def login(): + # Login function redirects to the Auth0 login page for our app + return oauth.auth0.authorize_redirect( + redirect_uri=url_for("main.callback", _external=True) + ) + +@main.route("/callback", methods=["GET", "POST"]) +def callback(): + # The callback function that Auth0 will redirect users to after authentication + try: + token = oauth.auth0.authorize_access_token() + print(f"TOKEN: {token}\n\n\n") + session["user"] = token + + user_info = token['userinfo'] + + + user = User.query.filter_by(email=user_info['email']).first() + if user is None: + registerUser(user_info) + else: + print("User is already registered.") + + loadSession(user_info['email']) + + except Exception as e: + print(f"Error: {e}\n\n") + return redirect(url_for("main.home")) + return redirect(url_for("main.home")) + + +@main.route("/logout") +def logout(): + # Log a user out of the app, clear the session and redirect them to the Auth0 logout url for our app + session.clear() + return redirect( + "https://" + env.get("AUTH0_DOMAIN") + + "/v2/logout?" + + urlencode( + { + "returnTo": url_for("main.home", _external=True), + "client_id": env.get("AUTH0_CLIENT_ID"), + }, + quote_via=quote_plus, + ) + ) + +@main.route("/api/list/") +@api_require_auth +def list_directory(folder_uuid): + # This function will return JSON representing the contents of the specified folder and details about it if the requesting user is authorized + folder_uuid_u = uuid.UUID(folder_uuid) + print(f"Directory List Request uuid: {folder_uuid}") + user_uuid = session['uuid'] + pwd = Folder.query.filter_by(uuid=folder_uuid_u).first() + print("Got Folder Info") + child_folders = Folder.query.filter_by(parent=pwd.uuid).all() + print("Got Child Folders") + child_files = File.query.filter_by(folder=pwd.uuid).all() + print("Got Child Files") + folder_objects = [] + sidebar_objects = [] + + if fga_check_user_access(user_uuid,"can_create_file","folder",folder_uuid): + pwd_can_write = True + else: + pwd_can_write = False + + if fga_check_user_access(user_uuid,"can_share", "folder", folder_uuid): + pwd_can_share = True + else: + pwd_can_share = False + + if fga_check_user_access(user_uuid,"owner","folder",folder_uuid): + is_owner = True + else: + is_owner = False + + session["pwd"] = folder_uuid_u + + print("Checking for parent folder") + if pwd.parent is not None: + parent_dir = Folder.query.filter_by(uuid=pwd.parent).first() + if fga_check_user_access(user_uuid, "viewer", "folder", parent_dir.uuid): + folder_objects.append({ + "uuid": parent_dir.uuid, + "name": "..", + "type": "folder" + }) + + + print("Checking child folder permissions") + for folder in child_folders: + if fga_check_user_access(user_uuid, "viewer", "folder", folder.uuid): + folder_objects.append({ + "uuid": folder.uuid, + "name": folder.name, + "type": "folder" + }) + + print("Checking child file permissions") + for file in child_files: + print(f"Found File {file.name}") + if fga_check_user_access(user_uuid, "can_read", "file", file.uuid): + print(f"Access to file {file.name} granted") + folder_objects.append({ + "uuid": file.uuid, + "name": file.name, + "type": "file" + }) + else: + print(f"Access to file {file.name} denied") + + print("Checking for folders shared with this user") + + folders = fga_list_objects(user_uuid,"viewer","folder") + print(f"Shared Folders:\n{folders}\n---") + for shared_folder in folders: + folder_uuid = shared_folder.split("folder:")[1] + folder_uuid_u = uuid.UUID(folder_uuid) + folder = Folder.query.filter_by(uuid=folder_uuid_u).first() + if folder.creator is not session['user_id']: + sidebar_objects.append({ + "uuid": folder_uuid, + "name": folder.name, + "type": "folder" + }) + + client_response = { + "folder_uuid": str(pwd.uuid), + "folder_name": pwd.name, + "can_create_file": pwd_can_write, + "can_share": pwd_can_share, + "is_default": pwd.default_folder, + "is_owner": is_owner, + "contents": folder_objects, + "sidebar" : sidebar_objects + } + return jsonify(client_response) + +def folder_delete(folder_id,user_uuid): + # NOT YET IMPLEMENTED - For use in delete_folder() for recursive deletions + print("Folder Delete initiated") + +def file_delete(file_id,user_uuid): + # NOT YET IMPLEMENTED + # for use in delete_folder() for recursive deletions + print("File Delete Initiated") + + +@main.route("/api/delete_folder/", methods=["POST"]) +@api_require_auth +def delete_folder(folder_uuid): + # Function to delete a folder. Currently Incomplete + folder_uuid_u = uuid.UUID(folder_uuid) + user_id = session['user_id'] + user_uuid = session['uuid'] + + folder = Folder.query.filter_by(uuid=folder_uuid_u).first() + + if folder.default_folder: + client_response = { + "result": "error", + "message": "Cannot delete your default folder" + } + return jsonify(client_response), 403 + + if fga_check_user_access(user_uuid,"owner","folder",folder_uuid): + print(f"User is owner of folder") + + child_folder_queue = [folder.id] + delete_folder_queue = [folder.id] + delete_file_queue = [] + + while len(child_folder_queue) > 0: + f_id = child_folder_queue.pop(0) + folders = Folder.query.filter_by(parent=f_id).all() + for f in folders: + child_folder_queue.append(f.id) + delete_folder_queue.append(f.id) + + files = File.query.filter_by(folder=f_id).all() + for fl in files: + delete_file_queue.append(fl.id) + + file_delete_count = 0 + folder_delete_count = 0 + + for dir in delete_folder_queue: + folder_delete(dir,user_uuid) + folder_delete_count += 1 + + for fle in delete_file_queue: + file_delete(fle,user_uuid) + file_delete_count += 1 + + client_response = { + "result": "success", + "message": f"{folder_delete_count} Folders and {file_delete_count} Files deleted sucessfully" + } + return jsonify(client_response) + + + else: + client_response = { + "result": "error", + "message": "Permission denied to delete folder" + } + return jsonify(client_response), 403 + +@main.route("/api/create_folder/", methods=["POST"]) +@api_require_auth +def create_folder(folder_uuid): + # Function to create a new folder within the folder specified if the user is authorized + # Expects a "name" form value + name = request.form['name'] + print(f"Creating folder named {name} in uuid: {folder_uuid}") + folder_uuid_u = uuid.UUID(folder_uuid) + user_id = session['user_id'] + user_uuid = session['uuid'] + pwd = Folder.query.filter_by(uuid=folder_uuid_u).first() + + if fga_check_user_access(user_uuid, "can_create_file", "folder", folder_uuid): + createNewFolder(folder_uuid_u,name,user_id) + else: + print("Access Denied to create folder") + return jsonify({'result': 'access denied'}), 403 + + return jsonify({'result': 'success'}) + +@main.route("/api/load_file/") +@api_require_auth +def load_file(file_uuid): + # Function to load the details and content of the specified file if the user is authorized. + user_id = session['user_id'] + user_uuid = session['uuid'] + file_uuid_u = uuid.UUID(file_uuid) + + if fga_check_user_access(user_uuid, "can_read", "file", file_uuid): + print("User allowed to read file") + read_allowed = True + file = File.query.filter_by(uuid=file_uuid_u).first() + if fga_check_user_access(user_uuid, "can_write", "file", file_uuid): + print("User allowed to write file") + write_allowed = True + + else: + write_allowed = False + + client_response = { + "authorized": True, + "read_allowed": read_allowed, + "write_allowed": write_allowed, + "file_name": file.name, + "file_content": file.text_content + } + return jsonify(client_response) + else: + read_allowed = False + write_allowed = True + + client_response = { + "authorized": False, + "read_allowed": read_allowed, + "write_allowed": write_allowed, + "message": "File access not authorized" + } + return jsonify(client_response), 403 + + +@main.route("/api/save_file/", methods=["POST"]) +@api_require_auth +def save_file(file_uuid): + # Function to save changes to an existing file if the user is authorized + name = request.form['name'] + content = request.form['content'] + user_uuid = session['uuid'] + user_id = session['user_id'] + file_uuid_u = uuid.UUID(file_uuid) + + if fga_check_user_access(user_uuid, "can_write", "file", file_uuid): + print("Write authorized") + file = File.query.filter_by(uuid=file_uuid_u).first() + file.name = name + file.text_content = content + file.updated = datetime.datetime.utcnow() + db.session.commit() + client_response = { + "authorized": True, + "write_allowed": True, + "result": "success", + "message": "Changes saved to file" + } + return jsonify(client_response) + else: + print("User is not authorized to write this file") + client_response = { + "authorized": False, + "write_allowed": False, + "message": "User is not authorized to write file" + } + return jsonify(client_response), 403 + + + +@main.route("/api/create_file/", methods=["POST"]) +@api_require_auth +def create_file(folder_uuid): + # Function to create a new file with the name and content provided in the specified folder if the user is authorized to do so + name = request.form['name'] + content = request.form['content'] + print(f"Creating file named {name} in uuid: {folder_uuid}") + folder_uuid_u = uuid.UUID(folder_uuid) + user_id = session['user_id'] + user_uuid = session['uuid'] + pwd = Folder.query.filter_by(uuid=folder_uuid_u).first() + + if fga_check_user_access(user_uuid, "can_create_file", "folder", pwd.uuid): + print(f"User has permission. Creating new file named {name} in folder {pwd.name}:{folder_uuid}") + file_uuid = createNewFile(folder_uuid_u, name, user_id, content) + else: + print("Access Denied to create a file here"), 403 + return jsonify({'result': 'access denied'}) + + return jsonify({'result': 'success', 'uuid': file_uuid }) + +@main.route("/api/delete_file/", methods=["POST"]) +@api_require_auth +def delete_file(file_uuid): + # Function to delete a specified file if the requesting user is authorized + file_uuid_u = uuid.UUID(file_uuid) + user_uuid = session['uuid'] + + if fga_check_user_access(user_uuid, "can_write", "file", file_uuid): + print("User authorized with write access can delete file.") + File.query.filter_by(uuid=file_uuid_u).delete() + db.session.commit() + client_response = { + "authorized": True, + "success": True, + "message": "File Deleted" + } + return jsonify(client_response) + else: + print("User is not authorized to delete file") + client_response = { + "authorized" : False, + "success": False, + "message": "User not authorized" + } + return jsonify(client_response), 403 + +@main.route("/api/create_group", methods=["POST"]) +@api_require_auth +def create_group(): + # Function to create a new user group with the provided name (All users can create new groups) + group_name = request.form["name"] + user_uuid = session['uuid'] + user_id = session['user_id'] + + group_uuid = createNewGroup(group_name,user_uuid) + + if group_uuid: + client_response = { + "status" : "success", + "message": f"Group {group_name} created with UUID: {group_uuid}" + } + return jsonify(client_response) + else: + client_response = { + "status": "error", + "message": "Failed to create group" + } + return jsonify(client_response), 403 + +@main.route("/api/group/") +@api_require_auth +def get_group(group_uuid): + # Function to retrieve the details of a specified group if the requesting user is authorized + user_uuid = session["uuid"] + group_uuid_u = uuid.UUID(group_uuid) + + if fga_check_user_access(user_uuid,"can_view", "group", group_uuid): + # User is authorized to view group members + group = Group.query.filter_by(uuid=group_uuid_u).first() + members = UserGroup.query.filter_by(group_id=group.id).all() + if fga_check_user_access(user_uuid, "can_invite", "group", group_uuid): + can_invite = True + else: + can_invite = False + + member_list = [] + member_count = 0 + + for member in members: + group_member = User.query.filter_by(id=member.user_id).first() + + #Check member's access level + member_level = None + if fga_check_user_access(group_member.uuid, "member", "group", group_uuid): + member_level = "member" + if fga_check_user_access(group_member.uuid, "admin", "group", group_uuid): + member_level = "admin" + if fga_check_user_access(group_member.uuid, "owner", "group", group_uuid): + member_level = "owner" + + if member_level is not None: + member_list.append({ + "name" : group_member.name, + "uuid": group_member.uuid, + "image": group_member.image, + "email": group_member.email, + "role" : member_level + }) + member_count += 1 + + client_response = { + "result": "success", + "name" : group.name, + "can_invite": can_invite, + "member_count": member_count, + "members": member_list + } + return jsonify(client_response) + + else: + client_response = { + "result": "Error", + "message": "Not authorized to view group details" + } + return jsonify(client_response), 403 + +@main.route("/api/share/folder/", methods=["POST"]) +@api_require_auth +def share_folder(folder_uuid): + # Function to share a folder with a user or group if the requesting user is authorized to do so + print("Folder Share Request") + user_id = session["user_id"] + user_uuid = session["uuid"] + + + subject_uuid = request.form["subject_uuid"] + subject_type = request.form["subject_type"] + + allow_write = request.form["allow_write"] + + print(f"Allow Write: {allow_write}") + + if fga_check_user_access(user_uuid,"can_share","folder",folder_uuid): + print("User is authorized to share folder") + if allow_write == "true": + relation = "can_create_file" + else: + relation = "viewer" + + print(f"Sharing folder {folder_uuid} with {subject_type} {subject_uuid} with relation {relation}") + + if subject_type == "user": + + fga_relate_user_object(subject_uuid,folder_uuid,"folder",relation) + elif subject_type == "group": + fga_relate_objects("group",f"{subject_uuid}#member","folder", folder_uuid, relation) + + else: + client_response = { + "result": "error", + "message": "No valid subject type defined" + } + return jsonify(client_response), 500 + + client_response = { + "result": "success", + "message": "Folder shared" + } + return jsonify(client_response) + + + else: + client_response = { + "result": "error", + "message": "Not authorized to share this folder" + } + return jsonify(client_response), 403 + + +@main.route("/api/share/file/") +@api_require_auth +def share_file(file_uuid): + # Function to share a specified file with a user or group if the requesting user is authorized + print("File Share Request") + user_id = session["user_id"] + user_uuid = session["uuid"] + + + subject_uuid = request.form["subject_uuid"] + subject_type = request.form["subject_type"] + + allow_write = request.form["allow_write"] + + print(f"Allow Write: {allow_write}") + + if fga_check_user_access(user_uuid,"can_share","file",file_uuid): + print("User is authorized to share file") + if allow_write == "true": + relation = "can_write" + else: + relation = "can_view" + + print(f"Sharing file {file_uuid} with {subject_type} {subject_uuid} with relation {relation}") + + if subject_type == "user": + + fga_relate_user_object(subject_uuid,file_uuid,"file",relation) + elif subject_type == "group": + fga_relate_objects("group",f"{subject_uuid}#member","file", file_uuid, relation) + + else: + client_response = { + "result": "error", + "message": "No valid subject type defined" + } + return jsonify(client_response), 500 + + client_response = { + "result": "success", + "message": "File shared" + } + return jsonify(client_response) + + + else: + client_response = { + "result": "error", + "message": "Not authorized to share this file" + } + return jsonify(client_response), 403 + +@main.route("/api/group/add/", methods=["POST"]) +@api_require_auth +def group_add_user(group_uuid): + # Function to add a user to a group if the requesting user is authorized to add users to the specified group + print("Add user to group request") + member_uuid = request.form["user_uuid"] + member_uuid_u = uuid.UUID(member_uuid) + group_uuid_u = uuid.UUID(group_uuid) + user_uuid = session['uuid'] + role = request.form['role'] + + if fga_check_user_access(user_uuid, "can_invite", "group", group_uuid): + print("user is authorized to add members to group") + new_user = User.query.filter_by(uuid=member_uuid_u).first() + group = Group.query.filter_by(uuid=group_uuid_u).first() + #Check if user is already a member + if UserGroup.query.filter_by(user_id=new_user.id, group_id=group.id).first() is None: + membership = UserGroup(user_id=new_user.id,group_id=group.id) + db.session.add(membership) + db.session.commit() + + res = fga_relate_user_object(new_user.uuid,group_uuid,"group",role) + if role == "admin": + fga_relate_user_object(new_user.uuid,group_uuid,"group","member") + if res is not None: + client_response = { + "result": "success", + "message": f"User added to group as {role}" + } + return jsonify(client_response) + else: + client_response = { + "result": "error", + "message": f"Failed to grant user {role} permissions on this group" + } + return jsonify(client_response),500 + else: + # User is already a group member. + client_response = { + "result": "error", + "message": "User is already a member of this group" + } + return jsonify(client_response), 409 + + +@main.route("/api/group/make_admin/") +@api_require_auth +def group_make_user_admin(group_uuid): + # Function to allow a group owner or admin to grant admin permissions on that group to another user + print("Make user group admin") + user_uuid = session['uuid'] + group_uuid_u = uuid.UUID(group_uuid) + subject_uuid = request.forn['subject_uuid'] + if fga_check_user_access(user_uuid,"owner","group",group_uuid) or fga_check_user_access(user_uuid,"admin","group",group_uuid): + fga_relate_user_object(subject_uuid,group_uuid,"group","admin") + client_response = { + "result": "success", + "message": "Admin permissions granted to user" + } + return jsonify(client_response) + else: + client_response = { + "result": "error", + "message": "User does not have permission to grant admin rights" + } + return jsonify(client_response), 403 + +@main.route("/api/group/downgrade_user/") +@api_require_auth +def group_downgrade_user(group_uuid): + # Function to allow a group owner or admin to revoke admin permissions from a specified group member + print("Remove group admin privileges from user") + user_uuid = session['uuid'] + group_uuid_u = uuid.UUID(group_uuid) + subject_uuid = request.form['subject_uuid'] + if fga_check_user_access(user_uuid,"admin","group",group_uuid) or fga_check_user_access(user_uuid,"owner","group",group_uuid): + print("user is authorized to change group permissions") + fga_delete_user_tuple(subject_uuid,group_uuid,"group","admin") + client_response = { + "result": "success", + "message": "Admin permissions removed from user" + } + return jsonify(client_response) + else: + client_response = { + "result": "error", + "message": "User does not have permission to modify group permissions" + } + return jsonify(client_response), 403 + +@main.route("/api/group/remove_user/") +@api_require_auth +def group_remove_user(group_uuid): + # NOT IMPLEMENTED + # Function to allow a group owner or admin to remove a user from the specified group + print("Remove user from group") + +@main.route("/api/user_autocomplete", methods=["POST"]) +@api_require_auth +def user_autocomplete(): + # Function used to populate the autocomplete in share UIs for selecting a user + partial = request.form["partial"] + suggestions = User.query.filter(User.email.startswith(partial)).limit(8) + matches = [] + match_count = 0 + for user in suggestions: + if user.uuid != session['uuid']: + matches.append({ + "name": user.name, + "email": user.email, + "uuid": user.uuid, + "image": user.image + }) + match_count += 1 + client_response = { + "matches": match_count, + "users": matches + } + return jsonify(client_response) + + +@main.route("/api/group_autocomplete", methods=["POST"]) +@api_require_auth +def group_autocomplete(): + # Function used to populate the autocomplete in the share UIs for selecting a group + user_uuid = session["uuid"] + + partial = request.form["partial"] + suggestions = Group.query.filter(Group.name.startswith(partial)).limit(8) + matches = [] + match_count = 0 + for group in suggestions: + if fga_check_user_access(user_uuid,"can_view","group",group.uuid): + matches.append({ + "name": group.name, + "uuid": group.uuid + }) + match_count += 1 + client_response = { + "matches": match_count, + "groups": matches + } + return jsonify(client_response) + + +@main.route("/file/") +@require_auth +def file_view(file_uuid): + # Function to load the contents of the specified file if the requesting user is authorized to view it. + # Also checks if the user has write or owner permissions and provides other metadata + file_uuid_u = uuid.UUID(file_uuid) + user_uuid = session.get('uuid') + + if fga_check_user_access(user_uuid, "can_read", "file", file_uuid): + print("File access authorized") + file = File.query.filter_by(uuid=file_uuid_u).first() + creator = User.query.filter_by(id=file.creator).first() + + if fga_check_user_access(user_uuid, "can_write", "file", file_uuid): + write_allowed = True + else: + write_allowed = False + print("User does not have write access") + + if fga_check_user_access(user_uuid, "can_share", "file", file_uuid): + share_allowed = True + else: + share_allowed = False + print("User cannot share this file") + + + created = datetime.datetime.strftime(file.created, '%d-%b-%Y %H:%M') + updated = datetime.datetime.strftime(file.updated, '%d-%b-%Y %H:%M') + + client_response = { + "authorized": True, + "write_allowed": write_allowed, + "share_allowed": share_allowed, + "uuid": file_uuid, + "name": file.name, + "content": file.text_content, + "created": created, + "modified": updated, + "creator_name": creator.name, + "creator_image": creator.image + } + return render_template("file.html", user=session, data=client_response) + else: + print("Not authorized") + client_response = { + "authorized": False, + "message": "Not authorized to view this file" + } + return render_template("file.html", user=session, data=client_response), 403 + +@main.route("/groups") +@require_auth +def groups(): + # Returns details about the groups the requesting user is owner, admin, or a member of + user_id = session['user_id'] + user_uuid = session['uuid'] + + groups = UserGroup.query.filter_by(user_id=user_id) + + users_groups = [] + group_count = 0 + + for membership in groups: + group_id = membership.group_id + group = Group.query.filter_by(id=group_id).first() + + member_count = UserGroup.query.filter_by(group_id=group_id).count() + + access_level = None + if fga_check_user_access(user_uuid, "member", "group", group.uuid): + access_level = "member" + + if fga_check_user_access(user_uuid, "admin", "group", group.uuid): + access_level = "admin" + + if fga_check_user_access(user_uuid, "owner", "group", group.uuid): + access_level = "owner" + + if fga_check_user_access(user_uuid, "can_invite", "group", group.uuid): + can_invite = True + else: + can_invite = False + + if access_level is not None: + users_groups.append({ + "group_name" : group.name, + "group_uuid" : group.uuid, + "member_count": member_count, + "access_level": access_level, + "can_invite": can_invite + }) + group_count += 1 + + client_response = { + "group_count": group_count, + "groups": users_groups + } + + return render_template("groups.html", user=session, data=client_response) + + + +@main.route("/") +def home(): + # Home page + # If no user is logged in it returns a default view with login buttons + # If a user is logged in this will load their "current directory" which is + # the last directory they viewed. + # + # If there is no "pwd" value specifying a current directory we default to the user's default_folder + if session: + user_id = session.get('user_id') + user_uuid = session.get('uuid') + if not session.get('pwd'): + # If a user is authenticated, fetch their default folder + user_folder = Folder.query.filter_by(creator=user_id, default_folder=True).first() + session['home_folder'] = user_folder.uuid + session['pwd'] = user_folder.pwd + else: + current_directory = session.get('pwd') + u_type = type(current_directory) + print(f"Current Folder: {current_directory} Type: {u_type}") + + if fga_check_user_access(user_uuid,"viewer","folder", current_directory): + user_folder = Folder.query.filter_by(uuid=current_directory).first() + else: + # If user is not authorized to view the folder, give them their default folder + user_folder = Folder.query.filter_by(creator=user_id, default_folder=True).first() + session['home_folder'] = user_folder.uuid + session['home_folder_name'] = user_folder.name + session["pwd"] = user_folder.uuid + else: + user_folder = None + + return render_template("main.html", session=session.get('user'),pwd=user_folder, user=session, pretty=json.dumps(session.get("user"), indent=4)) \ No newline at end of file diff --git a/app/templates/file.html b/app/templates/file.html new file mode 100644 index 0000000..5aa4d22 --- /dev/null +++ b/app/templates/file.html @@ -0,0 +1,214 @@ + + + + + + View File - Learning App + + + + + + + + + + + +
+ {% if data.write_allowed %} + + {% else %} +
{{data.content}}
+ {% endif %} +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/app/templates/groups.html b/app/templates/groups.html new file mode 100644 index 0000000..20786d2 --- /dev/null +++ b/app/templates/groups.html @@ -0,0 +1,460 @@ + + + + + + Groups - Learning App + + + + + + + + + + + + +
+
+
+ + +
+
+ +
+
+
+
+ + + + + + + + + + + {% for group in data.groups %} + + + + + + {% endfor %} + + +
Group NameMember CountActions
{{ group.group_name }}{{ group.member_count }} + {% if group.can_invite %} + + {% endif %} + {% if group.access_level == "owner" or group.access_level == "admin" %} + + {% endif %} + {% if group.access_level == "owner" %} + + {% endif %} +
+ + +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/app/templates/main.html b/app/templates/main.html new file mode 100644 index 0000000..7f27c17 --- /dev/null +++ b/app/templates/main.html @@ -0,0 +1,561 @@ + + + + + + Home - Learning App + + + + + + + + + + + + + +
+
+
+
+ + +
+ +
+
+
+ + + +
+ {% if session %} + {% if pwd %} + + +
+

{{ pwd.name }}

+
+ + + + + + + + + +
+
+
+
+ {% else %} +

Error: Default folder not found

+
{{pretty}}
+ {% endif %} +
+ + + {% else %} +
+

OpenFGA Demo App


+

This app uses Auth0 for authentication with a Google account and OpenFGA to manage access and sharing authorization.

+ +

Sign in to get started.

+ + Sign In + + +
+ + {% endif %} +
+ + + +
+
+
+ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config.py b/config.py new file mode 100644 index 0000000..90a5ece --- /dev/null +++ b/config.py @@ -0,0 +1,6 @@ +import os + +class Config: + SECRET_KEY = os.getenv("APP_SECRET_KEY") + SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI') + SQLALCHEMY_TRACK_MODIFICATIONS= False \ No newline at end of file diff --git a/env.example b/env.example new file mode 100644 index 0000000..9ebf0fd --- /dev/null +++ b/env.example @@ -0,0 +1,9 @@ +AUTH0_CLIENT_ID= +AUTH0_CLIENT_SECRET= +AUTH0_DOMAIN= +APP_SECRET_KEY= +SQLALCHEMY_DATABASE_URI=sqlite:///db.sqlite3 +PORT=3000 +FGA_API_URL=http://localhost:8080 +FGA_STORE_ID= +FGA_MODEL_ID= \ No newline at end of file diff --git a/model.fga b/model.fga new file mode 100644 index 0000000..50d6c73 --- /dev/null +++ b/model.fga @@ -0,0 +1,33 @@ +model + schema 1.1 + +type user + relations + define can_create: [user] + define can_delete: [user] + define can_invite: [user] + +type group + relations + define admin: [user] + define can_invite: [user] or owner or admin + define can_view: member or owner or admin + define member: [user] + define owner: [user] + +type folder + relations + define can_create_file: [user, group#member] or owner or owner from parent + define can_share: [group#admin, group#owner] or owner + define owner: [user] + define parent: [folder] + define viewer: [user, user:*, group#member] or owner or can_create_file or can_create_file from parent or viewer from parent + +type file + relations + define can_change_owner: owner + define can_read: [user, user:*, group#member] or owner or viewer from parent + define can_share: [user, user:*, group#member] or owner or owner from parent or can_share from parent + define can_write: [user, user:*, group#member] or owner or owner from parent or can_create_file from parent + define owner: [user] + define parent: [folder] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..be42acc --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +flask[async]>=2.0.3 +python-dotenv>=0.19.2 +authlib>=1.0 +requests>=2.27.1 +flask-sqlalchemy +openfga_sdk \ No newline at end of file diff --git a/run.py b/run.py new file mode 100644 index 0000000..e407d2f --- /dev/null +++ b/run.py @@ -0,0 +1,8 @@ +from app import create_app +import os +import asyncio + +app = create_app() + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=int(os.getenv("PORT", 3000))) \ No newline at end of file