consumer

package
v15.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2024 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CryptoWalletsClient

type CryptoWalletsClient struct {
	C stytch.Client
}

func NewCryptoWalletsClient

func NewCryptoWalletsClient(c stytch.Client) *CryptoWalletsClient

func (*CryptoWalletsClient) Authenticate

Authenticate: Complete the authentication of a crypto wallet by passing the signature.

func (*CryptoWalletsClient) AuthenticateStart

AuthenticateStart: Initiate the authentication of a crypto wallet. After calling this endpoint, the user will need to sign a message containing the returned `challenge` field.

For Ethereum crypto wallets, you can optionally use the Sign In With Ethereum (SIWE) protocol for the message by passing in the `siwe_params`. The only required fields are `domain` and `uri`. If the crypto wallet detects that the domain in the message does not match the website's domain, it will display a warning to the user.

If not using the SIWE protocol, the message will simply consist of the project name and a random string.

func (*CryptoWalletsClient) AuthenticateWithClaims

func (c *CryptoWalletsClient) AuthenticateWithClaims(
	ctx context.Context,
	body *cryptowallets.AuthenticateParams,
	claims any,
) (*cryptowallets.AuthenticateResponse, error)

AuthenticateWithClaims fills in the claims pointer with custom claims from the response. Pass in a map with the types of values you're expecting so that this function can marshal the claims from the response. See ExampleClient_AuthenticateWithClaims_map, ExampleClient_AuthenticateWithClaims_struct for examples

type M2MClient

type M2MClient struct {
	C       stytch.Client
	Clients *M2MClientsClient
	JWKS    *keyfunc.JWKS
}

func NewM2MClient

func NewM2MClient(c stytch.Client, jwks *keyfunc.JWKS) *M2MClient

func (*M2MClient) AuthenticateToken

func (c *M2MClient) AuthenticateToken(
	ctx context.Context,
	req *m2m.AuthenticateTokenParams,
) (*m2m.AuthenticateTokenResponse, error)

AuthenticateToken validates an access token issued by Stytch from the Token endpoint. M2M access tokens are JWTs signed with the project's JWKs, and can be validated locally using any Stytch client library. You may pass in an optional set of scopes that the JWT must contain in order to enforce permissions.

func (*M2MClient) Token

func (c *M2MClient) Token(
	ctx context.Context,
	body *m2m.TokenParams,
) (*m2m.TokenResponse, error)

Token retrieves an access token for the given M2M Client. Access tokens are JWTs signed with the project's JWKs, and are valid for one hour after issuance. M2M Access tokens contain a standard set of claims as well as any custom claims generated from templates. M2M Access tokens can be validated locally using the Authenticate Access Token method in the Stytch Backend SDKs, or with any library that supports JWT signature validation.

Here is an example of a standard set of claims from a M2M Access Token: ```

{
  "sub": "m2m-client-test-d731954d-dab3-4a2b-bdee-07f3ad1be885",
  "iss": "stytch.com/project-test-3e71d0a1-1e3e-4ee2-9be0-d7c0900f02c2",
  "aud": ["project-test-3e71d0a1-1e3e-4ee2-9be0-d7c0900f02c2"],
  "scope": "read:users write:users",
  "iat": 4102473300,
  "nbf": 4102473300,
  "exp": 4102476900
}

```

type M2MClientsClient

type M2MClientsClient struct {
	C       stytch.Client
	Secrets *M2MClientsSecretsClient
}

func NewM2MClientsClient

func NewM2MClientsClient(c stytch.Client) *M2MClientsClient

func (*M2MClientsClient) Create

Create: Creates a new M2M Client. On initial client creation, you may pass in a custom `client_id` or `client_secret` to import an existing M2M client. If you do not pass in a custom `client_id` or `client_secret`, one will be generated automatically. The `client_id` must be unique among all clients in your project.

**Important:** This is the only time you will be able to view the generated `client_secret` in the API response. Stytch stores a hash of the `client_secret` and cannot recover the value if lost. Be sure to persist the `client_secret` in a secure location. If the `client_secret` is lost, you will need to trigger a secret rotation flow to receive another one.

func (*M2MClientsClient) Delete

Delete: Deletes the M2M Client.

**Important:** Deleting a M2M Client will not invalidate any existing JWTs issued to the client, only prevent it from receiving new ones. To protect more-sensitive routes, pass a lower `max_token_age` value when[authenticating the token](https://stytch.com/docs/b2b/api/authenticate-m2m-token)[authenticating the token](https://stytch.com/docs/api/authenticate-m2m-token).

func (*M2MClientsClient) Get

Get: Gets information about an existing M2M Client.

func (*M2MClientsClient) Search

Search for M2M Clients within your Stytch Project. Submit an empty `query` in the request to return all M2M Clients.

The following search filters are supported today: - `client_id`: Pass in a list of client IDs to get many clients in a single request - `client_name`: Search for clients by exact match on client name - `scopes`: Search for clients assigned a specific scope

func (*M2MClientsClient) Update

Update: Updates an existing M2M Client. You can use this endpoint to activate or deactivate a M2M Client by changing its `status`. A deactivated M2M Client will not be allowed to perform future token exchange flows until it is reactivated.

**Important:** Deactivating a M2M Client will not invalidate any existing JWTs issued to the client, only prevent it from receiving new ones. To protect more-sensitive routes, pass a lower `max_token_age` value when[authenticating the token](https://stytch.com/docs/b2b/api/authenticate-m2m-token)[authenticating the token](https://stytch.com/docs/api/authenticate-m2m-token).

type M2MClientsSecretsClient

type M2MClientsSecretsClient struct {
	C stytch.Client
}

func NewM2MClientsSecretsClient

func NewM2MClientsSecretsClient(c stytch.Client) *M2MClientsSecretsClient

func (*M2MClientsSecretsClient) Rotate

Rotate: Complete the rotation of an M2M client secret started with the [Start Secret Rotation Endpoint](https://stytch.com/docs/b2b/api/m2m-rotate-secret-start) [Start Secret Rotation Endpoint](https://stytch.com/docs/api/m2m-rotate-secret-start). After this endpoint is called, the client's `next_client_secret` becomes its `client_secret` and the previous `client_secret` will no longer be valid.

func (*M2MClientsSecretsClient) RotateCancel

RotateCancel: Cancel the rotation of an M2M client secret started with the [Start Secret Rotation Endpoint](https://stytch.com/docs/b2b/api/m2m-rotate-secret-start) [Start Secret Rotation Endpoint](https://stytch.com/docs/api/m2m-rotate-secret-start). After this endpoint is called, the client's `next_client_secret` is discarded and only the original `client_secret` will be valid.

func (*M2MClientsSecretsClient) RotateStart

RotateStart: Initiate the rotation of an M2M client secret. After this endpoint is called, both the client's `client_secret` and `next_client_secret` will be valid. To complete the secret rotation flow, update all usages of `client_secret` to `next_client_secret` and call the [Rotate Secret Endpoint](https://stytch.com/docs/b2b/api/m2m-rotate-secret)[Rotate Secret Endpoint](https://stytch.com/docs/api/m2m-rotate-secret) to complete the flow. Secret rotation can be cancelled using the [Rotate Cancel Endpoint](https://stytch.com/docs/b2b/api/m2m-rotate-secret-cancel)[Rotate Cancel Endpoint](https://stytch.com/docs/api/m2m-rotate-secret-cancel).

**Important:** This is the only time you will be able to view the generated `next_client_secret` in the API response. Stytch stores a hash of the `next_client_secret` and cannot recover the value if lost. Be sure to persist the `next_client_secret` in a secure location. If the `next_client_secret` is lost, you will need to trigger a secret rotation flow to receive another one.

type MagicLinksClient

type MagicLinksClient struct {
	C     stytch.Client
	Email *MagicLinksEmailClient
}

func NewMagicLinksClient

func NewMagicLinksClient(c stytch.Client) *MagicLinksClient

func (*MagicLinksClient) Authenticate

Authenticate a User given a Magic Link. This endpoint verifies that the Magic Link token is valid, hasn't expired or been previously used, and any optional security settings such as IP match or user agent match are satisfied.

func (*MagicLinksClient) AuthenticateWithClaims

func (c *MagicLinksClient) AuthenticateWithClaims(
	ctx context.Context,
	body *magiclinks.AuthenticateParams,
	claims any,
) (*magiclinks.AuthenticateResponse, error)

AuthenticateWithClaims fills in the claims pointer with custom claims from the response. Pass in a map with the types of values you're expecting so that this function can marshal the claims from the response. See ExampleClient_AuthenticateWithClaims_map, ExampleClient_AuthenticateWithClaims_struct for examples

func (*MagicLinksClient) Create

Create an embeddable Magic Link token for a User. Access to this endpoint is restricted. To enable it, please send us a note at support@stytch.com.

### Next steps Send the returned `token` value to the end user in a link which directs to your application. When the end user follows your link, collect the token, and call [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete authentication.

type MagicLinksEmailClient

type MagicLinksEmailClient struct {
	C stytch.Client
}

func NewMagicLinksEmailClient

func NewMagicLinksEmailClient(c stytch.Client) *MagicLinksEmailClient

func (*MagicLinksEmailClient) Invite

Invite: Create a User and send an invite Magic Link to the provided `email`. The User will be created with a `pending` status until they click the Magic Link in the invite email.

### Next steps The User is emailed a Magic Link which redirects them to the provided [redirect URL](https://stytch.com/docs/guides/magic-links/email-magic-links/redirect-routing). Collect the `token` from the URL query parameters and call [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete authentication.

func (*MagicLinksEmailClient) LoginOrCreate

LoginOrCreate: Send either a login or signup Magic Link to the User based on if the email is associated with a User already. A new or pending User will receive a signup Magic Link. An active User will receive a login Magic Link. For more information on how to control the status your Users are created in see the `create_user_as_pending` flag.

### Next steps The User is emailed a Magic Link which redirects them to the provided [redirect URL](https://stytch.com/docs/guides/magic-links/email-magic-links/redirect-routing). Collect the `token` from the URL query parameters and call [Authenticate Magic Link](https://stytch.com/docs/api/authenticate-magic-link) to complete authentication.

func (*MagicLinksEmailClient) RevokeInvite

RevokeInvite: Revoke a pending invite based on the `email` provided.

func (*MagicLinksEmailClient) Send

Send a magic link to an existing Stytch user using their email address. If you'd like to create a user and send them a magic link by email with one request, use our [log in or create endpoint](https://stytch.com/docs/api/log-in-or-create-user-by-email).

### Add an email to an existing user This endpoint also allows you to add a new email address to an existing Stytch User. Including a `user_id`, `session_token`, or `session_jwt` in your Send Magic Link by email request will add the new, unverified email address to the existing Stytch User. If the user successfully authenticates within 5 minutes, the new email address will be marked as verified and remain permanently on the existing Stytch User. Otherwise, it will be removed from the User object, and any subsequent login requests using that email address will create a new User.

### Next steps The user is emailed a magic link which redirects them to the provided [redirect URL](https://stytch.com/docs/guides/magic-links/email-magic-links/redirect-routing). Collect the `token` from the URL query parameters, and call [Authenticate magic link](https://stytch.com/docs/api/authenticate-magic-link) to complete authentication.

type OAuthClient

type OAuthClient struct {
	C stytch.Client
}

func NewOAuthClient

func NewOAuthClient(c stytch.Client) *OAuthClient

func (*OAuthClient) Attach

func (c *OAuthClient) Attach(
	ctx context.Context,
	body *oauth.AttachParams,
) (*oauth.AttachResponse, error)

Attach: Generate an OAuth Attach Token to pre-associate an OAuth flow with an existing Stytch User. Pass the returned `oauth_attach_token` to the same provider's OAuth Start endpoint to treat this OAuth flow as a login for that user instead of a signup for a new user.

Exactly one of `user_id`, `session_token`, or `session_jwt` must be provided to identify the target Stytch User.

This is an optional step in the OAuth flow. Stytch can often determine whether to create a new user or log in an existing one based on verified identity provider information. This endpoint is useful for cases where we can't, such as missing or unverified provider information.

func (*OAuthClient) Authenticate

Authenticate a User given a `token`. This endpoint verifies that the user completed the OAuth flow by verifying that the token is valid and hasn't expired. To initiate a Stytch session for the user while authenticating their OAuth token, include `session_duration_minutes`; a session with the identity provider, e.g. Google or Facebook, will always be initiated upon successful authentication.

func (*OAuthClient) AuthenticateWithClaims

func (c *OAuthClient) AuthenticateWithClaims(
	ctx context.Context,
	body *oauth.AuthenticateParams,
	claims any,
) (*oauth.AuthenticateResponse, error)

AuthenticateWithClaims fills in the claims pointer with custom claims from the response. Pass in a map with the types of values you're expecting so that this function can marshal the claims from the response. See ExampleClient_AuthenticateWithClaims_map, ExampleClient_AuthenticateWithClaims_struct for examples

type OTPsClient

type OTPsClient struct {
	C        stytch.Client
	Sms      *OTPsSmsClient
	Whatsapp *OTPsWhatsappClient
	Email    *OTPsEmailClient
}

func NewOTPsClient

func NewOTPsClient(c stytch.Client) *OTPsClient

func (*OTPsClient) Authenticate

func (c *OTPsClient) Authenticate(
	ctx context.Context,
	body *otp.AuthenticateParams,
) (*otp.AuthenticateResponse, error)

Authenticate a User given a `method_id` (the associated `email_id` or `phone_id`) and a `code`. This endpoint verifies that the code is valid, hasn't expired or been previously used, and any optional security settings such as IP match or user agent match are satisfied. A given `method_id` may only have a single active OTP code at any given time, if a User requests another OTP code before the first one has expired, the first one will be invalidated.

func (*OTPsClient) AuthenticateWithClaims

func (c *OTPsClient) AuthenticateWithClaims(
	ctx context.Context,
	body *otp.AuthenticateParams,
	claims any,
) (*otp.AuthenticateResponse, error)

AuthenticateWithClaims fills in the claims pointer with custom claims from the response. Pass in a map with the types of values you're expecting so that this function can marshal the claims from the response. See ExampleClient_AuthenticateWithClaims_map, ExampleClient_AuthenticateWithClaims_struct for examples

type OTPsEmailClient

type OTPsEmailClient struct {
	C stytch.Client
}

func NewOTPsEmailClient

func NewOTPsEmailClient(c stytch.Client) *OTPsEmailClient

func (*OTPsEmailClient) LoginOrCreate

LoginOrCreate: Send a one-time passcode (OTP) to a User using their email. If the email is not associated with a User already, a User will be created.

### Next steps

Collect the OTP which was delivered to the User. Call [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the `phone_id` found in the response as the `method_id`.

func (*OTPsEmailClient) Send

Send a One-Time Passcode (OTP) to a User using their email. If you'd like to create a user and send them a passcode with one request, use our [log in or create endpoint](https://stytch.com/docs/api/log-in-or-create-user-by-email-otp).

### Add an email to an existing user This endpoint also allows you to add a new email address to an existing Stytch User. Including a `user_id`, `session_token`, or `session_jwt` in your Send one-time passcode by email request will add the new, unverified email address to the existing Stytch User. If the user successfully authenticates within 5 minutes, the new email address will be marked as verified and remain permanently on the existing Stytch User. Otherwise, it will be removed from the User object, and any subsequent login requests using that email address will create a new User.

### Next steps Collect the OTP which was delivered to the user. Call [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the `email_id` found in the response as the `method_id`.

type OTPsSmsClient

type OTPsSmsClient struct {
	C stytch.Client
}

func NewOTPsSmsClient

func NewOTPsSmsClient(c stytch.Client) *OTPsSmsClient

func (*OTPsSmsClient) LoginOrCreate

func (c *OTPsSmsClient) LoginOrCreate(
	ctx context.Context,
	body *sms.LoginOrCreateParams,
) (*sms.LoginOrCreateResponse, error)

LoginOrCreate: Send a One-Time Passcode (OTP) to a User using their phone number. If the phone number is not associated with a user already, a user will be created.

### Cost to send SMS OTP Before configuring SMS or WhatsApp OTPs, please review how Stytch [bills the costs of international OTPs](https://stytch.com/pricing) and understand how to protect your app against [toll fraud](https://stytch.com/docs/guides/passcodes/toll-fraud/overview).

__Note:__ SMS to phone numbers outside of the US and Canada is disabled by default for customers who did not use SMS prior to October 2023. If you're interested in sending international SMS, please reach out to [support@stytch.com](mailto:support@stytch.com?subject=Enable%20international%20SMS).

Even when international SMS is enabled, we do not support sending SMS to countries on our [Unsupported countries list](https://stytch.com/docs/guides/passcodes/unsupported-countries).

### Next steps

Collect the OTP which was delivered to the User. Call [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the `phone_id` found in the response as the `method_id`.

func (*OTPsSmsClient) Send

func (c *OTPsSmsClient) Send(
	ctx context.Context,
	body *sms.SendParams,
) (*sms.SendResponse, error)

Send a one-time passcode (OTP) to a user's phone number. If you'd like to create a user and send them a passcode with one request, use our [log in or create](https://stytch.com/docs/api/log-in-or-create-user-by-sms) endpoint.

Note that sending another OTP code before the first has expired will invalidate the first code.

### Cost to send SMS OTP Before configuring SMS or WhatsApp OTPs, please review how Stytch [bills the costs of international OTPs](https://stytch.com/pricing) and understand how to protect your app against [toll fraud](https://stytch.com/docs/guides/passcodes/toll-fraud/overview).

__Note:__ SMS to phone numbers outside of the US and Canada is disabled by default for customers who did not use SMS prior to October 2023. If you're interested in sending international SMS, please reach out to [support@stytch.com](mailto:support@stytch.com?subject=Enable%20international%20SMS).

Even when international SMS is enabled, we do not support sending SMS to countries on our [Unsupported countries list](https://stytch.com/docs/guides/passcodes/unsupported-countries).

### Add a phone number to an existing user

This endpoint also allows you to add a new phone number to an existing Stytch User. Including a `user_id`, `session_token`, or `session_jwt` in your Send one-time passcode by SMS request will add the new, unverified phone number to the existing Stytch User. If the user successfully authenticates within 5 minutes, the new phone number will be marked as verified and remain permanently on the existing Stytch User. Otherwise, it will be removed from the User object, and any subsequent login requests using that phone number will create a new User.

### Next steps

Collect the OTP which was delivered to the user. Call [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the `phone_id` found in the response as the `method_id`.

type OTPsWhatsappClient

type OTPsWhatsappClient struct {
	C stytch.Client
}

func NewOTPsWhatsappClient

func NewOTPsWhatsappClient(c stytch.Client) *OTPsWhatsappClient

func (*OTPsWhatsappClient) LoginOrCreate

LoginOrCreate: Send a one-time passcode (OTP) to a User's WhatsApp using their phone number. If the phone number is not associated with a User already, a User will be created.

### Cost to send SMS OTP Before configuring SMS or WhatsApp OTPs, please review how Stytch [bills the costs of international OTPs](https://stytch.com/pricing) and understand how to protect your app against [toll fraud](https://stytch.com/docs/guides/passcodes/toll-fraud/overview).

### Next steps

Collect the OTP which was delivered to the User. Call [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the `phone_id` found in the response as the `method_id`.

func (*OTPsWhatsappClient) Send

Send a One-Time Passcode (OTP) to a User's WhatsApp. If you'd like to create a user and send them a passcode with one request, use our [log in or create](https://stytch.com/docs/api/whatsapp-login-or-create) endpoint.

Note that sending another OTP code before the first has expired will invalidate the first code.

### Cost to send SMS OTP Before configuring SMS or WhatsApp OTPs, please review how Stytch [bills the costs of international OTPs](https://stytch.com/pricing) and understand how to protect your app against [toll fraud](https://stytch.com/docs/guides/passcodes/toll-fraud/overview).

### Add a phone number to an existing user

This endpoint also allows you to add a new phone number to an existing Stytch User. Including a `user_id`, `session_token`, or `session_jwt` in your Send one-time passcode by WhatsApp request will add the new, unverified phone number to the existing Stytch User. If the user successfully authenticates within 5 minutes, the new phone number will be marked as verified and remain permanently on the existing Stytch User. Otherwise, it will be removed from the User object, and any subsequent login requests using that phone number will create a new User.

### Next steps

Collect the OTP which was delivered to the user. Call [Authenticate OTP](https://stytch.com/docs/api/authenticate-otp) using the OTP `code` along with the `phone_id` found in the response as the `method_id`.

type PasswordsClient

type PasswordsClient struct {
	C                stytch.Client
	Email            *PasswordsEmailClient
	ExistingPassword *PasswordsExistingPasswordClient
	Sessions         *PasswordsSessionsClient
}

func NewPasswordsClient

func NewPasswordsClient(c stytch.Client) *PasswordsClient

func (*PasswordsClient) Authenticate

Authenticate a user with their email address and password. This endpoint verifies that the user has a password currently set, and that the entered password is correct. There are two instances where the endpoint will return a `reset_password` error even if they enter their previous password:

**One:** The user’s credentials appeared in the HaveIBeenPwned dataset. We force a password reset to ensure that the user is the legitimate owner of the email address, and not a malicious actor abusing the compromised credentials.

**Two:** A user that has previously authenticated with email/password uses a passwordless authentication method tied to the same email address (e.g. Magic Links, Google OAuth) for the first time. Any subsequent email/password authentication attempt will result in this error. We force a password reset in this instance in order to safely deduplicate the account by email address, without introducing the risk of a pre-hijack account takeover attack.

Imagine a bad actor creates many accounts using passwords and the known email addresses of their victims. If a victim comes to the site and logs in for the first time with an email-based passwordless authentication method then both the victim and the bad actor have credentials to access to the same account. To prevent this, any further email/password login attempts first require a password reset which can only be accomplished by someone with access to the underlying email address.

func (*PasswordsClient) AuthenticateWithClaims

func (c *PasswordsClient) AuthenticateWithClaims(
	ctx context.Context,
	body *passwords.AuthenticateParams,
	claims any,
) (*passwords.AuthenticateResponse, error)

AuthenticateWithClaims fills in the claims pointer with custom claims from the response. Pass in a map with the types of values you're expecting so that this function can marshal the claims from the response. See ExampleClient_AuthenticateWithClaims_map, ExampleClient_AuthenticateWithClaims_struct for examples

func (*PasswordsClient) Create

Create a new user with a password. If `session_duration_minutes` is specified, a new session will be started as well.

If a user with this email already exists in your Stytch project, this endpoint will return a `duplicate_email` error. To add a password to an existing passwordless user, you'll need to either call the [Migrate password endpoint](https://stytch.com/docs/api/password-migrate) or prompt the user to complete one of our password reset flows.

This endpoint will return an error if the password provided does not meet our strength requirements, which you can check beforehand via the [Password strength check endpoint](https://stytch.com/docs/api/password-strength-check).

When creating new Passwords users, it's good practice to enforce an email verification flow. We'd recommend checking out our [Email verification guide](https://stytch.com/docs/guides/passwords/email-verification/overview) for more information.

func (*PasswordsClient) Migrate

Migrate: Adds an existing password to a User's email that doesn't have a password yet. We support migrating users from passwords stored with `bcrypt`, `scrypt`, `argon2`, `MD-5`, `SHA-1`, or `PBKDF2`. This endpoint has a rate limit of 100 requests per second.

func (*PasswordsClient) StrengthCheck

StrengthCheck: This API allows you to check whether or not the user’s provided password is valid, and to provide feedback to the user on how to increase the strength of their password.

This endpoint adapts to your Project's password strength configuration. If you're using [zxcvbn](https://stytch.com/docs/guides/passwords/strength-policy), the default, your passwords are considered valid if the strength score is >= 3. If you're using [LUDS](https://stytch.com/docs/guides/passwords/strength-policy), your passwords are considered valid if they meet the requirements that you've set with Stytch. You may update your password strength configuration in the [stytch dashboard](https://stytch.com/dashboard/password-strength-config).

### Password feedback

The `feedback` object contains relevant fields for you to relay feedback to users that failed to create a strong enough password.

If you're using zxcvbn, the `feedback` object will contain `warning` and `suggestions` for any password that does not meet the zxcvbn strength requirements. You can return these strings directly to the user to help them craft a strong password.

If you're using LUDS, the `feedback` object will contain an object named `luds_requirements` which contain a collection of fields that the user failed or passed. You'll want to prompt the user to create a password that meets all of the requirements that they failed.

type PasswordsEmailClient

type PasswordsEmailClient struct {
	C stytch.Client
}

func NewPasswordsEmailClient

func NewPasswordsEmailClient(c stytch.Client) *PasswordsEmailClient

func (*PasswordsEmailClient) Reset

Reset the user’s password and authenticate them. This endpoint checks that the magic link `token` is valid, hasn’t expired, or already been used – and can optionally require additional security settings, such as the IP address and user agent matching the initial reset request.

The provided password needs to meet our password strength requirements, which can be checked in advance with the password strength endpoint. If the token and password are accepted, the password is securely stored for future authentication and the user is authenticated.

Note that a successful password reset by email will revoke all active sessions for the `user_id`.

func (*PasswordsEmailClient) ResetStart

ResetStart: Initiates a password reset for the email address provided. This will trigger an email to be sent to the address, containing a magic link that will allow them to set a new password and authenticate.

type PasswordsExistingPasswordClient

type PasswordsExistingPasswordClient struct {
	C stytch.Client
}

func NewPasswordsExistingPasswordClient

func NewPasswordsExistingPasswordClient(c stytch.Client) *PasswordsExistingPasswordClient

func (*PasswordsExistingPasswordClient) Reset

Reset the User’s password using their existing password.

Note that a successful password reset via an existing password will revoke all active sessions for the `user_id`.

type PasswordsSessionsClient

type PasswordsSessionsClient struct {
	C stytch.Client
}

func NewPasswordsSessionsClient

func NewPasswordsSessionsClient(c stytch.Client) *PasswordsSessionsClient

func (*PasswordsSessionsClient) Reset

Reset the user’s password using their existing session. The endpoint will error if the session does not have a password, email magic link, or email OTP authentication factor that has been issued within the last 5 minutes. This endpoint requires either a `session_jwt` or `session_token` be included in the request.

Note that a successful password reset via an existing session will revoke all active sessions for the `user_id`, except for the one used during the reset flow.

type ProjectClient

type ProjectClient struct {
	C stytch.Client
}

func NewProjectClient

func NewProjectClient(c stytch.Client) *ProjectClient

func (*ProjectClient) Metrics

type SessionsClient

type SessionsClient struct {
	C    stytch.Client
	JWKS *keyfunc.JWKS
}

func NewSessionsClient

func NewSessionsClient(c stytch.Client, jwks *keyfunc.JWKS) *SessionsClient

func (*SessionsClient) Authenticate

Authenticate a session token or session JWT and retrieve associated session data. If `session_duration_minutes` is included, update the lifetime of the session to be that many minutes from now. All timestamps are formatted according to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. This endpoint requires exactly one `session_jwt` or `session_token` as part of the request. If both are included, you will receive a `too_many_session_arguments` error.

You may provide a JWT that needs to be refreshed and is expired according to its `exp` claim. A new JWT will be returned if both the signature and the underlying Session are still valid. See our [How to use Stytch Session JWTs](https://stytch.com/docs/guides/sessions/using-jwts) guide for more information.

func (*SessionsClient) AuthenticateJWT

func (c *SessionsClient) AuthenticateJWT(
	ctx context.Context,
	maxTokenAge time.Duration,
	body *sessions.AuthenticateParams,
) (*sessions.AuthenticateResponse, error)

func (*SessionsClient) AuthenticateJWTLocal

func (c *SessionsClient) AuthenticateJWTLocal(
	token string,
	maxTokenAge time.Duration,
) (*sessions.Session, error)

func (*SessionsClient) AuthenticateJWTWithClaims

func (c *SessionsClient) AuthenticateJWTWithClaims(
	ctx context.Context,
	maxTokenAge time.Duration,
	body *sessions.AuthenticateParams,
	claims map[string]any,
) (*sessions.AuthenticateResponse, error)

func (*SessionsClient) AuthenticateWithClaims

func (c *SessionsClient) AuthenticateWithClaims(
	ctx context.Context,
	body *sessions.AuthenticateParams,
	claims any,
) (*sessions.AuthenticateResponse, error)

AuthenticateWithClaims fills in the claims pointer with custom claims from the response. Pass in a map with the types of values you're expecting so that this function can marshal the claims from the response. See ExampleClient_AuthenticateWithClaims_map, ExampleClient_AuthenticateWithClaims_struct for examples

Example (Map)
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/stytchauth/stytch-go/v15/stytch/consumer/sessions"
	"github.com/stytchauth/stytch-go/v15/stytch/consumer/stytchapi"
)

func main() {
	// If we know that our claims will follow this exact map structure, we can marshal the
	// custom claims from the response into it
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Handle the async JWKS fetch.
		if strings.HasPrefix(r.URL.Path, "/v1/sessions/jwks/") {
			_, _ = w.Write([]byte(`{"keys": []}`))
			return
		}

		// This is the test request
		if r.URL.Path == "/v1/sessions/authenticate" {
			// There are  many other fields in this response, but these are the only ones we need
			// for this test.
			_, _ = w.Write([]byte(`{
			  "session": {
			    "expires_at": "2022-06-29T19:53:48Z",
			    "last_accessed_at": "2022-06-29T17:54:13Z",
			    "session_id": "session-test-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
			    "started_at": "2022-06-29T17:53:48Z",
			    "user_id": "user-test-00000000-0000-0000-0000-000000000000",

			    "custom_claims": {
			      "https://my-app.example.net/custom-claim": {
			        "claim1": 1,
			        "claim2": 2,
			        "claim3": 3
			      }
			    }
			  }
			}`))
			return
		}

		http.Error(w, "Bad Request", http.StatusBadRequest)
	}))

	client, _ := stytchapi.NewClient(
		"project-test-00000000-0000-0000-0000-000000000000",
		"secret-test-11111111-1111-1111-1111-111111111111",
		stytchapi.WithBaseURI(srv.URL),
	)

	// Expecting a map where all the values are maps from strings to integers
	var mapClaims map[string]map[string]int32
	_, _ = client.Sessions.AuthenticateWithClaims(
		context.Background(),
		&sessions.AuthenticateParams{
			SessionToken: "fake session token",
		},
		&mapClaims,
	)

	fmt.Println(mapClaims)
}
Output:

map[https://my-app.example.net/custom-claim:map[claim1:1 claim2:2 claim3:3]]
Example (Struct)
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/stytchauth/stytch-go/v15/stytch/consumer/sessions"
	"github.com/stytchauth/stytch-go/v15/stytch/consumer/stytchapi"
)

func main() {
	// When we define a struct that follows the shape of our claims, we can marshal the
	// custom claims from the response into it
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Handle the async JWKS fetch.
		if strings.HasPrefix(r.URL.Path, "/v1/sessions/jwks/") {
			_, _ = w.Write([]byte(`{"keys": []}`))
			return
		}

		// This is the test request
		if r.URL.Path == "/v1/sessions/authenticate" {
			// There are  many other fields in this response, but these are the only ones we need
			// for this test.
			_, _ = w.Write([]byte(`{
			  "session": {
			    "expires_at": "2022-06-29T19:53:48Z",
			    "last_accessed_at": "2022-06-29T17:54:13Z",
			    "session_id": "session-test-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
			    "started_at": "2022-06-29T17:53:48Z",
			    "user_id": "user-test-00000000-0000-0000-0000-000000000000",

			    "custom_claims": {
			      "https://my-app.example.net/custom-claim": {
			        "number": 1,
			        "array": [1, "foo", null],
			        "nested": {
			          "data": "here"
			        }
			      }
			    }
			  }
			}`))
			return
		}

		http.Error(w, "Bad Request", http.StatusBadRequest)
	}))

	client, _ := stytchapi.NewClient(
		"project-test-00000000-0000-0000-0000-000000000000",
		"secret-test-11111111-1111-1111-1111-111111111111",
		stytchapi.WithBaseURI(srv.URL),
	)

	// Expecting claims to follow this exact data structure
	type MyAppClaims struct {
		Number int
		Array  []interface{}
		Nested struct {
			Data string
		}
	}
	type StructClaims struct {
		MyApp MyAppClaims `json:"https://my-app.example.net/custom-claim"`
	}

	var structClaims StructClaims
	_, _ = client.Sessions.AuthenticateWithClaims(
		context.Background(),
		&sessions.AuthenticateParams{
			SessionToken: "fake session token",
		},
		&structClaims,
	)

	fmt.Println(structClaims)
}
Output:

{{1 [1 foo <nil>] {here}}}

func (*SessionsClient) Get

Get: List all active Sessions for a given `user_id`. All timestamps are formatted according to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`.

func (*SessionsClient) GetJWKS

GetJWKS: Get the JSON Web Key Set (JWKS) for a project.

JWKS are rotated every ~6 months. Upon rotation, new JWTs will be signed using the new key set, and both key sets will be returned by this endpoint for a period of 1 month.

JWTs have a set lifetime of 5 minutes, so there will be a 5 minute period where some JWTs will be signed by the old JWKS, and some JWTs will be signed by the new JWKS. The correct JWKS to use for validation is determined by matching the `kid` value of the JWT and JWKS.

If you're using one of our [backend SDKs](https://stytch.com/docs/sdks), the JWKS roll will be handled for you.

If you're using your own JWT validation library, many have built-in support for JWKS rotation, and you'll just need to supply this API endpoint. If not, your application should decide which JWKS to use for validation by inspecting the `kid` value.

See our [How to use Stytch Session JWTs](https://stytch.com/docs/guides/sessions/using-jwts) guide for more information.

func (*SessionsClient) Migrate added in v15.3.0

Migrate a session from an external OIDC compliant endpoint. Stytch will call the external UserInfo endpoint defined in your Stytch Project settings in the [Dashboard](/dashboard), and then perform a lookup using the `session_token`. If the response contains a valid email address, Stytch will attempt to match that email address with an existing User and create a Stytch Session. You will need to create the user before using this endpoint.

func (*SessionsClient) Revoke

Revoke a Session, immediately invalidating all of its session tokens. You can revoke a session in three ways: using its ID, or using one of its session tokens, or one of its JWTs. This endpoint requires exactly one of those to be included in the request. It will return an error if multiple are present.

type TOTPsClient

type TOTPsClient struct {
	C stytch.Client
}

func NewTOTPsClient

func NewTOTPsClient(c stytch.Client) *TOTPsClient

func (*TOTPsClient) Authenticate

Authenticate a TOTP code entered by a user.

func (*TOTPsClient) AuthenticateWithClaims

func (c *TOTPsClient) AuthenticateWithClaims(
	ctx context.Context,
	body *totps.AuthenticateParams,
	claims any,
) (*totps.AuthenticateResponse, error)

AuthenticateWithClaims fills in the claims pointer with custom claims from the response. Pass in a map with the types of values you're expecting so that this function can marshal the claims from the response. See ExampleClient_AuthenticateWithClaims_map, ExampleClient_AuthenticateWithClaims_struct for examples

func (*TOTPsClient) Create

func (c *TOTPsClient) Create(
	ctx context.Context,
	body *totps.CreateParams,
) (*totps.CreateResponse, error)

Create a new TOTP instance for a user. The user can use the authenticator application of their choice to scan the QR code or enter the secret.

func (*TOTPsClient) Recover

func (c *TOTPsClient) Recover(
	ctx context.Context,
	body *totps.RecoverParams,
) (*totps.RecoverResponse, error)

Recover: Authenticate a recovery code for a TOTP instance.

func (*TOTPsClient) RecoveryCodes

RecoveryCodes: Retrieve the recovery codes for a TOTP instance tied to a User.

type UsersClient

type UsersClient struct {
	C stytch.Client
}

func NewUsersClient

func NewUsersClient(c stytch.Client) *UsersClient

func (*UsersClient) Create

func (c *UsersClient) Create(
	ctx context.Context,
	body *users.CreateParams,
) (*users.CreateResponse, error)

Create: Add a User to Stytch. A `user_id` is returned in the response that can then be used to perform other operations within Stytch. An `email` or a `phone_number` is required.

func (*UsersClient) Delete

func (c *UsersClient) Delete(
	ctx context.Context,
	body *users.DeleteParams,
) (*users.DeleteResponse, error)

Delete a User from Stytch.

func (*UsersClient) DeleteBiometricRegistration

DeleteBiometricRegistration: Delete a biometric registration from a User.

func (*UsersClient) DeleteCryptoWallet

DeleteCryptoWallet: Delete a crypto wallet from a User.

func (*UsersClient) DeleteEmail

DeleteEmail: Delete an email from a User.

func (*UsersClient) DeleteOAuthRegistration

DeleteOAuthRegistration: Delete an OAuth registration from a User.

func (*UsersClient) DeletePassword

DeletePassword: Delete a password from a User.

func (*UsersClient) DeletePhoneNumber

DeletePhoneNumber: Delete a phone number from a User.

func (*UsersClient) DeleteTOTP

DeleteTOTP: Delete a TOTP from a User.

func (*UsersClient) DeleteWebAuthnRegistration

DeleteWebAuthnRegistration: Delete a WebAuthn registration from a User.

func (*UsersClient) ExchangePrimaryFactor

ExchangePrimaryFactor: Exchange a user's email address or phone number for another.

Must pass either an `email_address` or a `phone_number`.

This endpoint only works if the user has exactly one factor. You are able to exchange the type of factor for another as well, i.e. exchange an `email_address` for a `phone_number`.

Use this endpoint with caution as it performs an admin level action.

func (*UsersClient) Get

func (c *UsersClient) Get(
	ctx context.Context,
	body *users.GetParams,
) (*users.GetResponse, error)

Get information about a specific User.

func (*UsersClient) Search

func (c *UsersClient) Search(
	ctx context.Context,
	body *users.SearchParams,
) (*users.SearchResponse, error)

Search for Users within your Stytch Project.

Use the `query` object to filter by different fields. See the `query.operands.filter_value` documentation below for a list of available filters.

### Export all User data

Submit an empty `query` in your Search Users request to return all of your Stytch Project's Users.

[This Github repository](https://github.com/stytchauth/stytch-node-export-users) contains a utility that leverages the Search Users endpoint to export all of your User data to a CSV or JSON file.

func (*UsersClient) Update

func (c *UsersClient) Update(
	ctx context.Context,
	body *users.UpdateParams,
) (*users.UpdateResponse, error)

Update a User's attributes.

**Note:** In order to add a new email address or phone number to an existing User object, pass the new email address or phone number into the respective `/send` endpoint for the authentication method of your choice. If you specify the existing User's `user_id` while calling the `/send` endpoint, the new, unverified email address or phone number will be added to the existing User object. If the user successfully authenticates within 5 minutes of the `/send` request, the new email address or phone number will be marked as verified and remain permanently on the existing Stytch User. Otherwise, it will be removed from the User object, and any subsequent login requests using that phone number will create a new User. We require this process to guard against an account takeover vulnerability.

type WebAuthnClient

type WebAuthnClient struct {
	C stytch.Client
}

func NewWebAuthnClient

func NewWebAuthnClient(c stytch.Client) *WebAuthnClient

func (*WebAuthnClient) Authenticate

Authenticate: Complete the authentication of a Passkey or WebAuthn registration by passing the response from the [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) request to the authenticate endpoint.

If the [webauthn-json](https://github.com/github/webauthn-json) library's `get()` method was used, the response can be passed directly to the [authenticate endpoint](https://stytch.com/docs/api/webauthn-authenticate). If not some fields from the [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) response will need to be converted from array buffers to strings and marshalled into JSON.

func (*WebAuthnClient) AuthenticateStart

AuthenticateStart: Initiate the authentication of a Passkey or WebAuthn registration.

To optimize for Passkeys, set the `return_passkey_credential_options` field to `true`.

After calling this endpoint, the browser will need to call [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) with the data from `public_key_credential_request_options` passed to the [navigator.credentials.get()](https://www.w3.org/TR/webauthn-2/#sctn-getAssertion) request via the public key argument. We recommend using the `get()` wrapper provided by the webauthn-json library.

If you are not using the [webauthn-json](https://github.com/github/webauthn-json) library, `the public_key_credential_request_options` will need to be converted to a suitable public key by unmarshalling the JSON and converting some the fields to array buffers.

func (*WebAuthnClient) AuthenticateWithClaims

func (c *WebAuthnClient) AuthenticateWithClaims(
	ctx context.Context,
	body *webauthn.AuthenticateParams,
	claims any,
) (*webauthn.AuthenticateResponse, error)

AuthenticateWithClaims fills in the claims pointer with custom claims from the response. Pass in a map with the types of values you're expecting so that this function can marshal the claims from the response. See ExampleClient_AuthenticateWithClaims_map, ExampleClient_AuthenticateWithClaims_struct for examples

func (*WebAuthnClient) Register

Register: Complete the creation of a WebAuthn registration by passing the response from the [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) request to this endpoint as the `public_key_credential` parameter.

If the [webauthn-json](https://github.com/github/webauthn-json) library's `create()` method was used, the response can be passed directly to the [register endpoint](https://stytch.com/docs/api/webauthn-register). If not, some fields (the client data and the attestation object) from the [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) response will need to be converted from array buffers to strings and marshalled into JSON.

func (*WebAuthnClient) RegisterStart

RegisterStart: Initiate the process of creating a new Passkey or WebAuthn registration.

To optimize for Passkeys, set the `return_passkey_credential_options` field to `true`.

After calling this endpoint, the browser will need to call [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) with the data from [public_key_credential_creation_options](https://w3c.github.io/webauthn/#dictionary-makecredentialoptions) passed to the [navigator.credentials.create()](https://www.w3.org/TR/webauthn-2/#sctn-createCredential) request via the public key argument. We recommend using the `create()` wrapper provided by the webauthn-json library.

If you are not using the [webauthn-json](https://github.com/github/webauthn-json) library, the `public_key_credential_creation_options` will need to be converted to a suitable public key by unmarshalling the JSON, base64 decoding the user ID field, and converting user ID and the challenge fields into an array buffer.

func (*WebAuthnClient) Update

Update: Updates a Passkey or WebAuthn registration.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL