@ngx-addons/omni-auth-core
Version:
Core library for authentication in Angular applications.
488 lines (469 loc) • 17.7 kB
TypeScript
import { HttpInterceptorFn } from '@angular/common/http';
import * as i0 from '@angular/core';
import { PipeTransform, Signal, ResourceRef, Type, InjectionToken, Provider } from '@angular/core';
import { Observable } from 'rxjs';
import { CanActivateFn } from '@angular/router';
type JwtPayloadType = JwtPayloadStandardClaims & JsonObject;
/**
* @description see https://tools.ietf.org/html/rfc7519#section-4.1 for standard JWT fields (claims)
*/
type JwtPayloadStandardClaims = {
/**
* @description expires at (timestamp in seconds)
*/
exp?: number;
/**
* @description issuer of the token (string or URI)
*/
iss?: string;
/**
* @description audience(s) that the token is intended for (string or array of strings)
*/
aud?: string | string[];
/**
* @description not before - time before which the token must not be accepted for processing (timestamp in seconds)
*/
nbf?: number;
/**
* @description issued at - time at which the token was issued (timestamp in seconds)
*/
iat?: number;
/**
* @description scope - space-separated list of scopes (string)
*/
scope?: string;
/**
* @description JWT ID - unique identifier for the token (string)
*/
jti?: string;
/**
* @description subject - usually a unique identifier of the user (string or URI)
*/
sub?: string;
};
type JsonPrimitive = null | string | number | boolean;
type JsonArray = (JsonPrimitive | JsonObject | JsonArray)[];
type JsonObject = {
[x: string]: JsonPrimitive | JsonArray | JsonObject;
};
declare class JwtToken<EXTRA_CLAIMS = unknown> {
token: string;
payload: JwtPayloadType & EXTRA_CLAIMS;
expireAt: Date | null;
constructor(token: string, payload: JwtPayloadType & EXTRA_CLAIMS);
isExpired(): boolean;
isValid(): boolean;
toString(): string;
}
type TokenFetcher<ID_TOKEN_PAYLOAD_CLAIMS = unknown, ACCESS_TOKEN_PAYLOAD_CLAIMS = unknown> = (refresh: boolean) => Promise<{
idToken: JwtToken<ID_TOKEN_PAYLOAD_CLAIMS>;
accessToken: JwtToken<ACCESS_TOKEN_PAYLOAD_CLAIMS>;
} | null>;
declare class TokenProxy<ID_TOKEN_PAYLOAD_CLAIMS = unknown, ACCESS_TOKEN_PAYLOAD_CLAIMS = unknown> {
protected fetcher: TokenFetcher<ID_TOKEN_PAYLOAD_CLAIMS, ACCESS_TOKEN_PAYLOAD_CLAIMS>;
constructor(fetcher: TokenFetcher<ID_TOKEN_PAYLOAD_CLAIMS, ACCESS_TOKEN_PAYLOAD_CLAIMS>);
getIdToken(): Promise<JwtToken<ID_TOKEN_PAYLOAD_CLAIMS> | null>;
getAccessToken(): Promise<JwtToken<ACCESS_TOKEN_PAYLOAD_CLAIMS> | null>;
}
declare const jwtInterceptor: HttpInterceptorFn;
declare const emailToFullName: (email: string | null | undefined) => string | null;
declare class OmniAuthError {
error: Error | unknown;
constructor(error: Error | unknown);
getErrorMessage(): string;
}
type ActionErrorCode = 'unknown' | 'signInWithRedirectFailure' | 'notVerified' | 'userDoesNotExist' | 'userAlreadyExists' | 'userIsNotConfirmed' | 'alreadySignedIn' | 'incorrectIdentifierOrPassword' | 'invalidConfiguration' | 'cancelledFlow' | 'invalidCode';
declare class FlowError extends OmniAuthError {
source: 'signIn' | 'signInWithProvider' | 'forgotPassword' | 'signUp' | 'confirmSignUp' | 'confirmSignIn' | 'resendSignUpCode' | 'confirmForgotPassword' | 'confirmForgotPasswordLink' | 'changePassword' | 'signOut';
code: ActionErrorCode;
error: Error | unknown;
silent: boolean;
constructor(source: 'signIn' | 'signInWithProvider' | 'forgotPassword' | 'signUp' | 'confirmSignUp' | 'confirmSignIn' | 'resendSignUpCode' | 'confirmForgotPassword' | 'confirmForgotPasswordLink' | 'changePassword' | 'signOut', code: ActionErrorCode, error: Error | unknown, silent?: boolean);
}
declare const defaultContentEmail: {
loggedIn: {
welcomeMessage: string;
welcomeMessageNoDisplayName: string;
};
common: {
identifierLabel: string;
passwordLabel: string;
identifierErrorRequiredText: string;
identifierErrorPatternText: string;
identifierErrorMinLengthText: string;
identifierErrorMaxLengthText: string;
identifierPlaceholder: string;
passwordErrorRequiredText: string;
passwordErrorMinLengthText: string;
passwordPatternText: string;
passwordPlaceholder: string;
codeLabel: string;
codeErrorRequiredText: string;
codePlaceholder: string;
backToSignInLabel: string;
icons: {
back: string;
email: string;
};
};
signIn: {
title: string;
errorSubmitMessage: string;
submitLabel: string;
forgetPassword: string;
};
signUp: {
title: string;
errorSubmitMessage: string;
submitLabel: string;
termsAndConditionsText: string;
termsAndConditionsLinkText: string;
};
confirmationSignUp: {
subTitle: string;
paragraph: string;
linkParagraph: string;
errorSubmitMessage: string;
submitLabel: string;
resendLabel: string;
errorResendMessage: string;
};
confirmationSignIn: {
subTitleEmail: string;
linkSentToEmail: string;
errorSubmitMessage: string;
backButton: string;
submitLabel: string;
};
resetPassword: {
title: string;
sendCodeMessage: string;
providePasswordMessage: string;
repeatPassword: string;
errorSubmitMessage: string;
errorSendCodeMessage: string;
sendCodeLabel: string;
submitLabel: string;
sendLinkMessage: string;
sendLinkLabel: string;
linkSentToEmail: string;
};
socialButtons: {
orLine: string;
signInWithGoogle: string;
signInWithApple: string;
signInWithFacebook: string;
};
errors: {
invalidCode: string;
incorrectIdentifierOrPassword: string;
userDoesNotExist: string;
userIsNotConfirmed: string;
userAlreadyExists: string;
notVerified: string;
alreadySignedIn: string;
signInWithRedirectFailure: string;
invalidConfiguration: string;
cancelledFlow: string;
unknown: string;
};
};
declare const defaultContentUsername: {
common: {
identifierLabel: string;
identifierErrorRequiredText: string;
identifierErrorPatternText: string;
identifierErrorMinLengthText: string;
identifierErrorMaxLengthText: string;
identifierPlaceholder: string;
passwordLabel: string;
passwordErrorRequiredText: string;
passwordErrorMinLengthText: string;
passwordPatternText: string;
passwordPlaceholder: string;
codeLabel: string;
codeErrorRequiredText: string;
codePlaceholder: string;
backToSignInLabel: string;
icons: {
back: string;
email: string;
};
};
errors: {
incorrectIdentifierOrPassword: string;
invalidCode: string;
userDoesNotExist: string;
userIsNotConfirmed: string;
userAlreadyExists: string;
notVerified: string;
alreadySignedIn: string;
signInWithRedirectFailure: string;
invalidConfiguration: string;
cancelledFlow: string;
unknown: string;
};
loggedIn: {
welcomeMessage: string;
welcomeMessageNoDisplayName: string;
};
signIn: {
title: string;
errorSubmitMessage: string;
submitLabel: string;
forgetPassword: string;
};
signUp: {
title: string;
errorSubmitMessage: string;
submitLabel: string;
termsAndConditionsText: string;
termsAndConditionsLinkText: string;
};
confirmationSignUp: {
subTitle: string;
paragraph: string;
linkParagraph: string;
errorSubmitMessage: string;
submitLabel: string;
resendLabel: string;
errorResendMessage: string;
};
confirmationSignIn: {
subTitleEmail: string;
linkSentToEmail: string;
errorSubmitMessage: string;
backButton: string;
submitLabel: string;
};
resetPassword: {
title: string;
sendCodeMessage: string;
providePasswordMessage: string;
repeatPassword: string;
errorSubmitMessage: string;
errorSendCodeMessage: string;
sendCodeLabel: string;
submitLabel: string;
sendLinkMessage: string;
sendLinkLabel: string;
linkSentToEmail: string;
};
socialButtons: {
orLine: string;
signInWithGoogle: string;
signInWithApple: string;
signInWithFacebook: string;
};
};
type ContentConfig = typeof defaultContentEmail;
declare class ErrorMessagePipe implements PipeTransform {
#private;
transform(source: FlowError['source'], messages: ContentConfig['errors']): Signal<string | null>;
static ɵfac: i0.ɵɵFactoryDeclaration<ErrorMessagePipe, never>;
static ɵpipe: i0.ɵɵPipeDeclaration<ErrorMessagePipe, "errorMessage", true>;
}
declare class RuntimeError extends OmniAuthError {
error: Error | unknown;
possibleSolution?: string | undefined;
constructor(error: Error | unknown, possibleSolution?: string | undefined);
}
declare class ActionErrorCollectorService {
#private;
readonly currentError: Signal<FlowError | null>;
reset(): void;
handle(error: FlowError): void;
static ɵfac: i0.ɵɵFactoryDeclaration<ActionErrorCollectorService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<ActionErrorCollectorService>;
}
/**
* Defines common patterns used for validation in the OmniAuth Core library.
*
* These patterns are used for validating passwords and email addresses.
*/
declare const passwordPattern: RegExp;
declare const emailPattern: RegExp;
declare const usernamePattern: RegExp;
declare const phonePattern: RegExp;
declare const patterns_d_emailPattern: typeof emailPattern;
declare const patterns_d_passwordPattern: typeof passwordPattern;
declare const patterns_d_phonePattern: typeof phonePattern;
declare const patterns_d_usernamePattern: typeof usernamePattern;
declare namespace patterns_d {
export {
patterns_d_emailPattern as emailPattern,
patterns_d_passwordPattern as passwordPattern,
patterns_d_phonePattern as phonePattern,
patterns_d_usernamePattern as usernamePattern,
};
}
declare const isError: (response: OmniAuthError | void) => response is OmniAuthError;
type CustomSignInProviderKey = string;
type SocialSignInProviderKey = 'google' | 'facebook' | 'apple' | 'github' | 'microsoft';
type SignInProviderKey = CustomSignInProviderKey | SocialSignInProviderKey;
type AuthState<EXTRA_ACCESS_TOKEN_CLAIMS = unknown, EXTRA_ID_TOKEN_CLAIMS = unknown> = {
state: 'unknown' | 'authenticated' | 'unauthenticated' | 'error';
user?: {
displayName?: string;
email?: string;
fullName?: string;
phone?: string;
verified: boolean;
};
tokens?: TokenProxy<EXTRA_ACCESS_TOKEN_CLAIMS, EXTRA_ID_TOKEN_CLAIMS>;
error?: OmniAuthError;
};
declare abstract class OmniAuthService<EXTRA_ACCESS_TOKEN_CLAIMS = unknown, EXTRA_ID_TOKEN_CLAIMS = unknown> {
abstract authState: ResourceRef<AuthState<EXTRA_ACCESS_TOKEN_CLAIMS, EXTRA_ID_TOKEN_CLAIMS>>;
abstract currentUser: Signal<AuthState['user']>;
abstract connectorConfig: {
identityConfirmation: 'code' | 'link';
resetPasswordConfirmation: 'code' | 'link';
};
/**
* @description An ID token is an artifact that proves that
* the user has been authenticated.
*
* @returns {undefined|null|JwtToken} undefined - means the token is still being loaded,
* null means there is no access token (user not authenticated) JwtToken means the user is authenticated
*/
abstract idToken$: Observable<JwtToken<EXTRA_ID_TOKEN_CLAIMS> | null | undefined>;
/**
* @description The access token is the artifact that allows
* the client application to access the user's resource.
*
* @returns {undefined|null|JwtToken} undefined - means the token is still being loaded,
* null means there is no access token (user not authenticated) JwtToken means the user is authenticated
*/
abstract accessToken$: Observable<JwtToken<EXTRA_ACCESS_TOKEN_CLAIMS> | null | undefined>;
abstract signOut(fromAllDevices?: boolean): Promise<void | FlowError>;
abstract resendSignUpCode(params: {
identifier: string;
}): Promise<void | FlowError>;
abstract signUp(params: {
identifier: string;
password: string;
attributes?: Record<string, string | boolean>;
}): Promise<void | FlowError>;
abstract confirmSignUp(params: {
identifier: string;
code: string;
}): Promise<void | FlowError>;
abstract confirmSignIn(params: {
identifier: string;
code: string;
}): Promise<void | FlowError>;
abstract signIn(params: {
identifier: string;
password?: string;
}): Promise<void | FlowError>;
abstract forgotPassword(params: {
identifier: string;
}): Promise<void | FlowError>;
abstract confirmForgotPassword(params: {
identifier: string;
code?: string;
newPassword: string;
}): Promise<void | FlowError>;
abstract changePassword(params: {
newPassword: string;
}): Promise<void | FlowError>;
abstract signInWithProvider(providerKey: SocialSignInProviderKey | CustomSignInProviderKey): Promise<void | FlowError>;
}
type AuthConfig = {
/**
* Authentication service class
*/
authService: Type<OmniAuthService>;
/**
* User identifier type, default is 'email'
*/
identifierType: 'email' | 'username' | 'phone';
/**
* Passwordless authentication, if true, the user will not be asked for a password
* when logging in, instead the user will receive a code to log in.
*/
passwordlessEnabled: boolean;
/**
* Automatic bearer authentication, if exist interceptor will be added automatically
*/
bearerAuthentication?: {
/**
* List of endpoints that do not require authentication, can be RegExp or string.
* In the case of an empty array, all endpoints will require authentication.
*/
whitelistedEndpoints: (RegExp | string)[];
/**
* Authentication token header name, default is 'Authorization'
*/
headerName?: string;
/**
* Authentication token suffix, default is "Bearer "
*/
headerValuePrefix?: string;
};
/**
* The routing configuration, e.g. redirect after login
*/
routing?: {
/**
* The route to redirect to after successful login
*/
secured: string[];
/**
* The route to redirect to after logout
*/
guest: string[];
};
/**
* Validate data before sending it to the server (it applies to input fields)
*/
validation?: {
/**
* Identifier validation pattern, used in sign-out / sign in method
*/
identifierPattern?: RegExp;
/**
* Password validation pattern, used in sign-out / sign in method
*/
passwordPattern?: RegExp;
};
};
declare const AUTH_CONFIG: InjectionToken<AuthConfig>;
type AuthConfigInput = Partial<AuthConfig> & Pick<AuthConfig, 'authService'>;
declare const configureAuth: (params: AuthConfigInput) => Provider[];
/**
* @description Guard that checks if the user is authenticated user otherwise redirects to the specified route.
* @param config
*/
declare const onlyAuthenticated: (config?: {
/**
* @description The route to redirect if someone is not authenticated. If not provided, will use the default from the AuthConfig.
*/
redirectTo?: string[];
}) => CanActivateFn;
/**
* @description Guard that checks if the user is not authenticated otherwise redirects to the specified route.
* @param config
*/
declare const onlyGuest: (config?: {
/**
* @description The route to in case of unauthenticated user. If not provided, will use the default from the AuthConfig.
*/
redirectTo?: string[];
}) => CanActivateFn;
type AuthStep = 'login' | 'register' | 'reset_password' | 'reset_password_link' | 'confirm_reset_password' | 'confirm_sign_in' | 'confirm_sign_up' | 'confirm_sign_up_link' | 'change_password';
declare class AuthRouteService {
#private;
readonly currentStep: i0.WritableSignal<AuthStep>;
readonly currentIdentifier: i0.WritableSignal<string | null>;
nextStep(state: AuthStep, details?: {
identifier?: string;
}): void;
navigateToGuestPage(_rememberPage?: boolean): Promise<boolean> | undefined;
navigateToSecuredPage(): Promise<boolean> | undefined;
static ɵfac: i0.ɵɵFactoryDeclaration<AuthRouteService, never>;
static ɵprov: i0.ɵɵInjectableDeclaration<AuthRouteService>;
}
export { AUTH_CONFIG, ActionErrorCollectorService, AuthRouteService, ErrorMessagePipe, FlowError, JwtToken, OmniAuthError, OmniAuthService, RuntimeError, TokenProxy, configureAuth, defaultContentEmail, defaultContentUsername, emailToFullName, isError, jwtInterceptor, onlyAuthenticated, onlyGuest, patterns_d as patterns };
export type { AuthConfig, AuthState, ContentConfig, CustomSignInProviderKey, JwtPayloadStandardClaims, JwtPayloadType, SignInProviderKey, SocialSignInProviderKey, TokenFetcher };