### Initialize WorkOS Client in Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Initializes the WorkOS client using an API key. This example also demonstrates how to access various WorkOS API modules and optionally configure a custom API hostname and port for testing. ```kotlin import com.workos.WorkOS // Initialize WorkOS client val workos = WorkOS("sk_test_your_api_key_here") // Access API modules val sso = workos.sso val userManagement = workos.userManagement val organizations = workos.organizations val directorySync = workos.directorySync val auditLogs = workos.auditLogs val webhooks = workos.webhooks val portal = workos.portal val events = workos.events // Optional: Configure custom endpoint (for testing) workos.apiHostname = "api.workos.dev" workos.https = true workos.port = 8080 ``` -------------------------------- ### Generate WorkOS Portal Link (Kotlin) Source: https://context7.com/workos/workos-kotlin/llms.txt Generates a portal link for initiating SSO setup or Directory Sync configuration with WorkOS. Requires the WorkOS API key, organization ID, intent type, and return/success URLs. Outputs a portal link for user redirection. ```kotlin import com.workos.WorkOS import com.workos.portal.PortalApi import com.workos.portal.models.Intent val workos = WorkOS("sk_test_your_api_key") // Generate SSO setup portal link val ssoLinkOptions = PortalApi.GeneratePortalLinkOptions.builder() .organization("org_01H1QPFZ3X") .intent(Intent.Sso) .returnUrl("https://yourapp.com/admin") .successUrl("https://yourapp.com/setup-complete") .build() val ssoLink = workos.portal.generateLink(ssoLinkOptions) println("SSO Portal link: ${ssoLink.link}") // Generate Directory Sync portal link val dsyncLinkOptions = PortalApi.GeneratePortalLinkOptions.builder() .organization("org_01H1QPFZ3X") .intent(Intent.Dsync) .returnUrl("https://yourapp.com/admin") .build() val dsyncLink = workos.portal.generateLink(dsyncLinkOptions) println("Directory Sync Portal link: ${dsyncLink.link}") // Redirect user to portal link for self-service configuration ``` -------------------------------- ### Authenticate User with Password - Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Provides a Kotlin example for authenticating a user with their email and password using the WorkOS SDK. This includes handling potential authentication failures. Upon success, it returns access and refresh tokens, along with user details. Requires client ID and API key. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") try { val authentication = workos.userManagement.authenticateWithPassword( clientId = "client_your_client_id", email = "user@example.com", password = "UserPassword123!" ) println("Access Token: ${authentication.accessToken}") println("Refresh Token: ${authentication.refreshToken}") println("User ID: ${authentication.user.id}") println("User Email: ${authentication.user.email}") // Store tokens securely for session management } catch (e: Exception) { println("Authentication failed: ${e.message}") } ``` -------------------------------- ### Get and Delete SSO Connection - Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Provides examples for retrieving a specific SSO connection by its ID and deleting an SSO connection using the WorkOS Kotlin SDK. This operation requires the WorkOS API key and the connection ID. Output includes connection details upon retrieval. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") // Get specific connection val connection = workos.sso.getConnection("conn_01H1QPFZ3X") println("Connection Name: ${connection.name}") println("Organization: ${connection.organizationId}") // Delete connection workos.sso.deleteConnection("conn_01H1QPFZ3X") ``` -------------------------------- ### WorkOS Kotlin: Get, Update, and Delete Organization Source: https://context7.com/workos/workos-kotlin/llms.txt Illustrates how to retrieve an existing organization's details, update its name and domain data, and subsequently delete it. Requires WorkOS API key and organization ID. ```kotlin import com.workos.WorkOS import com.workos.organizations.OrganizationsApi import com.workos.organizations.types.OrganizationDomainDataOptions val workos = WorkOS("sk_test_your_api_key") // Get organization val org = workos.organizations.getOrganization("org_01H1QPFZ3X") println("Organization: ${org.name}") println("Created: ${org.createdAt}") // Update organization val newDomainData = listOf( OrganizationDomainDataOptions( domain = "newdomain.com", state = "pending" ) ) val updateOptions = OrganizationsApi.UpdateOrganizationOptions.builder() .name("Updated Corp Name") .domainData(newDomainData) .build() val updatedOrg = workos.organizations.updateOrganization( id = org.id, options = updateOptions ) println("Updated organization: ${updatedOrg.name}") // Delete organization workos.organizations.deleteOrganization("org_01H1QPFZ3X") ``` -------------------------------- ### Authenticate User with Authorization Code - Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Demonstrates how to authenticate a user after they have been redirected back from an OAuth provider, using the authorization code. This Kotlin example requires the client ID and the authorization code obtained from the callback. It returns user details and organization ID. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") // After OAuth redirect val code = "authorization_code_from_callback" val authentication = workos.userManagement.authenticateWithCode( clientId = "client_your_client_id", code = code ) println("Authenticated user: ${authentication.user.email}") println("Organization ID: ${authentication.organizationId}") println("Access token expires: ${authentication.accessToken}") ``` -------------------------------- ### Get and Delete Directory in WorkOS Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Retrieves details for a specific directory using its ID and subsequently deletes it. Requires the directory ID as input and outputs the directory's name and type before deletion. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") // Get directory details val directory = workos.directorySync.getDirectory("directory_01H1QPFZ3X") println("Directory: ${directory.name}") println("Type: ${directory.type}") // Delete directory workos.directorySync.deleteDirectory("directory_01H1QPFZ3X") ``` -------------------------------- ### Get User Profile with Access Token in Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Retrieves a user's profile information using their access token. This is useful for making authenticated requests after the initial sign-in flow. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") val accessToken = "user_access_token" val profile = workos.sso.getProfile(accessToken) println("Profile Email: ${profile.email}") println("Profile ID: ${profile.id}") ``` -------------------------------- ### Get and Update User Details - Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Illustrates how to retrieve a user by their ID, update their details (like name and email verification status), and then delete the user using the WorkOS Kotlin SDK. Requires the WorkOS API key and the user ID. The update operation returns the modified user object. ```kotlin import com.workos.WorkOS import com.workos.usermanagement.types.UpdateUserOptions val workos = WorkOS("sk_test_your_api_key") // Get user by ID val user = workos.userManagement.getUser("user_01H1QPFZ3X") println("Current email: ${user.email}") // Update user details val updateOptions = UpdateUserOptions( firstName = "Jane", lastName = "Smith", emailVerified = true ) val updatedUser = workos.userManagement.updateUser( userId = user.id, options = updateOptions ) println("Updated name: ${updatedUser.firstName} ${updatedUser.lastName}") // Delete user workos.userManagement.deleteUser(user.id) ``` -------------------------------- ### Refresh Access Token - Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Provides a Kotlin example for refreshing an access token using a refresh token. This is useful when the original access token expires. The function requires the client ID and the refresh token, and optionally an organization ID. It returns new access and refresh tokens. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") val refreshToken = "stored_refresh_token" val refreshAuth = workos.userManagement.authenticateWithRefreshToken( clientId = "client_your_client_id", refreshToken = refreshToken, organizationId = "org_01H1QPFZ3X" // Optional ) println("New access token: ${refreshAuth.accessToken}") println("New refresh token: ${refreshAuth.refreshToken}") // Refresh tokens are single-use, store the new one ``` -------------------------------- ### WorkOS Kotlin: MFA Enrollment and Authentication Source: https://context7.com/workos/workos-kotlin/llms.txt Demonstrates how to enroll users in TOTP MFA, list their authentication factors, and authenticate using TOTP. Requires WorkOS API key and user/client IDs. ```kotlin import com.workos.WorkOS import com.workos.usermanagement.types.EnrolledAuthenticationFactorOptions val workos = WorkOS("sk_test_your_api_key") // Enroll user in TOTP MFA val enrollOptions = EnrolledAuthenticationFactorOptions( type = "totp" ) val authFactor = workos.userManagement.enrollAuthFactor( id = "user_01H1QPFZ3X", options = enrollOptions ) println("Auth factor ID: ${authFactor.id}") println("Type: ${authFactor.type}") println("TOTP QR code: ${authFactor.totp?.qrCode}") println("TOTP secret: ${authFactor.totp?.secret}") // List user's auth factors val factors = workos.userManagement.listAuthFactors("user_01H1QPFZ3X") factors.data.forEach { factor -> println("Factor: ${factor.type} - ${factor.id}") } // Authenticate with TOTP val totpAuth = workos.userManagement.authenticateWithTotp( clientId = "client_your_client_id", code = "123456", authenticationChallengeId = "auth_challenge_01H1QPFZ3X", pendingAuthenticationToken = "pending_token" ) ``` -------------------------------- ### Initialize WorkOS Client in Java Source: https://github.com/workos/workos-kotlin/blob/main/README.md This Java code snippet shows the basic initialization of the WorkOS client using an API key. The initialized 'workos' object can then be used to access various WorkOS API domains such as Directory Sync, SSO, and User Management. ```java import com.workos.WorkOS; WorkOS workos = new WorkOS("WORKOS_API_KEY"); // Access different domains of the WorkOS API through the following properties // workos.directorySync // workos.organizations // workos.passwordless // workos.portal // workos.sso // workos.userManagement // workos.webhooks ``` -------------------------------- ### WorkOS Kotlin: Create Organization Source: https://context7.com/workos/workos-kotlin/llms.txt Demonstrates how to create a new organization with specified name and domain data. Requires WorkOS API key and an idempotency key for the request. ```kotlin import com.workos.WorkOS import com.workos.organizations.OrganizationsApi import com.workos.organizations.types.OrganizationDomainDataOptions val workos = WorkOS("sk_test_your_api_key") // Create organization with domain data val domainData = listOf( OrganizationDomainDataOptions( domain = "example.com", state = "verified" ) ) val options = OrganizationsApi.CreateOrganizationOptions.builder() .name("Example Corp") .domainData(domainData) .build() val requestOptions = OrganizationsApi.CreateOrganizationRequestOptions.builder() .idempotencyKey("unique-key-12345") .build() val organization = workos.organizations.createOrganization(options, requestOptions) println("Organization created: ${organization.id}") println("Name: ${organization.name}") println("Domains: ${organization.domains?.map { it.domain }?.joinToString(", ")}") ``` -------------------------------- ### Create User with Password - Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Shows how to create a new user with a password using the WorkOS Kotlin SDK. This function requires the WorkOS API key and user details like email, password, first name, last name, and email verification status. Returns the created user's ID and details. ```kotlin import com.workos.WorkOS import com.workos.usermanagement.types.CreateUserOptions val workos = WorkOS("sk_test_your_api_key") val createOptions = CreateUserOptions( email = "user@example.com", password = "SecurePassword123!", firstName = "John", lastName = "Doe", emailVerified = true ) val user = workos.userManagement.createUser(createOptions) println("User created: ${user.id}") println("Email: ${user.email}") println("Created at: ${user.createdAt}") ``` -------------------------------- ### WorkOS Kotlin: List Organizations with Filtering and Pagination Source: https://context7.com/workos/workos-kotlin/llms.txt Shows how to list organizations, filter by domain, set limits, sort results, and handle pagination for large result sets. Requires WorkOS API key. ```kotlin import com.workos.WorkOS import com.workos.organizations.OrganizationsApi import com.workos.common.models.Order val workos = WorkOS("sk_test_your_api_key") val options = OrganizationsApi.ListOrganizationsOptions.builder() .domains(listOf("example.com", "test.com")) .limit(10) .order(Order.Desc) .build() val orgs = workos.organizations.listOrganizations(options) orgs.data.forEach { org -> println("Org: ${org.name} (${org.id})") org.domains?.forEach { domain -> println(" Domain: ${domain.domain} - ${domain.state}") } } // Navigate pagination if (orgs.listMetadata?.after != null) { val nextOptions = OrganizationsApi.ListOrganizationsOptions.builder() .after(orgs.listMetadata.after) .build() val nextPage = workos.organizations.listOrganizations(nextOptions) } ``` -------------------------------- ### List SSO Connections with Filters - Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Demonstrates how to list SSO connections using the WorkOS Kotlin SDK. It shows how to apply filters such as organization ID, connection type, and limit. The code also includes pagination logic to retrieve subsequent pages of results. Requires the WorkOS API key. ```kotlin import com.workos.WorkOS import com.workos.sso.SsoApi val workos = WorkOS("sk_test_your_api_key") // List connections with filters val options = SsoApi.ListConnectionsOptions.builder() .organizationId("org_01H1QPFZ3X") .connectionType("OktaSAML") .limit(10) .build() val connections = workos.sso.listConnections(options) connections.data.forEach { connection -> println("Connection: ${connection.name}") println("Type: ${connection.connectionType}") println("State: ${connection.state}") println("Domains: ${connection.domains?.joinToString(", ")}") } // Check if there are more results if (connections.listMetadata?.after != null) { val nextPage = SsoApi.ListConnectionsOptions.builder() .after(connections.listMetadata.after) .build() val moreConnections = workos.sso.listConnections(nextPage) } ``` -------------------------------- ### List Users with Filtering - Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Demonstrates listing users with various filtering options using the WorkOS Kotlin SDK. Supports filtering by email, organization ID, and setting a limit for the number of results. Includes pagination information. Requires the WorkOS API key. ```kotlin import com.workos.WorkOS import com.workos.usermanagement.types.ListUsersOptions val workos = WorkOS("sk_test_your_api_key") val listOptions = ListUsersOptions( email = "user@example.com", organizationId = "org_01H1QPFZ3X", limit = 20 ) val users = workos.userManagement.listUsers(listOptions) users.data.forEach { user -> println("User: ${user.email} (${user.id})") println("Name: ${user.firstName} ${user.lastName}") println("Email verified: ${user.emailVerified}") } // Pagination println("Has more: ${users.listMetadata?.after != null}") ``` -------------------------------- ### WorkOS Kotlin: Authorization and Logout URLs Source: https://context7.com/workos/workos-kotlin/llms.txt Shows how to generate authorization URLs for OAuth providers, retrieve JWKS URLs for token verification, and construct logout URLs. Requires WorkOS API key and client ID. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") // Build authorization URL val authUrl = workos.userManagement.getAuthorizationUrl( clientId = "client_your_client_id", redirectUri = "https://yourapp.com/callback" ) .provider("GoogleOAuth") .state("random_state") .build() // Get JWKS URL for token verification val jwksUrl = workos.userManagement.getJwksUrl("client_your_client_id") println("JWKS URL: $jwksUrl") // Get logout URL val logoutUrl = workos.userManagement.getLogoutUrl( sessionId = "session_01H1QPFZ3X", returnTo = "https://yourapp.com/logged-out" ) println("Logout URL: $logoutUrl") ``` -------------------------------- ### Handle WorkOS Kotlin SDK Exceptions Source: https://context7.com/workos/workos-kotlin/llms.txt This code snippet demonstrates how to catch and process various exceptions that can occur when interacting with the WorkOS Kotlin SDK. It includes specific handling for bad requests, unauthorized access, not found resources, unprocessable entities, and generic server errors, logging relevant details for each exception type. ```kotlin import com.workos.WorkOS import com.workos.common.exceptions.BadRequestException import com.workos.common.exceptions.UnauthorizedException import com.workos.common.exceptions.NotFoundException import com.workos.common.exceptions.UnprocessableEntityException import com.workos.common.exceptions.GenericServerException val workos = WorkOS("sk_test_your_api_key") try { val user = workos.userManagement.getUser("user_invalid_id") } catch (e: BadRequestException) { println("Bad request: ${e.message}") println("Error code: ${e.code}") println("Request ID: ${e.requestId}") e.errors?.forEach { error -> println("Field error: ${error.field} - ${error.code}") } } catch (e: UnauthorizedException) { println("Unauthorized: ${e.message}") println("Request ID: ${e.requestId}") } catch (e: NotFoundException) { println("Resource not found: ${e.message}") println("Request ID: ${e.requestId}") } catch (e: UnprocessableEntityException) { println("Unprocessable: ${e.message}") println("Error code: ${e.code}") e.errors?.forEach { error -> println("Validation error: ${error.message}") } } catch (e: GenericServerException) { println("Server error: ${e.message}") println("Status code: ${e.statusCode}") println("Request ID: ${e.requestId}") } ``` -------------------------------- ### Gradle Kotlin DSL Dependency for WorkOS Kotlin SDK Source: https://context7.com/workos/workos-kotlin/llms.txt This snippet demonstrates how to include the WorkOS Kotlin SDK as a dependency in a Gradle project using the Kotlin DSL. ```kotlin dependencies { implementation("com.workos:workos:4.16.0") } ``` -------------------------------- ### Password Reset Flow Source: https://context7.com/workos/workos-kotlin/llms.txt This section outlines the process for resetting user passwords. It includes creating a password reset token and URL, and then using the token to reset the user's password. ```APIDOC ## Password Reset Flow ### Description Enables users to reset their passwords. This involves generating a password reset token and a unique URL, which the user clicks to complete the reset process. ### Method POST (Implicitly through SDK calls) ### Endpoint `/user_management/password_reset` (for creating) and `/user_management/reset_password` (for resetting) - These are SDK method calls that map to underlying API endpoints. ### Parameters #### Request Body (for `createPasswordReset`) - **email** (string) - Required - The email address of the user requesting a password reset. - **passwordResetUrl** (string) - Required - The URL that will be used to reset the password, which will contain the reset token. #### Request Body (for `resetPassword`) - **token** (string) - Required - The password reset token obtained from the password reset link. - **newPassword** (string) - Required - The new password for the user. ### Request Example (Create Password Reset) ```json { "email": "user@example.com", "passwordResetUrl": "https://yourapp.com/reset-password" } ``` ### Request Example (Reset Password) ```json { "token": "token_from_reset_link", "newPassword": "NewSecurePassword123!" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the password reset request. - **passwordResetToken** (string) - The token used to reset the password. - **user** (object) - Information about the user whose password was reset. - **email** (string) - The email address of the user. #### Response Example (Create Password Reset) ```json { "id": "password_reset_id_123", "passwordResetToken": "a_very_secure_token_abc" } ``` #### Response Example (Reset Password) ```json { "email": "user@example.com" } ``` ``` -------------------------------- ### List Directories in WorkOS Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Fetches a list of directories associated with an organization. Allows filtering by organization ID and setting a limit for the number of results. Outputs directory names, types, states, and organization IDs. ```kotlin import com.workos.WorkOS import com.workos.directorysync.DirectorySyncApi val workos = WorkOS("sk_test_your_api_key") val options = DirectorySyncApi.ListDirectoriesOptions.builder() .organization("org_01H1QPFZ3X") .limit(10) .build() val directories = workos.directorySync.listDirectories(options) directories.data.forEach { directory -> println("Directory: ${directory.name}") println("Type: ${directory.type}") println("State: ${directory.state}") println("Organization: ${directory.organizationId}") } ``` -------------------------------- ### Magic Auth (Passwordless Authentication) Source: https://context7.com/workos/workos-kotlin/llms.txt This section covers the implementation of passwordless authentication using WorkOS Magic Auth. It includes sending a magic authentication code to a user's email and then authenticating the user with that code. ```APIDOC ## Magic Auth (Passwordless Authentication) ### Description Implements passwordless authentication by sending a magic authentication code to a user's email and subsequently authenticating the user with that code. ### Method POST (Implicitly through SDK calls) ### Endpoint `/user_management/magic_auth` (for creating) and `/user_management/authenticate/magic_auth` (for authenticating) - These are SDK method calls that map to underlying API endpoints. ### Parameters #### Request Body (for `createMagicAuth`) - **email** (string) - Required - The email address of the user to send the magic auth code to. #### Request Body (for `authenticateWithMagicAuth`) - **clientId** (string) - Required - Your WorkOS application's client ID. - **email** (string) - Required - The email address of the user attempting to authenticate. - **code** (string) - Required - The magic authentication code received by the user via email. ### Request Example (Create Magic Auth) ```json { "email": "user@example.com" } ``` ### Request Example (Authenticate with Magic Auth) ```json { "clientId": "client_your_client_id", "email": "user@example.com", "code": "123456" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the magic auth request. - **expiresAt** (string) - The timestamp indicating when the magic auth code expires. - **user** (object) - Information about the authenticated user. - **email** (string) - The email address of the authenticated user. #### Response Example (Create Magic Auth) ```json { "id": "magic_auth_req_id_123", "expiresAt": "2023-10-27T10:00:00Z" } ``` #### Response Example (Authenticate with Magic Auth) ```json { "user": { "email": "user@example.com" } } ``` ``` -------------------------------- ### Gradle Groovy DSL Dependency for WorkOS Kotlin SDK Source: https://context7.com/workos/workos-kotlin/llms.txt This snippet shows how to add the WorkOS Kotlin SDK as a dependency in a Gradle project using the Groovy DSL. ```groovy dependencies { implementation 'com.workos:workos:4.16.0' } ``` -------------------------------- ### List WorkOS Events (Kotlin) Source: https://context7.com/workos/workos-kotlin/llms.txt Retrieves a list of WorkOS events, with options to filter by event type, organization ID, limit, and order. Supports pagination to fetch subsequent pages of results. Outputs event details including type, ID, creation timestamp, and data. ```kotlin import com.workos.WorkOS import com.workos.events.EventsApi import com.workos.common.models.Order val workos = WorkOS("sk_test_your_api_key") // List events with filters val options = EventsApi.ListEventsOptions.builder() .events(listOf( "authentication.email_verification_succeeded", "user.created", "connection.activated" )) .organizationId("org_01H1QPFZ3X") .limit(25) .order(Order.Desc) .build() val events = workos.events.listEvents(options) events.data.forEach { event -> println("Event: ${event.event}") println("ID: ${event.id}") println("Created: ${event.createdAt}") println("Data: ${event.data}") } // Pagination if (events.listMetadata?.after != null) { val nextOptions = EventsApi.ListEventsOptions.builder() .after(events.listMetadata.after) .build() val nextPage = workos.events.listEvents(nextOptions) } ``` -------------------------------- ### Invitations API Source: https://context7.com/workos/workos-kotlin/llms.txt Manage user invitations for organizations, including sending, listing, retrieving, and revoking invitations. ```APIDOC ## Invitations API ### Description Handles the management of user invitations to organizations. This includes sending new invitations, listing existing ones, retrieving specific invitations by ID or token, and revoking them. ### Method POST, GET, DELETE (Implicitly through SDK calls) ### Endpoint `/user_management/invitations` (and related SDK methods) - These are SDK method calls that map to underlying API endpoints. ### Parameters #### Request Body (for `sendInvitation`) - **email** (string) - Required - The email address of the user to invite. - **organizationId** (string) - Required - The ID of the organization to invite the user to. - **expiresInDays** (integer) - Optional - Number of days until the invitation expires. - **inviterUserId** (string) - Optional - The ID of the user sending the invitation. - **roleSlug** (string) - Optional - The role slug to assign to the invited user. #### Query Parameters (for `listInvitations`) (No specific query parameters mentioned for basic listing) ### Request Example (Send Invitation) ```json { "email": "newuser@example.com", "organizationId": "org_01H1QPFZ3X", "expiresInDays": 7, "inviterUserId": "user_01H1QPFZ3Y", "roleSlug": "member" } ``` ### Request Example (List Invitations) (No request body) ### Response #### Success Response (200) - **data** (array) - A list of invitations. - **id** (string) - The unique identifier for the invitation. - **token** (string) - The invitation token. - **state** (string) - The current state of the invitation (e.g., "accepted", "pending", "revoked"). - **expiresAt** (string) - The timestamp indicating when the invitation expires. - **email** (string) - The email address of the invited user. - **role** (object) - Information about the invited user's role. - **slug** (string) - The slug of the role. #### Response Example (Send/List/Get Invitation) ```json { "data": [ { "id": "invitation_01H1QPFZ3X", "token": "invite_token_abc123", "state": "pending", "expiresAt": "2023-10-30T10:00:00Z", "email": "newuser@example.com", "role": { "slug": "member" } } ] } ``` ### Actions - **Get Invitation by ID**: `getInvitation(invitationId)` - **Find Invitation by Token**: `findInvitationByToken(token)` - **Revoke Invitation**: `revokeInvitation(invitationId)` ``` -------------------------------- ### WorkOS Kotlin: Invitation Management Source: https://context7.com/workos/workos-kotlin/llms.txt Handle user invitations using the WorkOS Kotlin SDK. This includes sending new invitations, listing existing ones, retrieving specific invitations by ID or token, and revoking invitations. Requires WorkOS API key and organization details. ```kotlin import com.workos.WorkOS import com.workos.usermanagement.types.SendInvitationOptions val workos = WorkOS("sk_test_your_api_key") // Send invitation val invitationOptions = SendInvitationOptions( email = "newuser@example.com", organizationId = "org_01H1QPFZ3X", expiresInDays = 7, inviterUserId = "user_01H1QPFZ3Y", roleSlug = "member" ) val invitation = workos.userManagement.sendInvitation(invitationOptions) println("Invitation sent: ${invitation.id}") println("Token: ${invitation.token}") println("State: ${invitation.state}") println("Expires at: ${invitation.expiresAt}") // List invitations val invitations = workos.userManagement.listInvitations() invitations.data.forEach { inv -> println("Invitation to: ${inv.email} - ${inv.state}") } // Get invitation by ID or token val inviteById = workos.userManagement.getInvitation("invitation_01H1QPFZ3X") val inviteByToken = workos.userManagement.findInvitationByToken("invite_token_abc123") // Revoke invitation val revoked = workos.userManagement.revokeInvitation(invitation.id) println("Invitation revoked: ${revoked.state}") ``` -------------------------------- ### Maven Dependency for WorkOS Kotlin SDK Source: https://context7.com/workos/workos-kotlin/llms.txt This snippet shows how to add the WorkOS Kotlin SDK as a Maven dependency. It includes the core artifact and suggests specifying the Kotlin version if encountering Fuel-related errors. ```xml com.workos workos 4.16.0 1.4.0 ``` -------------------------------- ### WorkOS Kotlin: Magic Auth (Passwordless Login) Source: https://context7.com/workos/workos-kotlin/llms.txt Implement passwordless login using WorkOS Magic Auth. This involves sending a magic auth code to a user's email and then authenticating them with that code. Requires WorkOS API key and client ID. ```kotlin import com.workos.WorkOS import com.workos.usermanagement.types.CreateMagicAuthOptions val workos = WorkOS("sk_test_your_api_key") // Send magic auth code val magicAuthOptions = CreateMagicAuthOptions( email = "user@example.com" ) val magicAuth = workos.userManagement.createMagicAuth(magicAuthOptions) println("Magic auth created: ${magicAuth.id}") println("Code expires at: ${magicAuth.expiresAt}") // User receives code via email, then authenticate val authentication = workos.userManagement.authenticateWithMagicAuth( clientId = "client_your_client_id", email = "user@example.com", code = "123456" // Code from email ) println("User authenticated: ${authentication.user.email}") ``` -------------------------------- ### WorkOS Kotlin: List Organization Roles Source: https://context7.com/workos/workos-kotlin/llms.txt Demonstrates how to retrieve a list of roles associated with a specific organization. Requires WorkOS API key and organization ID. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") val roles = workos.organizations.listOrganizationRoles("org_01H1QPFZ3X") roles.data.forEach { role -> println("Role: ${role.slug}") println("Name: ${role.name}") println("Description: ${role.description}") } ``` -------------------------------- ### List Users in Directory in WorkOS Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Fetches users within a specified directory. Supports filtering by directory ID and setting a limit. It can also retrieve details for a specific user by their ID. Outputs user first name, last name, email, and state. ```kotlin import com.workos.WorkOS import com.workos.directorysync.DirectorySyncApi val workos = WorkOS("sk_test_your_api_key") val options = DirectorySyncApi.ListDirectoryUserOptions.builder() .directory("directory_01H1QPFZ3X") .limit(50) .build() val users = workos.directorySync.listDirectoryUsers(options) users.data.forEach { user -> println("User: ${user.firstName} ${user.lastName}") println("Email: ${user.emails?.firstOrNull()?.value}") println("State: ${user.state}") } // Get specific user val user = workos.directorySync.getDirectoryUser("directory_user_01H1QPFZ3X") println("User details: ${user.username}") ``` -------------------------------- ### WorkOS Kotlin: Password Reset Flow Source: https://context7.com/workos/workos-kotlin/llms.txt Manage password resets with the WorkOS Kotlin SDK. This flow includes creating a password reset token, which is sent to the user via a generated URL, and then using that token to reset the password. Requires WorkOS API key. ```kotlin import com.workos.WorkOS import com.workos.usermanagement.types.CreatePasswordResetOptions val workos = WorkOS("sk_test_your_api_key") // Create password reset token val resetOptions = CreatePasswordResetOptions( email = "user@example.com", passwordResetUrl = "https://yourapp.com/reset-password" ) val passwordReset = workos.userManagement.createPasswordReset(resetOptions) println("Password reset ID: ${passwordReset.id}") println("Password reset token: ${passwordReset.passwordResetToken}") // User clicks link with token, then reset password val token = "token_from_reset_link" val updatedUser = workos.userManagement.resetPassword( token = token, newPassword = "NewSecurePassword123!" ) println("Password reset for user: ${updatedUser.email}") ``` -------------------------------- ### Create Audit Log Event in WorkOS Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Creates an audit log event with detailed information about an action, including actor, target, and context. Supports idempotency keys for safe retries. Outputs a confirmation message upon successful creation. ```kotlin import com.workos.WorkOS import com.workos.auditlogs.AuditLogsApi import java.util.Date val workos = WorkOS("sk_test_your_api_key") // Build audit log event val eventOptions = AuditLogsApi.CreateAuditLogEventOptions.builder() .action("user.login") .occurredAt(Date()) .actor( id = "user_01H1QPFZ3X", type = "user", name = "John Doe", metadata = mapOf("role" to "admin") ) .target( id = "resource_01H1QPFZ3Y", type = "document", name = "confidential.pdf", metadata = mapOf("size" to "1024") ) .context( location = "192.168.1.1", userAgent = "Mozilla/5.0..." ) .metadata(mapOf("session_id" to "sess_123")) .build() // Create event with idempotency val requestOptions = AuditLogsApi.CreateAuditLogEventRequestOptions.builder() .idempotencyKey("event-key-${System.currentTimeMillis()}") .build() workos.auditLogs.createEvent( organizationId = "org_01H1QPFZ3X", createAuditLogEventOptions = eventOptions, createAuditLogEventRequestOptions = requestOptions ) println("Audit log event created") ``` -------------------------------- ### Gradle Dependency for WorkOS Kotlin (Kotlin DSL) Source: https://github.com/workos/workos-kotlin/blob/main/README.md This Kotlin DSL snippet demonstrates how to add the WorkOS Kotlin library as a dependency in a Gradle project. Ensure 'VERSION' is substituted with the appropriate library version. ```kotlin dependencies { implementation("com.workos:workos:VERSION") } ``` -------------------------------- ### Generate SSO Authorization URL in Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Generates a Single Sign-On (SSO) authorization URL using the WorkOS Kotlin SDK. It supports specifying an organization or an OAuth provider and includes parameters for client ID, redirect URI, and state. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") // Build authorization URL with organization val authUrl = workos.sso.getAuthorizationUrl( clientId = "client_your_client_id", redirectUri = "https://yourapp.com/callback" ) .organization("org_01H1QPFZ3XKBWVQVXYZ1234567") .state("custom_state_token") .build() // Result: "https://api.workos.com/sso/authorize?client_id=client_...&redirect_uri=...&response_type=code&organization=org_01..." // Or use OAuth provider val googleAuthUrl = workos.sso.getAuthorizationUrl( clientId = "client_your_client_id", redirectUri = "https://yourapp.com/callback" ) .provider("GoogleOAuth") .state("google_auth_state") .build() ``` -------------------------------- ### WorkOS Kotlin: Organization Memberships Management Source: https://context7.com/workos/workos-kotlin/llms.txt Manage organization memberships within WorkOS using the Kotlin SDK. This includes creating, listing, updating, deactivating, reactivating, and deleting memberships. Requires WorkOS API key and organization/user IDs. ```kotlin import com.workos.WorkOS import com.workos.usermanagement.types.CreateOrganizationMembershipOptions import com.workos.usermanagement.types.ListOrganizationMembershipsOptions val workos = WorkOS("sk_test_your_api_key") // Create membership val createOptions = CreateOrganizationMembershipOptions( userId = "user_01H1QPFZ3X", organizationId = "org_01H1QPFZ3Y", roleSlug = "admin" ) val membership = workos.userManagement.createOrganizationMembership(createOptions) println("Membership created: ${membership.id}") println("Status: ${membership.status}") // List memberships val listOptions = ListOrganizationMembershipsOptions( userId = "user_01H1QPFZ3X" ) val memberships = workos.userManagement.listOrganizationMemberships(listOptions) memberships.data.forEach { m -> println("Organization: ${m.organizationId}") println("Role: ${m.role?.slug}") } // Update membership role val updated = workos.userManagement.updateOrganizationMembership( id = membership.id, roleSlug = "member" ) // Deactivate and reactivate workos.userManagement.deactivateOrganizationMembership(membership.id) workos.userManagement.reactivateOrganizationMembership(membership.id) // Delete membership workos.userManagement.deleteOrganizationMembership(membership.id) ``` -------------------------------- ### Organization Memberships API Source: https://context7.com/workos/workos-kotlin/llms.txt Manage user memberships within organizations, including creating, listing, updating, deactivating, reactivating, and deleting memberships. ```APIDOC ## Organization Memberships API ### Description Provides functionality to manage user memberships within organizations. This includes creating new memberships, listing existing ones, updating roles, and deactivating/reactivating/deleting memberships. ### Method POST, GET, PUT, DELETE (Implicitly through SDK calls) ### Endpoint `/user_management/organization_memberships` (and related SDK methods) - These are SDK method calls that map to underlying API endpoints. ### Parameters #### Request Body (for `createOrganizationMembership`) - **userId** (string) - Required - The ID of the user to add to the organization. - **organizationId** (string) - Required - The ID of the organization. - **roleSlug** (string) - Required - The slug for the role to assign to the user (e.g., "admin", "member"). #### Query Parameters (for `listOrganizationMemberships`) - **userId** (string) - Optional - Filter memberships by user ID. - **organizationId** (string) - Optional - Filter memberships by organization ID. #### Request Body (for `updateOrganizationMembership`) - **id** (string) - Required - The ID of the membership to update. - **roleSlug** (string) - Required - The new role slug to assign to the membership. ### Request Example (Create Membership) ```json { "userId": "user_01H1QPFZ3X", "organizationId": "org_01H1QPFZ3Y", "roleSlug": "admin" } ``` ### Request Example (List Memberships) (No request body, uses query parameters) ### Request Example (Update Membership Role) ```json { "id": "membership_id_123", "roleSlug": "member" } ``` ### Response #### Success Response (200) - **data** (array) - A list of organization memberships. - **id** (string) - The unique identifier for the membership. - **status** (string) - The status of the membership (e.g., "active", "invited"). - **organizationId** (string) - The ID of the organization. - **role** (object) - Information about the user's role. - **slug** (string) - The slug of the role. #### Response Example (Create/Update/List Membership) ```json { "data": [ { "id": "membership_01H1QPFZ3Z", "status": "active", "organizationId": "org_01H1QPFZ3Y", "role": { "slug": "admin" } } ] } ``` ### Actions - **Deactivate Membership**: `deactivateOrganizationMembership(membershipId)` - **Reactivate Membership**: `reactivateOrganizationMembership(membershipId)` - **Delete Membership**: `deleteOrganizationMembership(membershipId)` ``` -------------------------------- ### Create Audit Log Export in WorkOS Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Initiates an audit log export for a specified organization and date range. Allows filtering by actions, actor names, and target types. The function polls for export completion and provides a download URL upon readiness. Outputs the export ID, state, and URL. ```kotlin import com.workos.WorkOS import com.workos.auditlogs.AuditLogsApi import java.util.Calendar import java.util.Date val workos = WorkOS("sk_test_your_api_key") // Set date range val calendar = Calendar.getInstance() val rangeEnd = calendar.time calendar.add(Calendar.DAY_OF_MONTH, -30) val rangeStart = calendar.time // Create export with filters val exportOptions = AuditLogsApi.CreateAuditLogExportOptions.builder() .organizationId("org_01H1QPFZ3X") .rangeStart(rangeStart) .rangeEnd(rangeEnd) .actions(listOf("user.login", "user.logout", "document.view")) .actorNames(listOf("John Doe", "Jane Smith")) .targets(listOf("document")) .build() val export = workos.auditLogs.createExport(exportOptions) println("Export created: ${export.id}") println("State: ${export.state}") println("URL: ${export.url}") // Poll for completion var exportStatus = export while (exportStatus.state == "pending") { Thread.sleep(5000) exportStatus = workos.auditLogs.getExport(export.id) } if (exportStatus.state == "ready") { println("Export ready to download: ${exportStatus.url}") } ``` -------------------------------- ### Gradle Dependency for WorkOS Kotlin (Groovy DSL) Source: https://github.com/workos/workos-kotlin/blob/main/README.md This Groovy DSL snippet illustrates how to include the WorkOS Kotlin library in a Gradle project. Replace 'VERSION' with the specific version you wish to use. ```groovy dependencies { implementation 'com.workos:workos:VERSION' } ``` -------------------------------- ### Exchange Authorization Code for Profile in Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Exchanges an authorization code received after user authentication for a user profile and access token. Includes basic error handling for the exchange process. ```kotlin import com.workos.WorkOS val workos = WorkOS("sk_test_your_api_key") // After user redirects back with authorization code val code = "auth_code_from_redirect" try { val profileAndToken = workos.sso.getProfileAndToken( code = code, clientId = "client_your_client_id" ) // Access user profile val profile = profileAndToken.profile println("User ID: ${profile.id}") println("Email: ${profile.email}") println("First Name: ${profile.firstName}") println("Last Name: ${profile.lastName}") println("Organization ID: ${profile.organizationId}") // Access token for subsequent requests val accessToken = profileAndToken.accessToken // Profile includes roles if configured profile.roles?.forEach { role -> println("Role: ${role.slug}") } } catch (e: Exception) { println("Authentication failed: ${e.message}") } ``` -------------------------------- ### List Groups in Directory in WorkOS Kotlin Source: https://context7.com/workos/workos-kotlin/llms.txt Retrieves groups within a directory or groups associated with a specific user. Allows specifying directory or user IDs for filtering. Outputs group names and IDs. Also provides functionality to fetch details of a specific group. ```kotlin import com.workos.WorkOS import com.workos.directorysync.DirectorySyncApi val workos = WorkOS("sk_test_your_api_key") // List groups in directory val groupOptions = DirectorySyncApi.ListDirectoryGroupOptions.builder() .directory("directory_01H1QPFZ3X") .build() val groups = workos.directorySync.listDirectoryGroups(groupOptions) groups.data.forEach { group -> println("Group: ${group.name}") println("ID: ${group.id}") } // List groups for specific user val userGroupOptions = DirectorySyncApi.ListDirectoryGroupOptions.builder() .user("directory_user_01H1QPFZ3X") .build() val userGroups = workos.directorySync.listDirectoryGroups(userGroupOptions) // Get specific group val group = workos.directorySync.getDirectoryGroup("directory_group_01H1QPFZ3X") println("Group: ${group.name}") ```