### Start Flask Server Output Example (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-magic-link-example/README.md An example of the expected output when the Flask development server starts successfully. This output includes information about the environment, debug mode, and the server's running address. ```bash * Tip: There are .env or .flaskenv files present. Do "pip install python-dotenv" to use them. * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` -------------------------------- ### Navigate and Setup Virtual Environment (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-directory-sync-example/README.md Navigates into the specific example application directory and sets up a Python virtual environment, then activates it. This isolates project dependencies. ```bash $ cd python-flask-example-applications/python-flask-directory-sync-example $ python3 -m venv env $ source env/bin/activate (env) $ ``` -------------------------------- ### Start Flask Development Server Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-admin-portal-example/README.md Starts the Flask development server to run the Admin Portal example application. It specifies the port to run on, defaulting to 5000 or 5001 for macOS Monterey. ```bash (env) $ flask run ``` ```bash (env) $ flask run -p 5001 ``` -------------------------------- ### Install Project Dependencies (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md Installs all the Python dependencies required for the Flask application from the 'requirements.txt' file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Navigate to Example Directory (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-magic-link-example/README.md Changes the current directory to the specific Magic Link example application within the cloned repository. This prepares the environment for subsequent setup steps. ```bash $ cd python-flask-example-applications/python-flask-magic-link-example ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-directory-sync-example/README.md Installs all required Python packages listed in the 'requirements.txt' file within the activated virtual environment. ```bash (env) $ pip install -r requirements.txt ``` -------------------------------- ### Set Up Python Virtual Environment Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-admin-portal-example/README.md Creates and activates a Python virtual environment named 'env'. This isolates project dependencies and ensures a clean development setup. ```bash $ python3 -m venv env $ source env/bin/activate (env) $ ``` -------------------------------- ### Run Flask Development Server (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-directory-sync-example/README.md Starts the Flask development server. Includes an alternative command for macOS Monterey if the default port 5000 is unavailable. ```bash flask run ``` ```bash (env) $ flask run -p 5001 ``` -------------------------------- ### Navigate to MFA Example Directory Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-mfa-example/README.md Navigates the command line into the specific directory for the Python Flask MFA example application within the cloned repository. ```bash $ cd python-flask-mfa-example ``` -------------------------------- ### Run Flask Development Server (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md Starts the Flask development server. If port 5000 is unavailable, an alternative port like 5001 can be specified. ```bash flask run ``` ```bash flask run -p 5001 ``` -------------------------------- ### Navigate to the Admin Portal Example Directory Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-admin-portal-example/README.md Changes the current directory to the specific example application directory for the WorkOS Admin Portal within the cloned repository. ```bash $ cd python-flask-example-applications/python-flask-admin-portal-example ``` -------------------------------- ### Navigate to Example Directory (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-sso-example/README.md Changes the current directory to the specific Flask SSO example application within the cloned repository. ```bash $ cd python-flask-example-applications/python-flask-sso-example ``` -------------------------------- ### Restart Flask Server for Testing (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-sso-example/README.md Navigates back to the example directory, activates the virtual environment, and restarts the Flask development server to test the SSO integration. ```bash $ cd ~/Desktop/python-flask-sso-example/ $ source env/bin/activate (env) $ flask run ``` -------------------------------- ### Clone Example Application Repository (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md Clones the WorkOS Python Flask example applications repository using either HTTPS or SSH. This is the first step in setting up the project. ```bash git clone https://github.com/workos/python-flask-example-applications.git ``` ```bash git clone git@github.com:workos/python-flask-example-applications.git ``` -------------------------------- ### Example .env File Content Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md An example showing how to populate the .env file with necessary WorkOS credentials and an application secret key. ```dotenv WORKOS_API_KEY= WORKOS_CLIENT_ID= APP_SECRET_KEY= ``` -------------------------------- ### Clone Git Repository (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-directory-sync-example/README.md Clones the WorkOS Python example applications repository using either HTTPS or SSH. This is the initial step to obtain the project files. ```bash # HTTPS $ git clone https://github.com/workos/python-flask-example-applications.git ``` ```bash # SSH $ git clone git@github.com:workos/python-flask-example-applications.git ``` -------------------------------- ### Create and Populate .env File Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-admin-portal-example/README.md Creates a '.env' file to securely store environment variables, including WorkOS API key and Client ID. This file is typically ignored by Git. The example shows how to use 'nano' to edit it and lists the required environment variables. ```bash (env) $ touch .env (env) $ nano .env ``` ```bash export WORKOS_API_KEY= export WORKOS_CLIENT_ID= ``` -------------------------------- ### Run Flask Development Server (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-magic-link-example/README.md Starts the Flask development server. It can be run on the default port 5000 or a specified port like 5001 for macOS Monterey if port 5000 is unavailable. The server output indicates when it's running. ```bash (env) $ flask run ``` ```bash # For macOS Monterey or if port 5000 is unavailable (env) $ flask run -p 5001 ``` -------------------------------- ### MFA TOTP Enrollment (Python) Source: https://context7.com/workos/python-flask-example-applications/llms.txt Enrolls a user in Time-based One-Time Password (TOTP) authentication. It generates a QR code for authenticator app setup and stores the factor details. Requires the WorkOS SDK and Flask session management. ```python from flask import jsonify, session @app.route("/enroll_totp_factor", methods=["POST"]) def enroll_totp_factor(): data = request.get_json() type = data["type"] issuer = data["issuer"] user = data["user"] # Enroll TOTP factor new_factor = workos_client.mfa.enroll_factor( type=type, totp_issuer=issuer, totp_user=user ) # Extract QR code for authenticator app setup if new_factor.type == "totp": qr_code = new_factor.totp.qr_code session["current_factor_qr"] = qr_code session["factor_list"].append(new_factor.dict()) session.modified = True return jsonify({ "factor_id": new_factor.id, "qr_code": qr_code, "secret": new_factor.totp.secret }) ``` -------------------------------- ### GET /success - Passwordless Authentication Success Source: https://context7.com/workos/python-flask-example-applications/llms.txt Handles the callback from the magic link authentication and exchanges the provided code for user profile information. ```APIDOC ## GET /success ### Description Handles the callback from the magic link authentication and exchanges the provided code for user profile information. ### Method GET ### Endpoint /success ### Parameters #### Query Parameters - **code** (string) - Required - The authentication code provided in the callback. ### Response #### Success Response (200) - **message** (string) - A welcome message with the user's email. #### Response Example ```json { "message": "Welcome user@example.com" } ``` ``` -------------------------------- ### Create and Activate Python Virtual Environment (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-magic-link-example/README.md Creates a Python virtual environment named 'env' and activates it. This isolates project dependencies and ensures a clean development environment. ```bash python3 -m venv env source env/bin/activate (env) $ ``` -------------------------------- ### Create and Activate Python Virtual Environment (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md Creates a Python virtual environment named 'env' and activates it. This isolates project dependencies. ```bash python3 -m venv env source env/bin/activate ``` -------------------------------- ### Source Environment Variables Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-admin-portal-example/README.md Loads the environment variables defined in the '.env' file into the current shell session, making them accessible to the application. ```bash (env) $ source .env ``` -------------------------------- ### GET /auth/callback - SSO Callback Handler Source: https://context7.com/workos/python-flask-example-applications/llms.txt Handles the OAuth callback from WorkOS after successful user authentication. It exchanges the authorization code for user profile information and stores essential user details in the session. ```APIDOC ## GET /auth/callback ### Description Handles the OAuth callback from WorkOS after successful authentication. Exchanges the authorization code for user profile information and stores it in the session. ### Method GET ### Endpoint /auth/callback ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code returned by WorkOS. ### Response #### Success Response (302 Redirect) Redirects the user to the homepage after processing the callback. #### Response Example ``` Redirect to: / ``` #### Error Response (400 Bad Request) Returned if the 'code' query parameter is missing. #### Response Example ``` Missing code parameter ``` ``` -------------------------------- ### Get Directory User Details - Python Flask Source: https://context7.com/workos/python-flask-example-applications/llms.txt Retrieves detailed information for a specific user from a directory sync connection, including all attributes synced from the identity provider. It requires a user ID and returns a comprehensive user object. ```python from flask import Flask, request import workos import os app = Flask(__name__) # Initialize WorkOS client workos.api_key = os.getenv("WORKOS_API_KEY") workos_client = workos.WorkOS(token=os.getenv("WORKOS_API_KEY")) @app.route("/user") def directory_user(): user_id = request.args.get("id") if not user_id: return "No user ID provided", 400 # Get user details user = workos_client.directory_sync.get_user(user_id) return { "id": user.id, "email": user.emails[0].value if user.emails else None, "first_name": user.first_name, "last_name": user.last_name, "username": user.username, "state": user.state, "custom_attributes": user.custom_attributes, "raw_attributes": user.raw_attributes } ``` -------------------------------- ### Verify Environment Variables Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-mfa-example/README.md Confirms that the environment variables (WORKOS_API_KEY, WORKOS_CLIENT_ID, APP_SECRET_KEY) have been correctly set and are accessible in the current shell session. ```bash (env) $ echo $WORKOS_API_KEY (env) $ echo $WORKOS_CLIENT_ID (env) $ echo $APP_SECRET_KEY ``` -------------------------------- ### Create and Set Environment Variables (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-directory-sync-example/README.md Creates a .env file to store sensitive environment variables like WorkOS API key and webhooks secret, then sources the file to make them accessible. ```bash (env) $ touch .env (env) $ nano .env export WORKOS_API_KEY= export WEBHOOKS_SECRET= # To exit Nano: CTRL + x, then Y, then Enter ``` ```bash (env) $ source .env (env) $ echo $WORKOS_API_KEY (env) $ echo $WEBHOOKS_SECRET ``` -------------------------------- ### Create and Edit .env File (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-magic-link-example/README.md Creates a '.env' file for storing environment variables and opens it using the Nano text editor. Sensitive information like API keys should be stored here. ```bash (env) $ touch .env (env) $ nano .env ``` -------------------------------- ### Verify Environment Variables Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-admin-portal-example/README.md Checks if the WorkOS API Key and Client ID environment variables have been successfully loaded and are accessible in the current shell session. ```bash (env) $ echo $WORKOS_API_KEY (env) $ echo $WORKOS_CLIENT_ID ``` -------------------------------- ### Navigate to Audit Logs App Directory (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md Changes the current directory to the specific Audit Logs example application within the cloned repository. ```bash cd python-flask-example-applications/python-flask-audit-logs-example ``` -------------------------------- ### POST /verify_factor - MFA Challenge Verification Source: https://context7.com/workos/python-flask-example-applications/llms.txt Verifies the code provided by the user against an active MFA challenge. Returns whether the verification was successful. ```APIDOC ## POST /verify_factor ### Description Verifies the code provided by the user against an active MFA challenge. ### Method POST ### Endpoint /verify_factor ### Parameters #### Request Body - **code_digit_1** to **code_digit_6** (string) - Required - The digits of the verification code entered by the user. ### Response #### Success Response (200) - **status** (string) - The status of the verification (success). - **valid** (boolean) - Indicates if the verification was successful. - **challenge** (object) - The details of the verified challenge. #### Response Example ```json { "status": "success", "valid": true, "challenge": { "id": "chlg_klmnopqrs", "authentication_factor_id": "fct_12345abcde", "created_at": "2023-10-27T10:00:00Z", "expires_at": "2023-10-27T10:05:00Z", "status": "succeeded", "type": "sms" } } ``` #### Error Response (401) - **status** (string) - The status of the verification (failed). - **valid** (boolean) - Indicates if the verification was successful (false). #### Error Response Example ```json { "status": "failed", "valid": false } ``` ``` -------------------------------- ### Create and Populate .env File Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-mfa-example/README.md Creates a '.env' file to store sensitive environment variables like WorkOS API key, Client ID, and Flask app secret key. These are sourced for OS access. ```bash (env) $ touch .env (env) $ nano .env WORKOS_API_KEY= WORKOS_CLIENT_ID= APP_SECRET_KEY= To exit Nano: CTRL + x, then Y, then Enter. ``` -------------------------------- ### Verify Environment Variables (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md Commands to check if the environment variables have been successfully loaded and are accessible. ```bash echo $WORKOS_API_KEY echo $WORKOS_CLIENT_ID echo $APP_SECRET_KEY ``` -------------------------------- ### POST /provision_enterprise - Organization Creation and Management Source: https://context7.com/workos/python-flask-example-applications/llms.txt Creates a new organization within WorkOS, optionally verifying provided domains, or retrieves an existing organization if a matching domain is found. This is crucial for managing multi-tenant applications and their enterprise customers. ```APIDOC ## POST /provision_enterprise ### Description Creates a new organization with verified domains or retrieves an existing organization if domains match. This is essential for multi-tenant applications managing enterprise customers. ### Method POST ### Endpoint /provision_enterprise ### Parameters #### Request Body - **org** (string) - Required - The name of the organization. - **domain** (string) - Required - A space-separated string of domains associated with the organization. ### Request Example ```json { "org": "Example Corp", "domain": "example.com corp.com" } ``` ### Response #### Success Response (200 OK) Returns the Organization ID of the created or existing organization. #### Response Example ``` Organization ID: org_01EHQMYV6MBK39QC5PZXHY59C3 ``` ``` -------------------------------- ### Add Environment Variables to .env File (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-magic-link-example/README.md Defines the WorkOS API key and Client ID as environment variables within the '.env' file. These are essential for authenticating with WorkOS services. ```bash export WORKOS_API_KEY= export WORKOS_CLIENT_ID= ``` -------------------------------- ### POST /enroll_totp_factor - MFA TOTP Enrollment Source: https://context7.com/workos/python-flask-example-applications/llms.txt Enrolls a user in Time-based One-Time Password (TOTP) authentication compatible with authenticator apps like Google Authenticator or Authy. Returns a QR code that users can scan. ```APIDOC ## POST /enroll_totp_factor ### Description Enrolls a user in Time-based One-Time Password (TOTP) authentication. ### Method POST ### Endpoint /enroll_totp_factor ### Parameters #### Request Body - **type** (string) - Required - The type of factor, must be 'totp'. - **issuer** (string) - Required - The issuer name for the TOTP authenticator app. - **user** (string) - Required - The user identifier for the TOTP authenticator app. ### Response #### Success Response (200) - **factor_id** (string) - The ID of the newly enrolled factor. - **qr_code** (string) - The QR code for setting up the authenticator app. - **secret** (string) - The secret key for TOTP setup. #### Response Example ```json { "factor_id": "fct_67890fghij", "qr_code": "otpauth://totp/ExampleCorp:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=ExampleCorp", "secret": "JBSWY3DPEHPK3PXP" } ``` ``` -------------------------------- ### POST /enroll_sms_factor - MFA SMS Enrollment Source: https://context7.com/workos/python-flask-example-applications/llms.txt Enrolls a user in SMS-based two-factor authentication by registering their phone number. Returns a factor ID that can be used for subsequent challenges. ```APIDOC ## POST /enroll_sms_factor ### Description Enrolls a user in SMS-based two-factor authentication by registering their phone number. ### Method POST ### Endpoint /enroll_sms_factor ### Parameters #### Request Body - **type** (string) - Required - The type of factor, must be 'sms'. - **phone_number** (string) - Required - The user's phone number. ### Response #### Success Response (200) - **factor_id** (string) - The ID of the newly enrolled factor. - **type** (string) - The type of the enrolled factor (sms). - **phone_number** (string) - The enrolled phone number. #### Response Example ```json { "factor_id": "fct_12345abcde", "type": "sms", "phone_number": "+15551234567" } ``` ``` -------------------------------- ### POST /passwordless_auth - Magic Link Passwordless Authentication Source: https://context7.com/workos/python-flask-example-applications/llms.txt Creates a passwordless authentication session using magic links sent via email. This provides a secure, user-friendly alternative to traditional password-based authentication. ```APIDOC ## POST /passwordless_auth ### Description Creates a passwordless authentication session using magic links sent via email. ### Method POST ### Endpoint /passwordless_auth ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. ### Request Example ```json { "email": "user@example.com" } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message. #### Response Example ```json { "message": "Check your email at user@example.com" } ``` ``` -------------------------------- ### GET/POST /launch_admin_portal - Admin Portal Link Generation Source: https://context7.com/workos/python-flask-example-applications/llms.txt Generates a temporary, secure link to the WorkOS Admin Portal. This portal allows customers to configure SSO, Directory Sync, Audit Logs, or Log Streams through a self-service interface. ```APIDOC ## GET/POST /launch_admin_portal ### Description Generates a temporary link to the WorkOS Admin Portal where customers can configure SSO, Directory Sync, Audit Logs, or Log Streams. The portal provides a self-service interface for enterprise IT administrators. ### Method GET, POST ### Endpoint /launch_admin_portal ### Parameters #### Query Parameters - **intent** (string) - Required - Specifies the intended feature for the Admin Portal ('audit_logs', 'dsync', 'log_streams', 'sso'). ### Response #### Success Response (302 Redirect) Redirects the user to the generated WorkOS Admin Portal link. #### Response Example ``` Redirect to: [WorkOS Admin Portal Link] ``` #### Error Response (400 Bad Request) Returned if the 'intent' parameter is missing or invalid. #### Response Example ``` Missing intent parameter ``` OR ``` Invalid intent parameter ``` ``` -------------------------------- ### List Directories with Pagination - Python Flask Source: https://context7.com/workos/python-flask-example-applications/llms.txt Lists all configured directory sync connections using the WorkOS SDK with pagination support. It retrieves directory data and pagination cursors for navigating through results. Dependencies include Flask and the WorkOS Python client. ```python from flask import Flask, request import workos import os app = Flask(__name__) # Initialize WorkOS client workos.api_key = os.getenv("WORKOS_API_KEY") workos_client = workos.WorkOS(token=os.getenv("WORKOS_API_KEY")) @app.route("/") def home(): before = request.args.get("before") after = request.args.get("after") # List directories with pagination directories = workos_client.directory_sync.list_directories( before=before, after=after, limit=5 ) # Extract pagination cursors before = directories.list_metadata.before after = directories.list_metadata.after return { "directories": [d.dict() for d in directories.data], "before": before, "after": after } ``` -------------------------------- ### POST /challenge_factor - MFA Challenge Creation Source: https://context7.com/workos/python-flask-example-applications/llms.txt Initiates an MFA challenge for a registered authentication factor. For SMS, sends a code to the user's phone. For TOTP, prepares the system to verify a code from the authenticator app. ```APIDOC ## POST /challenge_factor ### Description Initiates an MFA challenge for a registered authentication factor. ### Method POST ### Endpoint /challenge_factor ### Parameters #### Request Body (Conditional) - **sms_message** (string) - Required if factor_type is 'sms' - The custom message to send with the SMS code. ### Response #### Success Response (200) - **challenge_id** (string) - The ID of the newly created challenge. - **status** (string) - The status of the challenge (pending). #### Response Example ```json { "challenge_id": "chlg_klmnopqrs", "status": "pending" } ``` ``` -------------------------------- ### Stop Flask Development Server (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-sso-example/README.md Stops the running Flask development server by pressing CTRL+C in the terminal. ```bash CTRL + c ``` -------------------------------- ### MFA Challenge Creation (Python) Source: https://context7.com/workos/python-flask-example-applications/llms.txt Initiates an MFA challenge for a registered authentication factor (SMS or TOTP). It stores the challenge ID for subsequent verification. Requires the WorkOS SDK and Flask session management. ```python from flask import session @app.route("/challenge_factor", methods=["POST"]) def challenge_factor(): factor_type = session["current_factor_type"] if factor_type == "sms": message = request.form["sms_message"] # Create SMS challenge with custom message challenge = workos_client.mfa.challenge_factor( authentication_factor_id=session["current_factor"], sms_template=message, ) elif factor_type == "totp": # Create TOTP challenge challenge = workos_client.mfa.challenge_factor( authentication_factor_id=session["current_factor"], ) # Store challenge ID for verification session["challenge_id"] = challenge.id session.modified = True return {"challenge_id": challenge.id, "status": "pending"} ``` -------------------------------- ### Audit Logs - Retrieve Export Source: https://context7.com/workos/python-flask-example-applications/llms.txt Retrieves the download URL for a completed audit log export. Exports are processed asynchronously, so the URL may not be immediately available. ```APIDOC ## GET /download_export ### Description Retrieves the download URL for a completed audit log export. Exports are processed asynchronously, so the URL may not be immediately available. ### Method GET ### Endpoint /download_export ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example (No request body or parameters needed for this endpoint, relies on session data) ### Response #### Success Response (200) - Redirects to the export download URL if the export is ready. #### Pending Response (202) - **status** (string) - Indicates the export is still processing. - **message** (string) - A message indicating the export is pending. #### Error Response (400) - **status** (string) - Indicates an error occurred. - **state** (string) - The state of the export job when the error occurred. #### Response Example (Success) (Redirects to a URL) #### Response Example (Pending) ```json { "status": "pending", "message": "Export is still processing" } ``` #### Response Example (Error) ```json { "status": "error", "state": "failed" } ``` ``` -------------------------------- ### Source Environment Variables (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md Loads the environment variables defined in the .env file into the current shell session, making them accessible to the application. ```bash source .env ``` -------------------------------- ### Configure Environment Variables in .env (Bash) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-sso-example/README.md Defines essential environment variables within the '.env' file, including WorkOS API key, Client ID, and an application secret key. These are necessary for WorkOS integration. ```bash WORKOS_API_KEY= WORKOS_CLIENT_ID= APP_SECRET_KEY= ``` -------------------------------- ### Flask Debug Mode Configuration (Python) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-directory-sync-example/README.md Demonstrates how to toggle the Flask application's debug mode in 'app.py'. Debug mode is useful for troubleshooting but must be disabled for WorkOS API connections. ```python # In app.py DEBUG = False # Set to True for troubleshooting, False for API connection ``` -------------------------------- ### Events API - List Events Source: https://context7.com/workos/python-flask-example-applications/llms.txt Lists events from WorkOS for monitoring directory sync changes and other system activities. Supports filtering by event type and pagination. ```APIDOC ## GET /events ### Description Lists events from WorkOS for monitoring directory sync changes and other system activities. Supports filtering by event type and pagination. ### Method GET ### Endpoint /events ### Parameters #### Path Parameters None #### Query Parameters - **after** (string) - Optional - Retrieves events that occurred after the specified event ID. #### Request Body None ### Request Example ``` GET /events?after=evt_12345abcde ``` ### Response #### Success Response (200) - **events** (array) - A list of event objects. - **id** (string) - The unique ID of the event. - **event** (string) - The type of the event. - **data** (object) - The data associated with the event. - **created_at** (string) - ISO 8601 timestamp of when the event was created. - **after** (string) - The cursor for the next page of results. #### Response Example ```json { "events": [ { "id": "evt_12345abcde", "event": "dsync.activated", "data": { "id": "dsync_01GBSZZB3M234S971V89T5X7A5", "directory_id": "dir_01GBSZZB3M234S971V89T5X7A5", "state": "active" }, "created_at": "2023-10-27T10:00:00Z" } ], "after": "evt_67890fghij" } ``` ``` -------------------------------- ### WorkOS MFA TOTP Flow Notes Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-mfa-example/README.md Provides notes on the TOTP MFA flow, including the requirement to use a third-party authenticator app and a limitation on storing only one TOTP connection at a time due to browser cookie size constraints. ```text TOTP: This type of authentication requires the use of a 3rd party authentication app (1Password, Authy, Google Authenticator, Microsoft Authenticator, Duo, etc). Scan the QR code from the Factor Details page to create the corresponding factor in the 3rd party app, then enter the time-based password when prompted in this MFA application. TOTP NOTE - Since all storage is being done via browser cookies, only 1 TOTP type connection can be added at a time to this app due to limitations on the size of the cookies that browsers can store. This is due to the size of the QR code. ``` -------------------------------- ### Create or Retrieve Organization with Verified Domains Source: https://context7.com/workos/python-flask-example-applications/llms.txt Creates a new organization with specified domains or retrieves an existing one if a matching domain is found. This is crucial for multi-tenant applications managing enterprise customers. It requires organization name and a list of domains. ```python from workos.types import DomainDataInput @app.route("/provision_enterprise", methods=["POST"]) def provision_enterprise(): organization_name = request.form["org"] organization_domains = request.form["domain"].split() # Check if organization with domain already exists orgs = workos_client.organizations.list_organizations( domains=organization_domains ) if len(orgs.data) > 0: org_id = orgs.data[0].id else: # Create domain data with verified state domain_data = list( map( lambda domain: DomainDataInput(domain=domain, state="verified"), organization_domains, ) ) # Create new organization organization = workos_client.organizations.create_organization( name=organization_name, domain_data=domain_data, ) org_id = organization.id return f"Organization ID: {org_id}" ``` -------------------------------- ### MFA SMS Enrollment (Python) Source: https://context7.com/workos/python-flask-example-applications/llms.txt Enrolls a user in SMS-based two-factor authentication by registering their phone number. It stores the enrolled factor and returns its ID. Requires the WorkOS SDK and Flask session management. ```python from flask import session @app.route("/enroll_sms_factor", methods=["POST"]) def enroll_sms_factor(): factor_type = request.form.get("type") phone_number = request.form.get("phone_number") if factor_type != "sms": return "Invalid factor type", 400 # Enroll SMS factor new_factor = workos_client.mfa.enroll_factor( type=factor_type, phone_number=phone_number ) # Store factor in session session["factor_list"].append(new_factor.dict()) session.modified = True return { "factor_id": new_factor.id, "type": new_factor.type, "phone_number": new_factor.sms.phone_number } ``` -------------------------------- ### Passwordless Authentication with Magic Links (Python) Source: https://context7.com/workos/python-flask-example-applications/llms.txt Creates a passwordless authentication session using magic links sent via email. It handles session creation and subsequent code exchange for user profile retrieval. Requires the WorkOS SDK. ```python from flask import Flask, request # Assuming workos_client is initialized elsewhere # import workos # workos_client = workos.WorkOS(token='YOUR_API_KEY') app = Flask(__name__) @app.route("/passwordless_auth", methods=["POST"]) def passwordless_auth(): email = request.form["email"] redirect_uri = "http://localhost:5000/success" # Create passwordless session session = workos_client.passwordless.create_session( email=email, type="MagicLink", redirect_uri=redirect_uri ) # The magic link can be sent via your own email service magic_link = session.link print(f"Magic link for {email}: {magic_link}") return f"Check your email at {email}" @app.route("/success") def success(): code = request.args.get("code") if not code: return "No code provided" # Exchange code for user profile profile = workos_client.sso.get_profile_and_token(code) return f"Welcome {profile.profile.email}" ``` -------------------------------- ### POST /auth - Initiate SSO Authentication Source: https://context7.com/workos/python-flask-example-applications/llms.txt Initiates the Single Sign-On (SSO) authentication flow. It generates an authorization URL for SAML or OAuth providers like Google and Microsoft, supporting both organization-based SAML and provider-based OAuth authentication. ```APIDOC ## POST /auth ### Description Initiates the SSO authentication flow by generating an authorization URL for either SAML or OAuth providers (Google, Microsoft). The function handles both organization-based SAML authentication and provider-based OAuth authentication. ### Method POST ### Endpoint /auth ### Parameters #### Query Parameters - **login_method** (string) - Required - Specifies the login method ('saml', 'GoogleOAuth', 'MicrosoftOAuth'). ### Request Body ```json { "login_method": "saml | GoogleOAuth | MicrosoftOAuth" } ``` ### Response #### Success Response (302 Redirect) Redirects the user to the WorkOS authorization URL. #### Response Example ``` Redirect to: [WorkOS Authorization URL] ``` ``` -------------------------------- ### MFA Challenge Verification (Python) Source: https://context7.com/workos/python-flask-example-applications/llms.txt Verifies a user-provided code against an active MFA challenge. It uses the stored challenge ID and the submitted code to validate the MFA attempt. Requires the WorkOS SDK and Flask session management. ```python from flask import session @app.route("/verify_factor", methods=["POST"]) def verify_factor(): # Build code from form inputs (e.g., 6-digit code split across inputs) code = "".join(request.form.values()) challenge_id = session["challenge_id"] # Verify the challenge verify_result = workos_client.mfa.verify_challenge( authentication_challenge_id=challenge_id, code=code, ) if verify_result.valid: return { "status": "success", "valid": verify_result.valid, "challenge": verify_result.challenge.dict() } else: return {"status": "failed", "valid": False}, 401 ``` -------------------------------- ### Audit Logs - Create Event Source: https://context7.com/workos/python-flask-example-applications/llms.txt Creates a custom audit log event to track important actions within your application. Audit logs provide a tamper-proof record of security-relevant activities. ```APIDOC ## POST /send_event ### Description Creates a custom audit log event to track important actions within your application. Audit logs provide a tamper-proof record of security-relevant activities. ### Method POST ### Endpoint /send_event ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **action** (string) - Required - The type of action being logged. - **version** (integer) - Required - The version of the audit log event schema. - **occurred_at** (string) - Required - ISO 8601 timestamp of when the event occurred. - **actor** (object) - Required - Information about the actor performing the action. - **type** (string) - Required - The type of the actor (e.g., 'user'). - **name** (string) - Required - The name of the actor. - **id** (string) - Required - The ID of the actor. - **targets** (array) - Optional - Information about the targets affected by the action. - **type** (string) - Required - The type of the target (e.g., 'organization'). - **name** (string) - Required - The name of the target. - **id** (string) - Required - The ID of the target. - **context** (object) - Optional - Additional context about the event. - **location** (string) - Optional - The IP address from which the action occurred. - **user_agent** (string) - Optional - The User-Agent string of the client. ### Request Example ```json { "action": "user.organization_deleted", "version": 1, "occurred_at": "2023-10-27T10:00:00Z", "actor": { "type": "user", "name": "Admin User", "id": "user_01GBNJC3MX9ZZJW1FSTF4C5938" }, "targets": [ { "type": "organization", "name": "Acme Corporation", "id": "team_01GBNJD4MKHVKJGEWK42JNMBGS" } ], "context": { "location": "123.123.123.123", "user_agent": "Chrome/104.0.0.0" } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates that the event was created successfully. #### Response Example ```json { "status": "event_created" } ``` ``` -------------------------------- ### JavaScript Snackbar Notification Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/templates/send_events.html A JavaScript function to display a snackbar notification with a timed auto-hide functionality. It manipulates CSS classes to show and hide the notification element. ```javascript function showSnackbar() { var x = document.getElementById("snackbar"); x.className = "show"; setTimeout(function(){ x.className = x.className.replace("show", ""); }, 500); } ``` -------------------------------- ### Handle WorkOS Webhooks with Flask and Socket.IO Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-directory-sync-example/templates/webhooks.html This JavaScript code snippet sets up a client-side connection to a Flask application using Socket.IO to receive and display WorkOS webhooks in real-time. It formats the incoming JSON data and appends it to the web page, managing UI elements based on the number of webhooks received. Dependencies include Socket.IO client library. ```javascript var counter = 0 var webhooksView = document.getElementById('webhooks-view') var clearButtonDiv = document.getElementById('clear_button_div') var clearButton = document.getElementById('clear_button') var tutorialButton = document.getElementById('tutorial_button') var socket = io("http://localhost:5000") socket.on('connect', function () { console.log('socket connection successful') }) socket.on('webhook_received', (data) => { var formattedData = JSON.stringify(JSON.parse(data), null, 2) console.log(formattedData) webhooksView.classList.add("webhooks_container") webhooksView.insertAdjacentHTML("afterbegin", "
Webhook received at: " + new Date().toISOString() + "
" + "
" + "
" + "" + formattedData + "" + "
" + "
" + "
" + "
" ); if (counter < 1) { clearButtonDiv.classList.remove('login_button') clearButtonDiv.classList.add('flex_right') clearButton.classList.remove('hidden') tutorialButton.classList.add('hidden') counter++ } }) ``` -------------------------------- ### Audit Logs - Create Export Source: https://context7.com/workos/python-flask-example-applications/llms.txt Creates a CSV export of audit log events for a specific date range with optional filtering. Useful for compliance reporting and security audits. ```APIDOC ## POST /export_events ### Description Creates a CSV export of audit log events for a specific date range with optional filtering. Useful for compliance reporting and security audits. ### Method POST ### Endpoint /export_events ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **filter-actions** (string) - Optional - Comma-separated list of actions to filter by. - **filter-actors** (string) - Optional - Comma-separated list of actor names to filter by. - **filter-targets** (string) - Optional - Comma-separated list of target names to filter by. ### Request Example ```json { "filter-actions": "user.login,user.logout", "filter-actors": "admin", "filter-targets": "Acme Corporation" } ``` ### Response #### Success Response (200) - **export_id** (string) - The ID of the created export job. - **state** (string) - The current state of the export job (e.g., 'pending'). #### Response Example ```json { "export_id": "export_01GBSZZB3M234S971V89T5X7A5", "state": "pending" } ``` ``` -------------------------------- ### WorkOS MFA SMS Flow Customization Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-mfa-example/README.md Demonstrates how to customize the SMS message for WorkOS MFA. The message must include '{{code}}' for WorkOS to generate and insert a random code. ```text SMS: The SMS flow requires you to send a code via text message. You can customize this message, but the message must include the string "{{code}}". This string of characters tells the WorkOS API to generate a random code that will be populated automatically. If "{{code}}" is not included in the message, the authentication cannot be completed. ``` -------------------------------- ### Display and Select Events in JavaScript Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-directory-sync-example/templates/events.html JavaScript functions to manage the display and selection of events. It handles adding/removing 'selected_event' classes and toggling the visibility of event details. It assumes a pre-selected event on page load. ```javascript function deselectEvent(element) { if (!element) { return; } element.classList.remove('selected_event'); const eventId = element.getAttribute('data-event-id'); const eventBody = document.getElementById(eventId); eventBody.hidden = true; } function selectEvent(element) { if (!element) { return; } element.classList.add('selected_event'); const eventId = element.getAttribute('data-event-id'); const eventBody = document.getElementById(eventId); eventBody.hidden = false; } function displayEvent(element) { const previousSelectedEvent = selectedEvent; deselectEvent(previousSelectedEvent); selectedEvent = element; selectEvent(selectedEvent); } let selectedEvent = document.getElementsByClassName('event_summary')[0]; displayEvent(selectedEvent); ``` -------------------------------- ### Initiate SSO Authorization with WorkOS Source: https://context7.com/workos/python-flask-example-applications/llms.txt Initiates the SSO authentication flow by generating an authorization URL. It supports both organization-based SAML and provider-based OAuth (Google, Microsoft) authentication. Requires WorkOS API key, client ID, and a redirect URI. ```python from flask import Flask, redirect, url_for, request import workos import os # Initialize WorkOS client workos_client = workos.WorkOSClient( api_key=os.getenv("WORKOS_API_KEY"), client_id=os.getenv("WORKOS_CLIENT_ID"), ) CUSTOMER_ORGANIZATION_ID = "org_01EHQMYV6MBK39QC5PZXHY59C3" @app.route("/auth", methods=["POST"]) def auth(): login_type = request.form.get("login_method") if login_type not in ("saml", "GoogleOAuth", "MicrosoftOAuth"): return redirect("/") redirect_uri = url_for("auth_callback", _external=True) # For SAML, use organization_id; for OAuth, use provider if login_type == "saml": authorization_url = workos_client.sso.get_authorization_url( redirect_uri=redirect_uri, organization_id=CUSTOMER_ORGANIZATION_ID ) else: authorization_url = workos_client.sso.get_authorization_url( redirect_uri=redirect_uri, provider=login_type ) return redirect(authorization_url) ``` -------------------------------- ### JavaScript Tabbed Interface Management Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/templates/send_events.html JavaScript code to manage a tabbed interface, allowing users to switch between different content panels. It uses local storage to remember the last active tab and handles click events for tab switching. ```javascript const tabs = document.querySelectorAll('\\[data-tab-target\\]') const tabContents = document.querySelectorAll('\\[data-tab-content\\]') tabs.forEach(tab => { tab.addEventListener('click', () => { const target = document.querySelector(tab.dataset.tabTarget) tabContents.forEach(tabContent => { tabContent.classList.remove('active') }) tabs.forEach(tab => { tab.classList.remove('active') }) tab.classList.add('active') target.classList.add('active') localStorage.setItem('selectedTab', target.getAttribute('name')) }) }) tabs.forEach(tab => { if(localStorage.getItem('selectedTab') != undefined || null) { if(tab.getAttribute('name') == localStorage.getItem('selectedTab')){ const target = document.querySelector(tab.dataset.tabTarget) tabContents.forEach(tabContent => { tabContent.classList.remove('active') }) tabs.forEach(tab => { tab.classList.remove('active') }) tab.classList.add('active') target.classList.add('active') } } }) ``` -------------------------------- ### Generate WorkOS Admin Portal Link Source: https://context7.com/workos/python-flask-example-applications/llms.txt Generates a temporary link to the WorkOS Admin Portal for configuring SSO, Directory Sync, Audit Logs, or Log Streams. This function requires an organization ID and an intent parameter ('audit_logs', 'dsync', 'log_streams', 'sso'). ```python from flask import redirect, request @app.route("/launch_admin_portal", methods=["GET", "POST"]) def launch_admin_portal(): intent = request.args.get("intent") if intent is None: return "Missing intent parameter", 400 if intent not in ("audit_logs", "dsync", "log_streams", "sso"): return "Invalid intent parameter", 400 # Generate portal link for the organization portal_link = workos_client.portal.generate_link( organization_id=org_id, intent=intent ) return redirect(portal_link.link) ``` -------------------------------- ### List Directory Users - Python Flask Source: https://context7.com/workos/python-flask-example-applications/llms.txt Retrieves all users from a specific directory sync connection, including their attributes synced from the identity provider. This function is useful for displaying synchronized user information. It requires a directory ID as input and returns a list of user objects. ```python from flask import Flask, request import workos import os app = Flask(__name__) # Initialize WorkOS client workos.api_key = os.getenv("WORKOS_API_KEY") workos_client = workos.WorkOS(token=os.getenv("WORKOS_API_KEY")) @app.route("/users") def directory_users(): directory_id = request.args.get("id") # List users in directory users = workos_client.directory_sync.list_users( directory_id=directory_id, limit=100 ) return { "users": [ { "id": user.id, "email": user.emails[0].value if user.emails else None, "first_name": user.first_name, "last_name": user.last_name, "state": user.state } for user in users.data ] } ``` -------------------------------- ### Configure Environment Variables (.env file) Source: https://github.com/workos/python-flask-example-applications/blob/main/python-flask-audit-logs-example/README.md Creates and opens a .env file to store sensitive environment variables like WorkOS API Key, Client ID, and an App Secret Key. These variables are essential for the application's functionality. ```bash touch .env nano .env ```