Spaces:
Running
Running
File size: 17,437 Bytes
5c05829 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 | import GoTrueAdminApi from './GoTrueAdminApi';
import { AuthError } from './lib/errors';
import { Fetch } from './lib/fetch';
import { Deferred } from './lib/helpers';
import type { AuthChangeEvent, AuthResponse, AuthTokenResponse, AuthTokenResponsePassword, AuthOtpResponse, CallRefreshTokenResult, GoTrueClientOptions, InitializeResult, OAuthResponse, SSOResponse, Session, SignInWithIdTokenCredentials, SignInWithOAuthCredentials, SignInWithPasswordCredentials, SignInWithPasswordlessCredentials, SignUpWithPasswordCredentials, SignInWithSSO, SignOut, Subscription, SupportedStorage, UserAttributes, UserResponse, VerifyOtpParams, GoTrueMFAApi, ResendParams, AuthFlowType, LockFunc, UserIdentity } from './lib/types';
export default class GoTrueClient {
private static nextInstanceID;
private instanceID;
/**
* Namespace for the GoTrue admin methods.
* These methods should only be used in a trusted server-side environment.
*/
admin: GoTrueAdminApi;
/**
* Namespace for the MFA methods.
*/
mfa: GoTrueMFAApi;
/**
* The storage key used to identify the values saved in localStorage
*/
protected storageKey: string;
protected flowType: AuthFlowType;
protected autoRefreshToken: boolean;
protected persistSession: boolean;
protected storage: SupportedStorage;
protected memoryStorage: {
[key: string]: string;
} | null;
protected stateChangeEmitters: Map<string, Subscription>;
protected autoRefreshTicker: ReturnType<typeof setInterval> | null;
protected visibilityChangedCallback: (() => Promise<any>) | null;
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null;
/**
* Keeps track of the async client initialization.
* When null or not yet resolved the auth state is `unknown`
* Once resolved the the auth state is known and it's save to call any further client methods.
* Keep extra care to never reject or throw uncaught errors
*/
protected initializePromise: Promise<InitializeResult> | null;
protected detectSessionInUrl: boolean;
protected url: string;
protected headers: {
[key: string]: string;
};
protected fetch: Fetch;
protected lock: LockFunc;
protected lockAcquired: boolean;
protected pendingInLock: Promise<any>[];
/**
* Used to broadcast state change events to other tabs listening.
*/
protected broadcastChannel: BroadcastChannel | null;
protected logDebugMessages: boolean;
protected logger: (message: string, ...args: any[]) => void;
/**
* Create a new client for use in the browser.
*/
constructor(options: GoTrueClientOptions);
private _debug;
/**
* Initializes the client session either from the url or from storage.
* This method is automatically called when instantiating the client, but should also be called
* manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
*/
initialize(): Promise<InitializeResult>;
/**
* IMPORTANT:
* 1. Never throw in this method, as it is called from the constructor
* 2. Never return a session from this method as it would be cached over
* the whole lifetime of the client
*/
private _initialize;
/**
* Creates a new user.
*
* Be aware that if a user account exists in the system you may get back an
* error message that attempts to hide this information from the user.
* This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*/
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;
/**
* Log in an existing user with an email and password or phone and password.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or that the
* email/phone and password combination is wrong or that the account can only
* be accessed via social login.
*/
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>;
/**
* Log in an existing user via a third-party provider.
* This method supports the PKCE flow.
*/
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
*/
exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse>;
private _exchangeCodeForSession;
/**
* Allows signing in with an OIDC ID token. The authentication provider used
* should be enabled and configured.
*/
signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
/**
* Log in a user using magiclink or a one-time password (OTP).
*
* If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
* If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
* If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
*
* Be aware that you may get back an error message that will not distinguish
* between the cases where the account does not exist or, that the account
* can only be accessed via social login.
*
* Do note that you will need to configure a Whatsapp sender on Twilio
* if you are using phone sign in with the 'whatsapp' channel. The whatsapp
* channel is not supported on other providers
* at this time.
* This method supports PKCE when an email is passed.
*/
signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>;
/**
* Log in a user given a User supplied OTP or TokenHash received through mobile or email.
*/
verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>;
/**
* Attempts a single-sign on using an enterprise Identity Provider. A
* successful SSO attempt will redirect the current page to the identity
* provider authorization page. The redirect URL is implementation and SSO
* protocol specific.
*
* You can use it by providing a SSO domain. Typically you can extract this
* domain by asking users for their email address. If this domain is
* registered on the Auth instance the redirect will use that organization's
* currently active SSO Identity Provider for the login.
*
* If you have built an organization-specific login page, you can use the
* organization's SSO Identity Provider UUID directly instead.
*/
signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>;
/**
* Sends a reauthentication OTP to the user's email or phone number.
* Requires the user to be signed-in.
*/
reauthenticate(): Promise<AuthResponse>;
private _reauthenticate;
/**
* Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
*/
resend(credentials: ResendParams): Promise<AuthOtpResponse>;
/**
* Returns the session, refreshing it if necessary.
* The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
*/
getSession(): Promise<{
data: {
session: Session;
};
error: null;
} | {
data: {
session: null;
};
error: AuthError;
} | {
data: {
session: null;
};
error: null;
}>;
/**
* Acquires a global lock based on the storage key.
*/
private _acquireLock;
/**
* Use instead of {@link #getSession} inside the library. It is
* semantically usually what you want, as getting a session involves some
* processing afterwards that requires only one client operating on the
* session at once across multiple tabs or processes.
*/
private _useSession;
/**
* NEVER USE DIRECTLY!
*
* Always use {@link #_useSession}.
*/
private __loadSession;
/**
* Gets the current user details if there is an existing session.
* @param jwt Takes in an optional access token jwt. If no jwt is provided, getUser() will attempt to get the jwt from the current session.
*/
getUser(jwt?: string): Promise<UserResponse>;
private _getUser;
/**
* Updates user data for a logged in user.
*/
updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
protected _updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}): Promise<UserResponse>;
/**
* Decodes a JWT (without performing any validation).
*/
private _decodeJWT;
/**
* Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
* If the refresh token or access token in the current session is invalid, an error will be thrown.
* @param currentSession The current session that minimally contains an access token and refresh token.
*/
setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
protected _setSession(currentSession: {
access_token: string;
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Returns a new session, regardless of expiry status.
* Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
* If the current session's refresh token is invalid, an error will be thrown.
* @param currentSession The current session. If passed in, it must contain a refresh token.
*/
refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
protected _refreshSession(currentSession?: {
refresh_token: string;
}): Promise<AuthResponse>;
/**
* Gets the session data from a URL string
*/
private _getSessionFromURL;
/**
* Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
*/
private _isImplicitGrantFlow;
/**
* Checks if the current URL and backing storage contain parameters given by a PKCE flow
*/
private _isPKCEFlow;
/**
* Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event.
*
* For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.
* There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
*
* If using `others` scope, no `SIGNED_OUT` event is fired!
*/
signOut(options?: SignOut): Promise<{
error: AuthError | null;
}>;
protected _signOut({ scope }?: SignOut): Promise<{
error: AuthError | null;
}>;
/**
* Receive a notification every time an auth event happens.
* @param callback A callback function to be invoked when an auth event happens.
*/
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void | Promise<void>): {
data: {
subscription: Subscription;
};
};
private _emitInitialSession;
/**
* Sends a password reset request to an email address. This method supports the PKCE flow.
*
* @param email The email address of the user.
* @param options.redirectTo The URL to send the user to after they click the password reset link.
* @param options.captchaToken Verification token received when the user completes the captcha on the site.
*/
resetPasswordForEmail(email: string, options?: {
redirectTo?: string;
captchaToken?: string;
}): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Gets all the identities linked to a user.
*/
getUserIdentities(): Promise<{
data: {
identities: UserIdentity[];
};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Links an oauth identity to an existing user.
* This method supports the PKCE flow.
*/
linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
/**
* Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
*/
unlinkIdentity(identity: UserIdentity): Promise<{
data: {};
error: null;
} | {
data: null;
error: AuthError;
}>;
/**
* Generates a new JWT.
* @param refreshToken A valid refresh token that was returned on login.
*/
private _refreshAccessToken;
private _isValidSession;
private _handleProviderSignIn;
/**
* Recovers the session from LocalStorage and refreshes
* Note: this method is async to accommodate for AsyncStorage e.g. in React native.
*/
private _recoverAndRefresh;
private _callRefreshToken;
private _notifyAllSubscribers;
/**
* set currentSession and currentUser
* process to _startAutoRefreshToken if possible
*/
private _saveSession;
private _removeSession;
/**
* Removes any registered visibilitychange callback.
*
* {@see #startAutoRefresh}
* {@see #stopAutoRefresh}
*/
private _removeVisibilityChangedCallback;
/**
* This is the private implementation of {@link #startAutoRefresh}. Use this
* within the library.
*/
private _startAutoRefresh;
/**
* This is the private implementation of {@link #stopAutoRefresh}. Use this
* within the library.
*/
private _stopAutoRefresh;
/**
* Starts an auto-refresh process in the background. The session is checked
* every few seconds. Close to the time of expiration a process is started to
* refresh the session. If refreshing fails it will be retried for as long as
* necessary.
*
* If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
* to call this function, it will be called for you.
*
* On browsers the refresh process works only when the tab/window is in the
* foreground to conserve resources as well as prevent race conditions and
* flooding auth with requests. If you call this method any managed
* visibility change callback will be removed and you must manage visibility
* changes on your own.
*
* On non-browser platforms the refresh process works *continuously* in the
* background, which may not be desirable. You should hook into your
* platform's foreground indication mechanism and call these methods
* appropriately to conserve resources.
*
* {@see #stopAutoRefresh}
*/
startAutoRefresh(): Promise<void>;
/**
* Stops an active auto refresh process running in the background (if any).
*
* If you call this method any managed visibility change callback will be
* removed and you must manage visibility changes on your own.
*
* See {@link #startAutoRefresh} for more details.
*/
stopAutoRefresh(): Promise<void>;
/**
* Runs the auto refresh token tick.
*/
private _autoRefreshTokenTick;
/**
* Registers callbacks on the browser / platform, which in-turn run
* algorithms when the browser window/tab are in foreground. On non-browser
* platforms it assumes always foreground.
*/
private _handleVisibilityChange;
/**
* Callback registered with `window.addEventListener('visibilitychange')`.
*/
private _onVisibilityChanged;
/**
* Generates the relevant login URL for a third-party provider.
* @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param options.scopes A space-separated list of scopes granted to the OAuth application.
* @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
*/
private _getUrlForProvider;
private _unenroll;
/**
* {@see GoTrueMFAApi#enroll}
*/
private _enroll;
/**
* {@see GoTrueMFAApi#verify}
*/
private _verify;
/**
* {@see GoTrueMFAApi#challenge}
*/
private _challenge;
/**
* {@see GoTrueMFAApi#challengeAndVerify}
*/
private _challengeAndVerify;
/**
* {@see GoTrueMFAApi#listFactors}
*/
private _listFactors;
/**
* {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
*/
private _getAuthenticatorAssuranceLevel;
}
//# sourceMappingURL=GoTrueClient.d.ts.map |