@adonisjs/auth

  • Version 9.2.0
  • Published
  • 328 kB
  • 2 dependencies
  • MIT license

Install

npm i @adonisjs/auth
yarn add @adonisjs/auth
pnpm add @adonisjs/auth

Overview

Official authentication provider for Adonis framework

Index

Variables

variable withAuthFinder

let withAuthFinder: (
hash: () => Hash,
options: { uids: string[]; passwordColumnName: string }
) => <Model extends NormalizeConstructor<any>>(
superclass: Model
) => {
new (...args: any[]): {
$attributes: any;
$extras: any;
$original: any;
$preloaded: { [relation: string]: any };
$columns: undefined;
$sideloaded: any;
$primaryKeyValue?: string | number;
$isPersisted: boolean;
$isNew: boolean;
$isLocal: boolean;
$dirty: any;
$isDirty: boolean;
$isDeleted: boolean;
$options?: any;
$trx?: any;
$setOptionsAndTrx(options?: any): void;
useTransaction(trx: any): any;
useConnection(connection: string): any;
$getQueryFor(action: 'insert', client: any): any;
$getQueryFor(action: 'delete' | 'refresh' | 'update', client: any): any;
$setAttribute(key: string, value: any): void;
$getAttribute(key: string): any;
$getAttributeFromCache(key: string, callback: (value: any) => any): any;
$hasRelated(key: string): boolean;
$setRelated(key: string, result: any): void;
$pushRelated(key: string, result: any): void;
$getRelated(key: string, defaultValue?: any): any;
$consumeAdapterResult(adapterResult: any, sideloadAttributes?: any): void;
$hydrateOriginals(): void;
fill(value: Partial<{}>, allowExtraProperties?: boolean): any;
merge(value: Partial<{}>, allowExtraProperties?: boolean): any;
enableForceUpdate(): any;
save(): Promise<any>;
lockForUpdate<T>(callback: (user: any) => T | Promise<T>): Promise<T>;
delete(): Promise<void>;
refresh(): Promise<any>;
load: any;
preload: any;
loadAggregate: <
Self extends unknown,
Name extends any,
RelatedBuilder = Self[Name] extends any ? Self[Name]['subQuery'] : never
>(
name: Name,
callback: (builder: RelatedBuilder) => void
) => any;
loadCount: <
Self_1 extends unknown,
Name_1 extends any,
RelatedBuilder_1 = Self_1[Name_1] extends any
? Self_1[Name_1]['subQuery']
: never
>(
name: Name_1,
callback?: (builder: RelatedBuilder_1) => void
) => any;
serializeAttributes(fields?: any, raw?: boolean): any;
serializeComputed(fields?: any): any;
serializeRelations(fields: undefined, raw: true): { [key: string]: any };
serializeRelations(cherryPick: { [relation: string]: any }, raw: false): any;
serializeRelations(
cherryPick?: { [relation: string]: any },
raw?: boolean
): any;
serialize(cherryPick?: any): any;
toObject(): any;
toJSON(): any;
related<Name_2 extends undefined>(relation: Name_2): any;
};
hashPassword<T_1 extends unknown>(
this: T_1,
user: InstanceType<T_1>
): Promise<void>;
findForAuth<T_2 extends unknown>(
this: T_2,
uids: string[],
value: string
): Promise<InstanceType<T_2>>;
verifyCredentials<T_3 extends unknown>(
this: T_3,
uid: string,
password: string
): Promise<InstanceType<T_3>>;
readonly booted: boolean;
find: <T_4 extends any>(
this: T_4,
value: any,
options?: any
) => Promise<InstanceType<T_4>>;
$columnsDefinitions: Map<string, any>;
$relationsDefinitions: Map<string, any>;
$computedDefinitions: Map<string, any>;
primaryKey: string;
connection?: string;
namingStrategy: any;
table: string;
selfAssignPrimaryKey: boolean;
$adapter: any;
useAdapter: (adapter: any) => void;
$hooks: any;
$keys: {
attributesToColumns: any;
attributesToSerialized: any;
columnsToAttributes: any;
columnsToSerialized: any;
serializedToColumns: any;
serializedToAttributes: any;
};
$createFromAdapterResult: <T_5 extends any>(
this: T_5,
result?: any,
sideloadAttributes?: any,
options?: any
) => InstanceType<T_5>;
$createMultipleFromAdapterResult: <T_6 extends any>(
this: T_6,
results: any[],
sideloadAttributes?: any,
options?: any
) => InstanceType<T_6>[];
$addColumn: (name: string, options: any) => any;
$hasColumn: (name: string) => boolean;
$getColumn: (name: string) => any;
$addComputed: (name: string, options: any) => any;
$hasComputed: (name: string) => boolean;
$getComputed: (name: string) => any;
$addRelation: (
name: string,
type: 'hasOne' | 'hasMany' | 'belongsTo' | 'manyToMany' | 'hasManyThrough',
relatedModel: () => any,
options: any
) => void;
$hasRelation: (name: string) => boolean;
$getRelation: {
<Model_1 extends any, Name_3 extends any>(
this: Model_1,
name: Name_3
): InstanceType<Model_1>[Name_3] extends any
? InstanceType<Model_1>[Name_3]['client']['relation']
: any;
<Model_2 extends any>(this: Model_2, name: string): any;
};
$defineProperty: <Model_3 extends any, Prop extends keyof Model_3>(
this: Model_3,
propertyName: Prop,
defaultValue: Model_3[Prop],
strategy: 'inherit' | 'define' | ((value: Model_3[Prop]) => Model_3[Prop])
) => void;
boot: () => void;
before: {
<Model_4 extends any, Event extends 'find' | 'fetch'>(
this: Model_4,
event: Event,
handler: any
): void;
<Model_5 extends any>(this: Model_5, event: 'paginate', handler: any): void;
<Model_6 extends any, Event_1 extends any>(
this: Model_6,
event: Event_1,
handler: any
): void;
};
after: {
<Model_7 extends any>(this: Model_7, event: 'fetch', handler: any): void;
<Model_8 extends any>(this: Model_8, event: 'paginate', handler: any): void;
<Model_9 extends any, Event_2 extends any>(
this: Model_9,
event: Event_2,
handler: any
): void;
};
create: <T_7 extends any>(
this: T_7,
values: any,
options?: any
) => Promise<InstanceType<T_7>>;
createMany: <T_8 extends any>(
this: T_8,
values: any[],
options?: any
) => Promise<InstanceType<T_8>[]>;
findOrFail: <T_9 extends any>(
this: T_9,
value: any,
options?: any
) => Promise<InstanceType<T_9>>;
findBy: {
<T_10 extends any>(
this: T_10,
clause: Record<string, unknown>,
options?: any
): Promise<InstanceType<T_10>>;
<T_11 extends any>(
this: T_11,
key: string,
value: any,
options?: any
): Promise<InstanceType<T_11>>;
};
findByOrFail: {
<T_12 extends any>(
this: T_12,
clause: Record<string, unknown>,
options?: any
): Promise<InstanceType<T_12>>;
<T_13 extends any>(
this: T_13,
key: string,
value: any,
options?: any
): Promise<InstanceType<T_13>>;
};
findManyBy: {
<T_14 extends any>(
this: T_14,
clause: Record<string, unknown>,
options?: any
): Promise<InstanceType<T_14>[]>;
<T_15 extends any>(
this: T_15,
key: string,
value: any,
options?: any
): Promise<InstanceType<T_15>[]>;
};
first: <T_16 extends any>(
this: T_16,
options?: any
) => Promise<InstanceType<T_16>>;
firstOrFail: <T_17 extends any>(
this: T_17,
options?: any
) => Promise<InstanceType<T_17>>;
findMany: <T_18 extends any>(
this: T_18,
value: any[],
options?: any
) => Promise<InstanceType<T_18>[]>;
firstOrNew: <T_19 extends any>(
this: T_19,
searchPayload: any,
savePayload?: any,
options?: any
) => Promise<InstanceType<T_19>>;
firstOrCreate: <T_20 extends any>(
this: T_20,
searchPayload: any,
savePayload?: any,
options?: any
) => Promise<InstanceType<T_20>>;
updateOrCreate: <T_21 extends any>(
this: T_21,
searchPayload: any,
updatePayload: any,
options?: any
) => Promise<InstanceType<T_21>>;
fetchOrNewUpMany: <T_22 extends any>(
this: T_22,
predicate: string | number | symbol | (string | number | symbol)[],
payload: any[],
options?: any
) => Promise<InstanceType<T_22>[]>;
fetchOrCreateMany: <T_23 extends any>(
this: T_23,
predicate: string | number | symbol | (string | number | symbol)[],
payload: any[],
options?: any
) => Promise<InstanceType<T_23>[]>;
updateOrCreateMany: <T_24 extends any>(
this: T_24,
predicate: string | number | symbol | (string | number | symbol)[],
payload: any[],
options?: any
) => Promise<InstanceType<T_24>[]>;
all: <T_25 extends any>(
this: T_25,
options?: any
) => Promise<InstanceType<T_25>[]>;
query: <Model_10 extends any, Result = InstanceType<Model_10>>(
this: Model_10,
options?: any
) => any;
truncate: (cascade?: boolean) => Promise<void>;
} & Model;
  • Deprecated

    Import withAuthFinder from @adonisjs/auth/mixins/lucid instead

Functions

function configure

configure: (command: Configure) => Promise<void>;
  • Configures the auth package

function defineConfig

defineConfig: <
KnownGuards extends Record<
string,
GuardFactory | GuardConfigProvider<GuardFactory>
>
>(config: {
default: keyof KnownGuards;
guards: KnownGuards;
}) => ConfigProvider<ResolvedAuthConfig<KnownGuards>>;
  • Define configuration for the auth package. The function returns a config provider that is invoked inside the auth service provider

Classes

class Authenticator

class Authenticator<KnownGuards extends Record<string, GuardFactory>> {}
  • Authenticator is used to authenticate incoming HTTP requests using one or more known guards.

constructor

constructor(
ctx: HttpContext,
config: { default: keyof KnownGuards; guards: KnownGuards }
);

    property authenticatedViaGuard

    readonly authenticatedViaGuard: string | number | symbol;
    • Reference to the guard using which the current request has been authenticated.

    property authenticationAttempted

    readonly authenticationAttempted: boolean;
    • Whether or not the authentication has been attempted during the current request. The property returns false when the "authenticate" or "authenticateUsing" methods are not used.

    property defaultGuard

    readonly defaultGuard: string | number | symbol;
    • Name of the default guard

    property isAuthenticated

    readonly isAuthenticated: boolean;
    • A boolean to know if the current request has been authenticated. The property returns false when "authenticate" or "authenticateUsing" methods are not used.

    property user

    readonly user: {};
    • Reference to the currently authenticated user. The property returns undefined when "authenticate" or "authenticateUsing" methods are not used.

    method authenticate

    authenticate: () => Promise<
    {
    [K in keyof KnownGuards]: ReturnType<
    ReturnType<KnownGuards[K]>['getUserOrFail']
    >;
    }[keyof KnownGuards]
    >;
    • Authenticate current request using the default guard. Calling this method multiple times triggers multiple authentication with the guard.

    method authenticateUsing

    authenticateUsing: (
    guards?: (keyof KnownGuards)[],
    options?: { loginRoute?: string }
    ) => Promise<
    {
    [K in keyof KnownGuards]: ReturnType<
    ReturnType<KnownGuards[K]>['getUserOrFail']
    >;
    }[keyof KnownGuards]
    >;
    • Authenticate the request using all of the mentioned guards or the default guard.

      The authentication process will stop after any of the mentioned guards is able to authenticate the request successfully.

      Otherwise, "E_UNAUTHORIZED_ACCESS" will be raised.

    method check

    check: () => Promise<boolean>;
    • Silently attempt to authenticate the request using the default guard. Calling this method multiple times triggers multiple authentication with the guard.

    method getUserOrFail

    getUserOrFail: () => {
    [K in keyof KnownGuards]: ReturnType<
    ReturnType<KnownGuards[K]>['getUserOrFail']
    >;
    }[keyof KnownGuards];
    • Returns an instance of the logged-in user or throws an exception

    method use

    use: <Guard extends keyof KnownGuards>(
    guard?: Guard
    ) => ReturnType<KnownGuards[Guard]>;
    • Returns an instance of a known guard. Guards instances are cached during the lifecycle of an HTTP request.

    class AuthenticatorClient

    class AuthenticatorClient<KnownGuards extends Record<string, GuardFactory>> {}
    • Authenticator client is used to create guard instances for testing. It passes a fake HTTPContext to the guards, so make sure to not call server side APIs that might be relying on a real HTTPContext instance.

    constructor

    constructor(config: { default: keyof KnownGuards; guards: KnownGuards });

      property defaultGuard

      readonly defaultGuard: string | number | symbol;
      • Name of the default guard

      method use

      use: <Guard extends keyof KnownGuards>(
      guard?: Guard
      ) => ReturnType<KnownGuards[Guard]>;
      • Returns an instance of a known guard. Guards instances are cached during the lifecycle of an HTTP request.

      class AuthManager

      class AuthManager<KnownGuards extends Record<string, GuardFactory>> {}
      • Auth manager exposes the API to register and manage authentication guards from the config

      constructor

      constructor(config: { default: keyof KnownGuards; guards: KnownGuards });

        property config

        config: { default: keyof KnownGuards; guards: KnownGuards };

          property defaultGuard

          readonly defaultGuard: string | number | symbol;
          • Name of the default guard

          method createAuthenticator

          createAuthenticator: (ctx: HttpContext) => Authenticator<KnownGuards>;
          • Create an authenticator for a given HTTP request. The authenticator is used to authenticated in incoming HTTP request

          method createAuthenticatorClient

          createAuthenticatorClient: () => AuthenticatorClient<KnownGuards>;
          • Creates an instance of the authenticator client. The client is used to setup authentication state during testing.

          Namespaces

          namespace errors

          module 'build/src/errors.d.ts' {}
          • The "E_UNAUTHORIZED_ACCESS" exception is raised when unable to authenticate an incoming HTTP request.

            The "error.guardDriverName" can be used to know the driver which raised the error.

          variable E_INVALID_CREDENTIALS

          const E_INVALID_CREDENTIALS: {
          new (
          message?: string | undefined,
          options?:
          | (ErrorOptions & {
          code?: string | undefined;
          status?: number | undefined;
          })
          | undefined
          ): {
          identifier: string;
          getResponseMessage(error: any, ctx: HttpContext): string;
          handle(error: any, ctx: HttpContext): Promise<void>;
          name: string;
          help?: string | undefined;
          code?: string | undefined;
          status: number;
          toString(): string;
          message: string;
          stack?: string | undefined;
          cause?: unknown;
          readonly [Symbol.toStringTag]: string;
          };
          status: number;
          code: string;
          help?: string | undefined;
          message?: string | undefined;
          captureStackTrace(
          targetObject: object,
          constructorOpt?: Function | undefined
          ): void;
          prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any;
          stackTraceLimit: number;
          };
          • Exception is raised when user credentials are invalid

          variable E_UNAUTHORIZED_ACCESS

          const E_UNAUTHORIZED_ACCESS: {
          new (
          message: string,
          options: { redirectTo?: string; guardDriverName: string }
          ): {
          redirectTo?: string | undefined;
          identifier: string;
          guardDriverName: string;
          renderers: Record<
          string,
          (message: string, error: any, ctx: HttpContext) => Promise<void> | void
          >;
          getResponseMessage(error: any, ctx: HttpContext): string;
          handle(error: any, ctx: HttpContext): Promise<void>;
          name: string;
          help?: string | undefined;
          code?: string | undefined;
          status: number;
          toString(): string;
          message: string;
          stack?: string | undefined;
          cause?: unknown;
          readonly [Symbol.toStringTag]: string;
          };
          status: number;
          code: string;
          help?: string | undefined;
          message?: string | undefined;
          captureStackTrace(
          targetObject: object,
          constructorOpt?: Function | undefined
          ): void;
          prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any;
          stackTraceLimit: number;
          };
          • The "E_UNAUTHORIZED_ACCESS" exception is raised when unable to authenticate an incoming HTTP request.

            The "error.guardDriverName" can be used to know the driver which raised the error.

          namespace symbols

          module 'build/src/symbols.d.ts' {}
          • A symbol to identify the type of the real user for a given user provider

          variable GUARD_KNOWN_EVENTS

          const GUARD_KNOWN_EVENTS: Symbol;
          • A symbol to identify the type for the events emitted by a guard

          variable PROVIDER_REAL_USER

          const PROVIDER_REAL_USER: Symbol;
          • A symbol to identify the type of the real user for a given user provider

          Package Files (8)

          Dependencies (2)

          Dev Dependencies (48)

          Peer Dependencies (6)

          Badge

          To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

          You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@adonisjs/auth.

          • Markdown
            [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@adonisjs/auth)
          • HTML
            <a href="https://www.jsdocs.io/package/@adonisjs/auth"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>