View Source Lightning.Credentials.OauthToken (Lightning v2.11.1)
Schema and functions for managing OAuth tokens. This module handles the storage and validation of OAuth tokens, allowing multiple credentials to share the same token when they have identical scope sets.
Summary
Functions
Creates a changeset for validating and creating an OAuth token.
Extracts scopes from OAuth token data in various formats.
Creates a changeset for updating token data. Only merges with existing token body if new_token is a map, otherwise uses new_token directly. Preserves the refresh_token from the existing token.
Types
@type t() :: %Lightning.Credentials.OauthToken{ __meta__: term(), body: map(), credentials: [Lightning.Credentials.Credential.t()] | nil, id: Ecto.UUID.t() | nil, inserted_at: DateTime.t() | nil, oauth_client: Lightning.Credentials.OauthClient.t() | nil, oauth_client_id: Ecto.UUID.t() | nil, scopes: [String.t()], updated_at: DateTime.t() | nil, user: Lightning.Accounts.User.t() | nil, user_id: Ecto.UUID.t() | nil }
Functions
Creates a changeset for validating and creating an OAuth token.
Parameters
attrs
- A map containing token attributes::body
- The token data (required):scopes
- List of permission scopes for the token (required):oauth_client_id
- Reference to the OAuth client (required):user_id
- Reference to the user (required)
Validations
- All fields are required
- Referenced oauth_client and user must exist
- Token body must be valid (via validate_oauth_body/1)
Examples
iex> OauthToken.changeset(%{
...> body: %{"access_token" => "abc123", "refresh_token" => "xyz789"},
...> scopes: ["read", "write"],
...> oauth_client_id: client.id,
...> user_id: user.id
...> })
#Ecto.Changeset<...>
Extracts scopes from OAuth token data in various formats.
Handles four common OAuth scope formats:
- Maps with string "scope" key containing space-delimited scope strings
- Maps with atom :scope key containing space-delimited scope strings
- Maps with string "scopes" key containing a list of scope strings
- Maps with atom :scopes key containing a list of scope strings
Return values
{:ok, scopes}
- List of scope strings if extraction succeeds:error
- If scopes cannot be determined from the input
Examples
iex> extract_scopes(%{"scope" => "read write delete"})
{:ok, ["read", "write", "delete"]}
iex> extract_scopes(%{scope: "profile email"})
{:ok, ["profile", "email"]}
iex> extract_scopes(%{"scopes" => ["admin", "user"]})
{:ok, ["admin", "user"]}
iex> extract_scopes(%{scopes: ["read", "write"]})
{:ok, ["read", "write"]}
iex> extract_scopes(%{other_key: "value"})
:error
Creates a changeset for updating token data. Only merges with existing token body if new_token is a map, otherwise uses new_token directly. Preserves the refresh_token from the existing token.