Flask Reference - PropelAuth Docs

Flask Reference

Installation

pip install propelauth_flask

Initialize

init_auth performs a one-time initialization of the library. This verifies your api_key and fetches the metadata needed to verify access tokens in require_user and optional_user.

In serverless environments, it's beneficial to skip the fetch, in which case you can pass in token_verification_metadata instead of having the library fetch it. You can find your verifier key and issuer URL in the Backend Integration page in your PropelAuth dashboard.

Traditional

from propelauth_flask import init_auth

auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

Serverless

from propelauth_flask import init_auth

auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

Async Support

If you prefer to use asynchronous functions you can use init_auth_async instead of init_auth. When using init_auth_async, each backend API request will be async.

Traditional

from propelauth_flask import init_auth_async

auth = init_auth_async(
    "YOUR_AUTH_URL",
    "YOUR_API_KEY",
    httpx_client=httpx.AsyncClient() # Optional. Only needed if you want to use a custom client
)

Protect API Routes

Protecting an API route is as simple as adding a decorator to the route.

None of the decorators make an external request to PropelAuth. They all are verified locally using the access token provided in the request, making it very fast.

require_user

A decorator that will verify the request was made by a valid user. If a valid access token is provided, it will return a User Class. If not, the request is rejected with a 401 status code.

from flask import Flask
from propelauth_flask import init_auth, current_user

app = Flask(__name__)
auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

@app.route("/api/whoami")
@auth.require_user
def who_am_i():
    """This route is protected, current_user is always set"""
    return {"user_id": current_user.user_id}

optional_user

Similar to require_user, except if an access token is missing or invalid, the request is allowed to continue, but current_user.exists() will be False.

from flask import Flask
from propelauth_flask import init_auth, current_user

app = Flask(__name__)
auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

@app.route("/api/whoami_optional")
@auth.optional_user
def who_am_i_optional():
    if current_user.exists():
        return {"user_id": current_user.user_id}
    return {}

current_user

A per-request value that contains user information for the user making the request. It's set by one of require_user or optional_user.

It has all the fields on the User class, as well as an exists() method that returns True if the user exists. The only time exists() will return False is if you are using optional_user and no valid access token was provided.

If you want to take advantage of type support, you can import the User class to define a new user variable.

from flask import Flask
from propelauth_flask import init_auth, current_user, User

app = Flask(__name__)
auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

@app.route("/api/whoami")
@auth.require_user
def who_am_i():
    user: User = current_user.user
    return {"user_id": user.user_id}

Authorization / Organizations

You can also verify which organizations the user is in, and which roles and permissions they have in each organization all through the User Class.

Check Org Membership

Verify that the request was made by a valid user and that the user is a member of the specified organization. This can be done using the User class.

@app.route("/api/org/<org_id>", methods=['GET'])
@auth.require_user
def org_membership(org_id):
    org = current_user.get_org(org_id)
    if org == None:
        # Return a 403 error, e.g.: return "Forbidden", 403
    return f"You are in org {org.org_name}"

Check Org Membership and Role

Similar to checking org membership, but will also verify that the user has a specific Role in the organization. This can be done using either the User or OrgMemberInfo classes.

## Assuming a Role structure of Owner => Admin => Member

@app.route("/api/org/<org_id>", methods=['GET'])
@auth.require_user
def org_owner(org_id):
    org = current_user.get_org(org_id)
    if (org == None) or (org.user_is_role("Owner") == False):
        # return 403 error
    return f"You are in org {org.org_name}"

Check Org Membership and Permission

Similar to checking org membership, but will also verify that the user has the specified permission in the organization. This can be done using either the User or OrgMemberInfo classes.

@app.route("/api/org/<org_id>", methods=['GET'])
@auth.require_user
def org_billing(org_id):
    org = current_user.get_org(org_id)
    if (org == None) or (org.user_has_permission("can_view_billing") == False):
        # return 403 error
    return f"You can view billing information for org {org.org_name}"

User

The User Class contains information about the user that made the request. It can be retrieved by using the require_user decorator.

@app.route("/api/whoami")
@auth.require_user
def who_am_i():
    return {"user_id": current_user.user_id}

Here's the full type structure of the User Class:

OrgMemberInfo

The OrgMemberInfo Class contains information about the user's membership in an organization. It can be retrieved by first getting the User Class and using either get_org(), get_active_org(), or get_orgs().

@app.route("/api/org/<org_id>", methods=['GET'])
@auth.require_user
def org_membership(org_id):
    orgMemberInfo = current_user.get_org(org_id)
    if orgMemberInfo == None:
        # return 403 error
    return f"You are in org {orgMemberInfo.org_name}"

Calling Backend APIs

You can also use the library to call the PropelAuth APIs directly, allowing you to fetch users, create orgs, and a lot more. See the API Reference for more information.

from propelauth_flask import init_auth

auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

magic_link = auth.create_magic_link(email="test@example.com")