{"id":18896483,"url":"https://github.com/descope/descope-ruby-sdk","last_synced_at":"2025-04-15T01:51:52.367Z","repository":{"id":222701088,"uuid":"735184280","full_name":"descope/descope-ruby-sdk","owner":"descope","description":"Ruby library used to integrate with Descope","archived":false,"fork":false,"pushed_at":"2025-04-08T15:21:48.000Z","size":2768,"stargazers_count":17,"open_issues_count":11,"forks_count":1,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-04-11T21:20:02.110Z","etag":null,"topics":["authentication","authorization","descope","ruby","ruby-sdk","sdk"],"latest_commit_sha":null,"homepage":"https://docs.descope.com","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/descope.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-12-24T00:58:11.000Z","updated_at":"2025-04-09T10:28:10.000Z","dependencies_parsed_at":"2025-01-02T16:30:26.518Z","dependency_job_id":"ff251ea9-6858-4ba2-bdd6-114ae0911887","html_url":"https://github.com/descope/descope-ruby-sdk","commit_stats":null,"previous_names":["descope/descope-ruby-sdk","descope/ruby-sdk"],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/descope%2Fdescope-ruby-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/descope%2Fdescope-ruby-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/descope%2Fdescope-ruby-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/descope%2Fdescope-ruby-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/descope","download_url":"https://codeload.github.com/descope/descope-ruby-sdk/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248480422,"owners_count":21110939,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","authorization","descope","ruby","ruby-sdk","sdk"],"created_at":"2024-11-08T08:34:09.043Z","updated_at":"2025-04-15T01:51:52.352Z","avatar_url":"https://github.com/descope.png","language":"Ruby","readme":"# Descope SDK for Ruby\n\nThe Descope SDK for Ruby provides convenient access to the Descope user management and authentication API\nfor a backend written in Ruby. You can read more on the [Descope Website](https://descope.com).\n\n## Requirements\n\nThe SDK supports Ruby 3.3.0 and above.\n\n## Installing the SDK\n\nInstall the package with:\n\n```bash\ngem install descope\n```\n\n## Setup\n\nA Descope `Project ID` is required to initialize the SDK. Find it on the\n[project page in the Descope Console](https://app.descope.com/settings/project).\n\n```ruby\nrequire 'descope'\n\ndescope_client = Descope::Client.new(\n  {\n    project_id: '\u003cproject_id\u003e',\n    management_key: ENV['MGMT_KEY']\n  }\n)\n```\n\n### Important Logging note\nYou may pass `log_level: 'debug'` to the client config or use `DESCOPE_LOG_LEVEL` env var.\nBe aware that only the management key is truncated, and the JWT responses are printed on debug\n\nDo not run with log level debug on Production!\n\n\n## Authentication Methods\nThese sections show how to use the SDK to perform various authentication/authorization functions:\n\n1. [OTP Authentication](#otp-authentication)\n2. [Magic Link](#magic-link)\n3. [Enchanted Link](#enchanted-link)\n4. [OAuth](#oauth)\n5. [SSO (SAML / OIDC)](#sso-saml-oidc)\n6. [TOTP Authentication](#totp-authentication)\n7. [Passwords](#passwords)\n8. [Session Validation](#session-validation)\n9. [Roles \u0026 Permission Validation](#roles-permission-validation)\n10. [Tenant selection](#tenant-selection)\n11. [Signing Out](#signing-out)\n12. [History](#history)\n\n## API Management Function\n\nThese sections show how to use the SDK to perform permission and user management functions. You will need to create an instance of `DescopeClient` by following the [Setup](#setup-1) guide, before you can use any of these methods:\n\n1. [Manage Tenants](#manage-tenants)\n2. [Manage Users](#manage-users)\n3. [Manage Access Keys](#manage-access-keys)\n4. [Manage SSO Setting](#manage-sso-setting)\n5. [Manage Permissions](#manage-permissions)\n6. [Manage Roles](#manage-roles)\n7. [Query SSO Groups](#query-sso-groups)\n8. [Manage Flows](#manage-flows-and-theme)\n9. [Manage JWTs](#manage-jwts)\n10. [Impersonate](#impersonate)\n11. [Embedded links](#embedded-links)\n12. [Audit](#audit)\n13. [Manage ReBAC Authz](#manage-rebac-authz)\n14. [Manage Project](#manage-project)\n15. [Manage SSO Applications](#manage-sso-applications)\n\nIf you wish to run any of our code examples and play with them, check out our [Code Examples](#code-examples) section.\n\nIf you're performing end-to-end testing, check out the [Utils for your end to end (e2e) tests and integration tests](#utils-for-your-end-to-end-e2e-tests-and-integration-tests) section. You will need to use the `DescopeClient` object created under [Setup](#setup-1) guide.\n\nFor rate limiting information, please confer to the [API Rate Limits](#api-rate-limits) section.\n\n### OTP Authentication\n\nSend a user a one-time password (OTP) using your preferred delivery method (Email/SMS/Voice call). An email address or phone number must be provided accordingly.\n\nThe user can either `sign up`, `sign in` or `sign up or in`\n\n```ruby\n# Every user must have a login ID. All other user information is optional\n# For sign up either phone or email is required\nemail = 'desmond@descope.com'\nuser = {'name': 'Desmond Copeland', 'phone': '212-555-1234', 'email': email}\nmasked_address = descope_client.otp_sign_up(method: Descope::Mixins::Common::DeliveryMethod::EMAIL, login_id: 'someone@example.com', user: user)\n```\n\nThe user will receive a code using the selected delivery method. Verify that code using:\n\n```ruby\njwt_response = descope_client.otp_verify_code(\n    method: Descope::Mixins::Common::DeliveryMethod::EMAIL, login_id: 'someone@example.com', code: '123456'\n)\nsession_token = jwt_response[Descope::Mixins::Common::SESSION_TOKEN_NAME].fetch('jwt')\nrefresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME].fetch('jwt')\n```\n\nThe session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)\n\n### Magic Link\n\nSend a user a Magic Link using your preferred delivery method (Email / SMS).\nThe Magic Link will redirect the user to page where the token needs to be verified.\nThis redirection can be configured in code, or generally in the [Descope Console](https://app.descope.com/settings/authentication/magiclink)\n\nThe user can either `sign up`, `sign in` or `sign up or in`\n\n```ruby\nmasked_address = descope_client.magiclink_sign_up_or_in(\n    method: Descope::Mixins::Common::DeliveryMethod::EMAIL,\n    login_id: 'desmond@descope.com',\n    uri: 'https://myapp.com/verify-magic-link', # Set redirect URI here or via console\n)\n```\n\nTo verify a magic link, your redirect page must call the validation function on the token (`t`) parameter (`https://your-redirect-address.com/verify?t=\u003ctoken\u003e`):\n\n```ruby\njwt_response = descope_client.magiclink_verify_token('token-here')\nsession_token = jwt_response[Descope::Mixins::Common::SESSION_TOKEN_NAME].fetch('jwt')\nrefresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME].fetch('jwt')\n```\n\nThe session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)\n\n### Enchanted Link\n\nUsing the Enchanted Link APIs enables users to sign in by clicking a link\ndelivered to their email address. The email will include 3 different links,\nand the user will have to click the right one, based on the 2-digit number that is\ndisplayed when initiating the authentication process.\n\nThis method is similar to [Magic Link](#magic-link) but differs in two major ways:\n\n- The user must choose the correct link out of the three, instead of having just one\n  single link.\n- This supports cross-device clicking, meaning the user can try to log in on one device,\n  like a computer, while clicking the link on another device, for instance a mobile phone.\n\nThe Enchanted Link will redirect the user to a page where the token needs to be verified.\nThis redirection can be configured in code per request, or set globally in the [Descope Console](https://app.descope.com/settings/authentication/enchantedlink).\n\nThe user can either `sign up`, `sign in` or `sign up or in`\n\n```ruby\nres = descope_client.enchanted_link_sign_up_or_in(\n    login_id: 'someone@example.com',\n    uri: 'https://myapp.com/verify-enchanted-link', # Set redirect URI here or via console\n)\nlink_identifier = res['linkId'] # Show the user which link they should press in their email\npending_ref = res['pendingRef'] # Used to poll for a valid session\nmasked_email = res['maskedEmail'] # The email that the message was sent to in a masked format\n```\n\nAfter sending the link, you must poll to receive a valid session using the `pending_ref` from\nthe previous step. A valid session will be returned only after the user clicks the right link.\n\n```ruby\n\npending_ref = res['pendingRef']\n\ndef poll_for_session(descope_client, pending_ref)\n  max_tries = 15\n  i = 0\n  done = false\n  while !done \u0026\u0026 i \u003c max_tries\n    begin\n      i += 1\n      puts 'waiting 4 seconds for session to be created...'\n      sleep(4)\n      print '.'\n      jwt_response = descope_client.enchanted_link_get_session(pending_ref)\n      done = true\n    rescue Descope::AuthException, Descope::Unauthorized =\u003e e\n      puts \"Failed pending session, err: #{e}\"\n      nil\n    end\n\n    if jwt_response\n      puts \"jwt_response: #{jwt_response}\"\n      refresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME]['jwt']\n\n      puts \"refresh_token: #{refresh_token}\"\n      puts :'Done logging out!'\n      descope_client.sign_out(refresh_token)\n      puts 'User logged out'\n      done = true\n    end\n  end\nend\n\npoll_for_session(descope_client, pending_ref)\n```\n\nTo verify an enchanted link, your redirect page must call the validation function on the token (`t`) parameter (`https://your-redirect-address.com/verify?t=\u003ctoken\u003e`). Once the token is verified, the session polling will receive a valid `jwt_response`.\n\n```ruby\nbegin\n    descope_client.enchanted_link_verify_token(token=token)\n    # Token is valid\nrescue AuthException =\u003e e\n  # Token is invalid\n  puts \"Failed to verify token, err: #{e}\"\nend\n```\n\nThe session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)\n\n### OAuth\n\nUsers can authenticate using their social logins, using the OAuth protocol. Configure your OAuth settings on the [Descope console](https://app.descope.com/settings/authentication/social). To start a flow call:\n\n```ruby\n\ndescope_client.oauth_start(\n    provider: 'google', # Choose an oauth provider out of the supported providers\n    return_url: 'https://my-app.com/handle-oauth', # Can be configured in the console instead of here\n)\n```\n\nThe user will authenticate with the authentication provider, and will be redirected back to the redirect URL, with an appended `code` HTTP URL parameter. Exchange it to validate the user:\n\n```ruby\njwt_response = descope_client.oauth_exchange_token(code)\nsession_token = jwt_response[Descope::Mixins::Common::SESSION_TOKEN_NAME].fetch('jwt')\nrefresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME].fetch('jwt')\n```\n\nThe session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)\n\n### SSO (SAML / OIDC)\n\nUsers can authenticate to a specific tenant using SAML or Single Sign On. Configure your SSO/SAML settings on the [Descope console](https://app.descope.com/settings/authentication/sso). To start a flow call:\n\n```ruby\n\ndescope_client.saml_sign_in(\n    tenant: 'my-tenant-ID', # Choose which tenant to log into\n    return_url: 'https://my-app.com/handle-saml', # Can be configured in the console instead of here\n    prompt: 'custom prompt here'\n)\n```\n\nThe user will authenticate with the authentication provider configured for that tenant, and will be redirected back to the redirect URL, with an appended `code` HTTP URL parameter. Exchange it to validate the user:\n\n```ruby\njwt_response = descope_client.saml_exchange_token(code)\nsession_token = jwt_response[Descope::Mixins::Common::SESSION_TOKEN_NAME].fetch('jwt')\nrefresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME].fetch('jwt')\n```\n\nThe session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)\n\n### TOTP Authentication\n\nThe user can authenticate using an authenticator app, such as Google Authenticator.\nSign up like you would use any other authentication method. The sign-up response\nwill then contain a QR code `image` that can be displayed to the user to scan using\ntheir mobile device camera app, or the user can enter the `key` manually or click\non the link provided by the `provisioning_url`.\n\nExisting users can add TOTP using the `update` function.\n\n```ruby\n# Every user must have a login ID. All other user information is optional\nemail = 'desmond@descope.com'\nuser = {name: 'Desmond Copeland', phone: '212-555-1234', email: 'someone@example.com'}\ntotp_response = descope_client.totp_sign_up(method: Descope::Mixins::Common::DeliveryMethod::EMAIL, login_id: 'someone@example.com', user: user)\n\n# Use one of the provided options to have the user add their credentials to the authenticator\nprovisioning_url = totp_response['provisioningURL']\nimage = totp_response['image']\nkey = totp_response['key']\n```\n\nThere are 3 different ways to allow the user to save their credentials in\ntheir authenticator app - either by clicking the provisioning URL, scanning the QR\nimage or inserting the key manually. After that, signing in is done using the code\nthe app produces.\n\n```ruby\njwt_response = descope_client.totp_sign_in_code(\n    login_id: 'someone@example.com',\n    code: '123456' # Code from authenticator app\n)\nsession_token = jwt_response[Descope::Mixins::Common::SESSION_TOKEN_NAME].fetch('jwt')\nrefresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME].fetch('jwt')\n```\n\nThe session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)\n\n### Passwords\n\nThe user can also authenticate with a password, though it's recommended to\nprefer passwordless authentication methods if possible. Sign up requires the\ncaller to provide a valid password that meets all the requirements configured\nfor the [password authentication method](https://app.descope.com/settings/authentication/password) in the Descope console.\n\n```ruby\n# Every user must have a login_id and a password. All other user information is optional\nlogin_id = 'desmond@descope.com'\npassword = 'qYlvi65KaX'\nuser = {\n    name: 'Desmond Copeland',\n    email: login_id,\n}\njwt_response = descope_client.password_sign_up(login_id:, password:, user:)\nsession_token = jwt_response[Descope::Mixins::Common::SESSION_TOKEN_NAME].fetch('jwt')\nrefresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME].fetch('jwt')\n```\n\nThe user can later sign in using the same login_id and password.\n\n```ruby\njwt_response = descope_client.password_sign_in(login_id:, password:)\nsession_token = jwt_response[Descope::Mixins::Common::SESSION_TOKEN_NAME].fetch('jwt')\nrefresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME].fetch('jwt')\n```\n\nThe session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on [session validation](#session-validation)\n\nIn case the user needs to update their password, one of two methods are available: Resetting their password or replacing their password\n\n**Changing Passwords**\n\n_NOTE: send_reset will only work if the user has a validated email address. Otherwise, password reset prompts cannot be sent._\n\nIn the [password authentication method](https://app.descope.com/settings/authentication/password) in the Descope console, it is possible to define which alternative authentication method can be used in order to authenticate the user, in order to reset and update their password.\n\n```ruby\n# Start the reset process by sending a password reset prompt. In this example we'll assume\n# that magic link is configured as the reset method. The optional redirect URL is used in the\n# same way as in regular magic link authentication.\nlogin_id = 'desmond@descope.com'\nredirect_url = 'https://myapp.com/password-reset'\ndescope_client.password_reset(login_id:, redirect_url:)\n```\n\nThe magic link, in this case, must then be verified like any other magic link (see the [magic link section](#magic-link) for more details). However, after verifying the user, it is expected\nto allow them to provide a new password instead of the old one. Since the user is now authenticated, this is possible via:\n\n```ruby\n# The refresh token is required to make sure the user is authenticated.\nerr = descope_client.password_update(login_id:, new_password: 'xyz123', token: 'token-here')\n```\n\n`update` can always be called when the user is authenticated and has a valid session.\n\nAlternatively, it is also possible to replace an existing active password with a new one.\n\n```ruby\n# Replaces the user's current password with a new one\njwt_response = descope_client.password_replace(login_id: 'login', old_password: '1234', new_password: '4567')\nsession_token = jwt_response[Descope::Mixins::Common::SESSION_TOKEN_NAME].fetch('jwt')\nrefresh_token = jwt_response[Descope::Mixins::Common::REFRESH_SESSION_TOKEN_NAME].fetch('jwt')\n```\n\n### Session Validation\n\nEvery secure request performed between your client and server needs to be validated. The client sends\nthe session and refresh tokens with every request, and they are validated using one of the following:\n\n```ruby\n# Validate the session. Will raise if expired\nbegin\n    jwt_response = descope_client.validate_session('session_token')\nrescue AuthException =\u003e e\n    # Session expired\nend\n\n# If validate_session raises an exception, you will need to refresh the session using\njwt_response = descope_client.refresh_session('refresh_token')\n\n# Alternatively, you could combine the two and\n# have the session validated and automatically refreshed when expired\njwt_response = descope_client.validate_and_refresh_session('session_token', 'refresh_token')\n```\n\nChoose the right session validation and refresh combination that suits your needs.\n\nNote: all those validation apis can receive an optional 'audience' parameter that should be provided when using jwt that has the 'aud' claim.\n\nRefreshed sessions return the same response as is returned when users first sign up / log in,\ncontaining the session and refresh tokens, as well as all the JWT claims.\nMake sure to return the tokens from the response to the client, or updated the cookie if you're using it.\n\nUsually, the tokens can be passed in and out via HTTP headers or via a cookie.\nThe implementation can defer according to your framework of choice. See our [examples](#code-examples) for a few examples.\n\nIf Roles \u0026 Permissions are used, validate them immediately after validating the session. See the [next section](#roles-permission-validation)\nfor more information.\n\n### Roles Permission Validation\n\nWhen using Roles \u0026 Permission, it's important to validate the user has the required\nauthorization immediately after making sure the session is valid. Taking the `jwt_response`\nreceived by the [session validation](#session-validation), call the following functions:\n\nFor multi-tenant uses:\n\n```ruby\n# You can validate specific permissions\nvalid_permissions = descope_client.validate_tenant_permissions(\n    jwt_response: 'resp', tenant: 'my-tenant-ID', permissions: ['Permission to validate']\n)\n\nunless valid_permissions\n    # Deny access\nend\n\n# Or validate roles directly\nvalid_roles = descope_client.validate_tenant_roles(\n    jwt_response: 'resp', tenant: 'my-tenant-ID', roles: ['Role to validate']\n)\n\nunless valid_roles\n    # Deny access\nend\n```\n\nWhen not using tenants use:\n\n```ruby\n# You can validate specific permissions\nvalid_permissions = descope_client.validate_permissions(\n    jwt_response: 'resp', permissions: ['Permission to validate']\n)\nunless valid_permissions\n    # Deny access\nend\n\n# Or validate roles directly\nvalid_roles = descope_client.validate_roles(\n    jwt_response: 'resp', roles: ['Role to validate']\n)\n\nunless valid_roles\n    # Deny access\nend\n```\n\n### Tenant selection\nFor a user that has permissions to multiple tenants, you can set a specific tenant as the current selected one\nThis will add an extra attribute to the refresh JWT and the session JWT with the selected tenant ID\n\n```ruby\ntenant_id = 't1'\njwt_response = descope_client.select_tenant(tenant_id:, refresh_token: 'refresh_token')\n```\n\n### Signing Out\n\nYou can log out a user from an active session by providing their `refresh_token` for that session.\nAfter calling this function, you must invalidate or remove any cookies you have created.\n\n```ruby\ndescope_client.sign_out('refresh_token')\n```\n\nIt is also possible to sign the user out of all the devices they are currently signed in with. Calling `logout_all` will\ninvalidate all user's refresh tokens. After calling this function, you must invalidate or remove any cookies you have created.\n\n```ruby\ndescope_client.sign_out_all('refresh_token')\n```\n\n### History\nYou can get the current session user history.\nThe request requires a valid refresh token.\n\n```ruby\nusers_history_resp = descope_client.history(refresh_token)\nfor user_history in users_history_resp:\n    # Do something\n```\n\n## Management API\n\nIt is very common for some form of management or automation to be required. These can be performed\nusing the management API. Please note that these actions are more sensitive as they are administrative\nin nature. Please use responsibly.\n\n### Setup\n\nTo use the management API you'll need a `Management Key` along with your `Project ID`.\nCreate one in the [Descope Console](https://app.descope.com/settings/company/managementkeys).\n\n```ruby\nrequire 'descope'\n\n# Initialized after setting the DESCOPE_PROJECT_ID and the DESCOPE_MANAGEMENT_KEY env vars\nproject_id = '\u003cproject_id\u003e'\nclient = Descope::Client.new(\n        {\n                project_id: project_id,\n                management_key: ENV['MGMT_KEY']\n        }\n)\n\n```\n\n### Manage Tenants\n\nYou can create, update, delete or load tenants:\n\n```ruby\n# You can optionally set your own ID when creating a tenant\ndescope_client.create_tenant(\n        name: 'My First Tenant',\n        id: 'my-custom-id', # This is optional.\n        self_provisioning_domains: ['domain.com'],\n        custom_attributes: { 'attribute-name': 'value' },\n)\n\n# Update will override all fields as is. Use carefully.\ndescope_client.update_tenant(\n        id: 'my-custom-id',\n        name: 'My First Tenant',\n        self_provisioning_domains: %w[domain.com another-domain.com],\n        custom_attributes: { 'attribute-name': 'value' },\n)\n\n# Tenant deletion cannot be undone. Use carefully.\ndescope_client.delete_tenant('my-custom-id')\n\n# Load tenant by id\ntenant_resp = descope_client.load_tenant('my-custom-id')\n\n# Load all tenants\ntenants_resp = descope_client.load_all_tenants\ntenants = tenants_resp['tenants']\ntenants.each do |tenant|\n  # Do something\nend\n\n# search all tenants\ntenants_resp = descope_client.search_all_tenants(ids: ['id1'], names: ['name1'], custom_attributes: { 'k1': 'v1' }, self_provisioning_domains: ['spd1'])\ntenants = tenants_resp['tenants']\ntenants.each do |tenant|\n  # Do something\n  tenant_id = tenant['id']\nend\n```\n\n### Manage Users\n\nYou can create, update, delete or load users, as well as setting new password, expire password and search according to filters:\n\n```ruby\n# A user must have a login ID, other fields are optional.\n# Roles should be set directly if no tenants exist, otherwise set\n# on a per-tenant basis.\ndescope_client.create_user(\n        login_id: 'desmond@descope.com',\n        email: 'desmond@descope.com',\n        display_name: 'Desmond Copeland',\n        user_tenants: [\n                AssociatedTenant('my-tenant-id', ['role-name1']),\n        ],\n)\n\n# Alternatively, a user can be created and invited via an email message.\n# Make sure to configure the invite URL in the Descope console prior to using this function,\n# and that an email address is provided in the information.\nassociated_tenants = [{ tenant_id: 'tenant_id1', role_names: %w[role_name1 role_name2] }]\ndescope_client.invite_user(\n        login_id: 'desmond@descope.com',\n        email: 'desmond@descope.com',\n        display_name: 'Desmond Copeland',\n        user_tenants: client.associated_tenants_to_hash_array(associated_tenants),\n)\n\n# Update will override all fields as is. Use carefully.\ndescope_client.update_user(\n        login_id: 'desmond@descope.com',\n        email: 'desmond@descope.com',\n        display_name: 'Desmond Copeland',\n        user_tenants: client.associated_tenants_to_hash_array(associated_tenants)\n)\n\n# Patch all user attribute in one api call\ndescope_client.patch_user(\n        login_id: 'desmond@descope.com',\n        email: 'desmond@descope.com',\n        given_name: 'Desmond',\n        family_name: 'Copeland',\n        display_name: 'Desmond Copeland',\n        user_tenants: client.associated_tenants_to_hash_array(associated_tenants)\n)\n\n# Update explicit data for a user rather than overriding all fields\ndescope_client.update_login_id(\n        login_id: 'desmond@descope.com',\n        new_login_id: 'bane@descope.com'\n)\n\ndescope_client.update_phone(\n        login_id: 'desmond@descope.com',\n        phone: '+18005551234',\n        verified: true\n)\n\ndescope_client.user_remove_tenant_roles(\n        login_id: 'desmond@descope.com',\n        tenant_id: 'my-tenant-id',\n        role_names: ['role-name1']\n)\n\n# User deletion cannot be undone. Use carefully.\ndescope_client.delete_user('desmond@descope.com')\n\n# Load specific user\nuser_resp = descope_client.load_user('desmond@descope.com')\nuser = user_resp['user']\n\n# If needed, users can be loaded using the user ID as well\nuser_resp = descope_client.load_by_user_id('\u003cuser-id\u003e')\nuser = user_resp['user']\n\n# Logout user from all devices by login ID\ndescope_client.logout_user('\u003clogin-id\u003e')\n\n# Logout user from all devices by user ID\ndescope_client.logout_user_by_id('\u003cuser-id\u003e')\n\n# Search all users, optionally according to tenant and/or role filter\n# results can be paginated using the limit and page parameters\nusers_resp = descope_client.search_all_users(tenant_ids = ['my-tenant-id'])\nusers = users_resp['users']\nusers.each do |user|\n  # Do something\nend\n```\n\n#### Set or Expire User Password\n\nYou can set a new active password for a user, which they can then use to sign in. You can also set a temporary\npassword that the user will be forced to change on the next login.\n\n```ruby\n# Set a user's temporary password\ndescope_client.set_temporary_password(login_id: '\u003clogin-id\u003e', password:  '\u003csome-password\u003e');\n\n# Set a user's password\ndescope_client.set_active_password(login_id: '\u003clogin-id\u003e', password:  '\u003csome-password\u003e');\n\n# Or alternatively, expire a user password\ndescope_client.expire_password('\u003clogin-id\u003e')\n```\n\n### Manage Access Keys\n\nYou can create, update, delete or load access keys, as well as search according to filters:\n\n```ruby\n# An access key must have a name and expiration, other fields are optional.\n# Roles should be set directly if no tenants exist, otherwise set\n# on a per-tenant basis. If custom_claims supplied they will be presented on the jwt.\n# If customClaims is supplied, then those claims will be present in the JWT returned by calls to ExchangeAccessKey.\nassociated_tenants = [{ tenant_id: 'tenant_id1', role_names: %w[role_name1 role_name2] }]\ncreate_resp = descope_client.create_access_key(\n    name: 'name',\n    expire_time: 1677844931,\n    key_tenants: associated_tenants,\n\tcustom_claims: {'k1': 'v1'}\n)\nkey = create_resp['key']\ncleartext = create_resp['cleartext'] # make sure to save the returned cleartext securely. It will not be returned again.\n\n# Load a specific access key\naccess_key_resp = descope_client.load_access_key('key-id')\naccess_key = access_key_resp['key']\n\n# Search all access keys, optionally according to a tenant filter\nkeys_resp = descope_client.search_all_access_keys(['my-tenant-id'])\nkeys = keys_resp['keys']\nkeys.each do |key|\n        # Do something with key\nend\n\n# Update will rename the access key\ndescope_client.update_access_key(\n    id: 'key-id',\n    name: 'new name'\n)\n\n# Access keys can be deactivated to prevent usage. This can be undone using 'activate'.\ndescope_client.deactivate_access_key('key-id')\n\n# Disabled access keys can be activated once again.\ndescope_client.activate_access_key('key-id')\n\n# Access key deletion cannot be undone. Use carefully.\ndescope_client.delete_access_key('key-id')\n\n```\n\n### Manage SSO SAML Settings\n\nYou can manage SSO settings and map SSO group roles and user attributes.\n\n```ruby\n# You can get SSO SAML settings for a tenant\nsso_settings_res = descope_client.sso_get_settings('tenant-id')  \n\n# You can configure SSO SAML settings manually by setting the required fields directly\ndescope_client.configure_sso_saml_metadata(\n    tenant_id: '123', # Which tenant this configuration is for\n    settings: {\n      name: 'test',\n      clientId: 'test',\n      scope: ['test'],\n      userAttrMapping: {\n              loginId: 'test',\n              username: 'test',\n              name: 'test'\n      },\n      callbackDomain: 'test'   \n    },\n    redirect_url: 'https://your.domain.com', # Global redirection after successful authentication\n    domain: 'tenant-users.com' # Users authentication with this domain will be logged in to this tenant\n)\n```\n\n\n### Manage Permissions\n\nYou can create, update, delete or load permissions:\n\n```ruby\n# You can optionally set a description for a permission.\ndescope_client.create_permission(\n    name:'My Permission',\n    description:'Optional description to briefly explain what this permission allows.'\n)\n\n# Update will override all fields as is. Use carefully.\ndescope_client.mgmt.update_permission(\n    name: 'My Permission',\n    new_name: 'My Updated Permission',\n    description: 'A revised description'\n)\n\n# Permission deletion cannot be undone. Use carefully.\ndescope_client.mgmt.permission.delete('My Updated Permission')\n\n# Load all permissions\npermissions_resp = descope_client.load_all_permissions\npermissions = permissions_resp['permissions']\n    permissions.each do |permission|\n        # Do something\n    end\n```\n\n### Manage Roles\n\nYou can create, update, delete or load roles:\n\n```ruby\n# You can optionally set a description and associated permission for a roles.\ndescope_client.create_role(\n    name: 'My Role',\n    description: 'Optional description to briefly explain what this role allows.',\n    permission_names: ['My Updated Permission'],\n    tenant_id: 'Optionally scope this role for this specific tenant. If left empty, the role will be available to all tenants.'\n)\n\n# Update will override all fields as is. Use carefully.\ndescope_client.update_role(\n    name: 'My Role',\n    new_name: 'My Updated Role',\n    description: 'A revised description',\n    permission_names: ['My Updated Permission', 'Another Permission'],\n    tenant_id: 'The tenant ID to which this role is associated, leave empty, if role is a global one'\n)\n\n# Role deletion cannot be undone. Use carefully.\ndescope_client.delete_role(name: 'My Updated Role',  tenant_id: 'The tenant ID to which this role is associated, leave empty, if role is a global one')\n\n# Load all roles\nroles_resp = descope_client.load_all_roles\nroles = roles_resp['roles']\n    roles.each do |role|\n      # Do something\n    end\n# \n```\n\n# Search roles\n\n```ruby\nroles_resp = descope_client.search_roles(\n  names: %w[role1 role2], # Search for roles with the names 'role1' and 'role2'\n  role_name_like: 'role', # Search for roles that contain the string 'role'\n  tenant_ids: %w[tenant1 tenant2], # Search for roles that are associated with the tenants 'tenant1' and 'tenant2'\n  permission_names: %w[permission1 permission2] # Search for roles that have the permissions 'permission1' and 'permission2'\n)\n\nroles = roles_resp['roles']\nroles.each do |role|\n  # Do something\nend\n```\n\n### Manage Flows and Theme\n\nYou can list your flows and also import and export flows and screens, or the project theme:\n\n```ruby\n# List all project flows\nflows_resp = descope_client.list_or_search_flows()\nputs(\"Total number of flows: #{flows_resp['total']}\")\nflows = flows_resp['flows']\nflows.each do |flow|\n  # Do something\nend\n\n# Export a selected flow by id for the flow and matching screens.\nexported_flow_and_screens = descope_client.export_flow('sign-up-or-in')\n\n# Import a given flow and screens to the flow matching the id provided.\nimported_flow_and_screens = descope_client.import_flow(\n        flow_id: 'sign-up-or-in',\n        flow: {},\n        screens: []\n)\n\n# Export your project theme.\nexported_theme = descope_client.export_theme\n\n# Import a theme to your project.\nimported_theme = descope_client.import_theme('theme')\n\n```\n\n### Query SCIM Groups\n\nYou can query SCIM groups:\n\n```ruby\n# Load all groups for a given tenant id\ngroups_resp = descope_client.scim_search_groups(\n        group_id: 'group_id',\n        display_name: 'display_name',\n        members: ['members'],\n        external_id: 'external_id',\n        excluded_attributes: { abc: '123' }\n)\n\n# Load SCIM group\ngroup = descope_client.scim_load_group(\n    tenant_id: 'tenant-id',\n    group_id: 'group-id'\n)\n\n# Load SCIM group members\ngroup = descope_client.scim_create_group(\n        group_id: 'group_id',\n        display_name: 'display_name',\n        members: ['members'],\n        external_id: 'external_id',\n        excluded_attributes: { abc: '123' }\n)\n```\n\n### Manage JWTs\n\nYou can add custom claims to a valid JWT.\n\n```ruby\nupdated_jwt = descope_client.update_jwt(\n    jwt: 'original-jwt',\n    custom_claims: {\n        'custom-key1': 'custom-value1',\n        'custom-key2': 'custom-value2'\n    },\n)\n```\n\n# Note 1: The generate code/link functions, work only for test users, will not work for regular users.\n\n# Note 2: In case of testing sign-in / sign-up operations with test users, need to make sure to generate the code prior calling the sign-in / sign-up operations.\n\n### Embedded links\n\nEmbedded links can be created to directly receive a verifiable token without sending it.\n\nThis token can then be verified using the magic link 'verify' function, either directly or through a flow.\n\n```ruby\ntoken = descope_client.generate_embedded_link(login_id: 'desmond@descope.com', custom_claims: {'key1':'value1'})\n```\n\n### Audit\n\nYou can perform an audit search for either specific values or full-text across the fields. Audit search is limited to the last 30 days.\nBelow are some examples. For a full list of available search criteria options, see the function documentation.\n\n```ruby\n# Full text search on last 10 days\naudits = descope_client.audit_search(\n        no_tenants: true,\n        actions: ['LoginSucceed'],\n        user_ids: %w[user1 user2],\n        exclude_actions: %w[exclude1 exclude2],\n        devices: %w[Bot Mobile Desktop Tablet Unknown],\n        methods: %w[otp totp magiclink oauth saml password],\n        geos: %w[US IL],\n        remote_addresses: %w[remote1 remote2],\n        login_ids: %w[login1 login2],\n        tenants: %w[tenant1 tenant2],\n        text: 'text123',\n        from_ts: time.now - 10 * 24 * 60 * 60,\n        to_ts: time.now - 1 * 24 * 60 * 60,\n)\n\n# Search successful logins in the last 30 days\naudits = descope_client.audit_search(actions: ['LoginSucceed'])\n```\n\nYou can also create audit event with data\n\n```ruby\ndescope_client.audit_create_event(\n  actor_id: \"UXXX\", # required, for example a user ID\n  tenant_id: \"tenant-id\", # required\n  action: \"pencil.created\", # required\n  type: \"info\", # either: info/warn/error # required\n  data: {\n        pencil_id: \"PXXX\",\n        pencil_name: \"Pencil Name\"\n  } # optional\n)\n```\n\n### Manage ReBAC Authz\n\nDescope supports full relation based access control (ReBAC) using a [Google Zanzibar](https://research.google/pubs/pub48190/) like schema and operations.\nA schema comprises namespaces (entities like documents, folders, orgs, etc.) and each namespace has relation definitions to define relations.\nEach relation definition can be simple (either you have it or not) or complex (union of nodes).\n\nA simple example for a file system like schema would be:\n\n```yaml\n# Example schema for the authz tests\nname: Files\nnamespaces:\n  - name: org\n    relationDefinitions:\n      - name: parent\n      - name: member\n        complexDefinition:\n          nType: union\n          children:\n            - nType: child\n              expression:\n                neType: self\n            - nType: child\n              expression:\n                neType: relationLeft\n                relationDefinition: parent\n                relationDefinitionNamespace: org\n                targetRelationDefinition: member\n                targetRelationDefinitionNamespace: org\n  - name: folder\n    relationDefinitions:\n      - name: parent\n      - name: owner\n        complexDefinition:\n          nType: union\n          children:\n            - nType: child\n              expression:\n                neType: self\n            - nType: child\n              expression:\n                neType: relationRight\n                relationDefinition: parent\n                relationDefinitionNamespace: folder\n                targetRelationDefinition: owner\n                targetRelationDefinitionNamespace: folder\n      - name: editor\n        complexDefinition:\n          nType: union\n          children:\n            - nType: child\n              expression:\n                neType: self\n            - nType: child\n              expression:\n                neType: relationRight\n                relationDefinition: parent\n                relationDefinitionNamespace: folder\n                targetRelationDefinition: editor\n                targetRelationDefinitionNamespace: folder\n            - nType: child\n              expression:\n                neType: targetSet\n                targetRelationDefinition: owner\n                targetRelationDefinitionNamespace: folder\n      - name: viewer\n        complexDefinition:\n          nType: union\n          children:\n            - nType: child\n              expression:\n                neType: self\n            - nType: child\n              expression:\n                neType: relationRight\n                relationDefinition: parent\n                relationDefinitionNamespace: folder\n                targetRelationDefinition: viewer\n                targetRelationDefinitionNamespace: folder\n            - nType: child\n              expression:\n                neType: targetSet\n                targetRelationDefinition: editor\n                targetRelationDefinitionNamespace: folder\n  - name: doc\n    relationDefinitions:\n      - name: parent\n      - name: owner\n        complexDefinition:\n          nType: union\n          children:\n            - nType: child\n              expression:\n                neType: self\n            - nType: child\n              expression:\n                neType: relationRight\n                relationDefinition: parent\n                relationDefinitionNamespace: doc\n                targetRelationDefinition: owner\n                targetRelationDefinitionNamespace: folder\n      - name: editor\n        complexDefinition:\n          nType: union\n          children:\n            - nType: child\n              expression:\n                neType: self\n            - nType: child\n              expression:\n                neType: relationRight\n                relationDefinition: parent\n                relationDefinitionNamespace: doc\n                targetRelationDefinition: editor\n                targetRelationDefinitionNamespace: folder\n            - nType: child\n              expression:\n                neType: targetSet\n                targetRelationDefinition: owner\n                targetRelationDefinitionNamespace: doc\n      - name: viewer\n        complexDefinition:\n          nType: union\n          children:\n            - nType: child\n              expression:\n                neType: self\n            - nType: child\n              expression:\n                neType: relationRight\n                relationDefinition: parent\n                relationDefinitionNamespace: doc\n                targetRelationDefinition: viewer\n                targetRelationDefinitionNamespace: folder\n            - nType: child\n              expression:\n                neType: targetSet\n                targetRelationDefinition: editor\n                targetRelationDefinitionNamespace: doc\n```\n\nDescope SDK allows you to fully manage the schema and relations as well as perform simple (and not so simple) checks regarding the existence of relations.\n\n```ruby\n# Load the existing schema\nschema = descope_client.authz_load_schema\n\n# Save schema and make sure to remove all namespaces not listed\ndescope_client.authz_save_schema(schema: schema, upgrade: true)\n\n# Create a relation between a resource and user\ndescope_client.authz_create_relations(\n        [\n                { \n                        resource: 'some-doc',\n                        relationDefinition: 'owner',\n                        namespace: 'doc',\n                        target: 'u1'\n                }\n        ]\n)\n\n# Check if target has the relevant relation\n# The answer should be true because an owner is also a viewer\nrelations = descope_client.authz_has_relations?(\n        [\n                {\n                        resource: 'some-doc',\n                        relationDefinition: 'viewer',\n                        namespace: 'doc',\n                        target: 'u1'\n                }\n        ]\n)\n```\n\n### Manage Project\n\nYou can change the project name, as well as to clone the current project to a new one.\n\n```ruby\n\n# Change the project name\ndescope.client.rename_project('new-project-name')\n\n# Clone the current project, including its settings and configurations.\n# Note that this action is supported only with a pro license or above.\n# Users, tenants and access keys are not cloned.\nclone_resp = descope.client.clone_project('new-project-name')\n```\n\n### Utils for your end to end (e2e) tests and integration tests\n\nTo ease your e2e tests, we exposed dedicated management methods,\nthat way, you don't need to use 3rd party messaging services in order to receive sign-in/up Emails or SMS, and avoid the need of parsing the code and token from them.\n\n```ruby\n# User for test can be created, this user will be able to generate code/link without\n# the need of 3rd party messaging services.\n# Test user must have a loginId, other fields are optional.\n# Roles should be set directly if no tenants exist, otherwise set\n# on a per-tenant basis.\n\nassociated_tenants = [{ tenant_id: 'tenant_id1', role_names: %w[role_name1 role_name2] }]\ndescope_client.create_test_user(\n        login_id: 'desmond@descope.com',\n        email: 'desmond@descope.com',\n        display_name: 'Desmond Copeland',\n        user_tenants: client.associated_tenants_to_hash_array(associated_tenants)\n)\n\n# Search all test users, optionally according to tenant and/or role filter\n# results can be paginated using the limit and page parameters\nusers_resp = descope_client.search_all_test_users()\nusers = users_resp[\"users\"]\nusers.each do |user|\n  # Do something\n\n# Now test user got created, and this user will be available until you delete it,\n# you can use any management operation for test user CRUD.\n# You can also delete all test users.\ndescope_client.delete_all_test_users\n\n# OTP code can be generated for test user, for example:\nresp = descope_client.generate_otp_for_test_user(\n        method: Descope::Mixins::Common::DeliveryMethod::EMAIL, login_id: 'login-id'\n)\ncode = resp['code']\n# Now you can verify the code is valid (using descope_client.*.verify for example)\n\n# Same as OTP, magic link can be generated for test user, for example:\nresp = descope_client.generate_magic_link_for_test_user(\n        method: Descope::Mixins::Common::DeliveryMethod::EMAIL,\n        login_id: 'login-id',\n)\nlink = resp['link']\n\n# Enchanted link can be generated for test user, for example:\nresp = descope_client.generate_enchanted_link_for_test_user(\n        'login-id', ''\n)\nlink = resp['link']\npending_ref = resp['pendingRef']\n```\n\n### Manage SSO Applications\n\nYou can create, update, delete or load SSO applications:\n\n```ruby\ndescope_client.create_sso_oidc_app(\n  name: \"My First sso app\",\n  login_page_url: \"https://dummy.com/login\",\n  id: \"my-custom-id\", # this is optional\n)\n\n# Create SAML sso application\ndescope_client.create_saml_application(\n  name: \"My First sso app\",\n  login_page_url: \"https://dummy.com/login\",\n  id: \"my-custom-id\", # this is optional\n  use_metadata_info: true,\n  metadata_url: \"https://dummy.com/metadata\",\n  default_relay_state: \"relayState\",\n  force_authentication: false,\n  logout_redirect_url: \"https://dummy.com/logout\",\n)\n```\n\n# Update OIDC sso application\n# Update will override all fields as is. Use carefully.\n\n```ruby\ndescope_client.update_sso_oidc_app(\n  id: \"my-custom-id\",\n  name: \"My First sso app\",\n  login_page_url: \"https://dummy.com/login\",\n)\n````\n\n# Update SAML sso application\n# Update will override all fields as is. Use carefully.\n\n```ruby\ndescope_client.update_saml_application(\n  id: \"my-custom-id\",\n  name: \"My First sso app\",\n  login_page_url: \"https://dummy.com/login\",\n  use_metadata_info: false,\n  entity_id: \"ent1234\",\n  acs_url: \"https://dummy.com/acs\",\n  certificate: \"my cert\"\n)\n```\n\n# SSO application deletion cannot be undone. Use carefully.\n\n```ruby\ndescope_client.delete_sso_app('my-custom-id')\n```\n\n# Load SSO application by id\n\n```ruby\ndescope_client.load_sso_app('my-custom-id')\n```\n\n# Load all SSO applications\n\n```ruby\nresp = descope_client.load_all_sso_apps\nresp[\"apps\"].each do |app|\n  # Do something\nend\n```\n\n\n## API Rate Limits\n\nHandle API rate limits by comparing the exception to the APIRateLimitExceeded exception, which includes the RateLimitParameters map with the key 'Retry-After.' This key indicates how many seconds until the next valid API call can take place.\n\n```ruby\nbegin\n    descope_client.magiclink_sign_up_or_in(\n        method: Descope::Mixins::Common::DeliveryMethod::EMAIL,\n        login_id: 'desmond@descope.com',\n        uri: 'https://myapp.com/verify-magic-link',\n    )\nrescue Descope::RateLimitException =\u003e e\n    retry_after_seconds = e['API_RATE_LIMIT_RETRY_AFTER_HEADER']\n    puts \"Rate limit exceeded, retry after #{retry_after_seconds} seconds\"\nend\n    # This variable indicates how many seconds until the next valid API call can take place.\n```\n\n## Code Examples\n\nYou can find various usage examples in the [examples folder](https://github.com/descope/ruby-sdk/blob/main/examples).\n\n## Run Locally\n\n### Prerequisites\n\n- Ruby 3.3.0 or higher\n- Bundler\n\n\n### Install dependencies\n\n```bash\nbundle install\n```\n\n### Run tests\n\nRunning all tests:\n\n```bash\nbundle exec rspec\n```\n\n## Learn More\n\nTo learn more please see the [Descope Documentation and API reference page](https://docs.descope.com/).\n\n## Contact Us\n\nIf you need help you can email [Descope Support](mailto:support@descope.com)\n\n## License\n\nThe Descope SDK for Python is licensed for use under the terms and conditions of the [MIT license Agreement](https://github.com/descope/ruby-sdk/blob/main/LICENSE).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdescope%2Fdescope-ruby-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdescope%2Fdescope-ruby-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdescope%2Fdescope-ruby-sdk/lists"}