@adonisjs/auth

  • Version 9.1.1
  • Published
  • 324 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

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

function withAuthFinder

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 | undefined;
$isPersisted: boolean;
$isNew: boolean;
$isLocal: boolean;
$dirty: any;
$isDirty: boolean;
$isDeleted: boolean;
$options?: import('@adonisjs/lucid/types/model').ModelOptions | undefined;
$trx?:
| import('@adonisjs/lucid/types/database').TransactionClientContract
| undefined;
$setOptionsAndTrx(
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
): 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:
| import('@adonisjs/lucid/types/querybuilder').OneOrMany<
import('@adonisjs/lucid/types/model').LucidRow
>
| null
): void;
$pushRelated(
key: string,
result:
| import('@adonisjs/lucid/types/querybuilder').OneOrMany<
import('@adonisjs/lucid/types/model').LucidRow
>
| null
): void;
$getRelated(
key: string,
defaultValue?: any
):
| import('@adonisjs/lucid/types/querybuilder').OneOrMany<
import('@adonisjs/lucid/types/model').LucidRow
>
| null
| undefined;
$consumeAdapterResult(
adapterResult: any,
sideloadAttributes?:
| import('@adonisjs/lucid/types/model').ModelObject
| undefined
): void;
$hydrateOriginals(): void;
fill(value: Partial<{}>, allowExtraProperties?: boolean | undefined): any;
merge(value: Partial<{}>, allowExtraProperties?: boolean | undefined): any;
enableForceUpdate(): any;
save(): Promise<any>;
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?:
| import('@adonisjs/lucid/types/model').CherryPickFields
| undefined,
raw?: boolean | undefined
): any;
serializeComputed(
fields?:
| import('@adonisjs/lucid/types/model').CherryPickFields
| undefined
): any;
serializeRelations(fields: undefined, raw: true): { [key: string]: any };
serializeRelations(
cherryPick: { [relation: string]: any },
raw: false | undefined
): any;
serializeRelations(
cherryPick?: { [relation: string]: any },
raw?: boolean | undefined
): any;
serialize(
cherryPick?: import('@adonisjs/lucid/types/model').CherryPick | undefined
): any;
toObject(): any;
toJSON(): any;
related<Name_2 extends undefined>(relation: Name_2): any;
};
hashPassword<T extends unknown>(this: T, user: InstanceType<T>): Promise<void>;
findForAuth<T_1 extends unknown>(
this: T_1,
uids: string[],
value: string
): Promise<InstanceType<T_1>>;
verifyCredentials<T_2 extends unknown>(
this: T_2,
uid: string,
password: string
): Promise<InstanceType<T_2>>;
readonly booted: boolean;
find: <T_3 extends any>(
this: T_3,
value: any,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => Promise<InstanceType<T_3>>;
$columnsDefinitions: Map<
string,
import('@adonisjs/lucid/types/model').ModelColumnOptions
>;
$relationsDefinitions: Map<
string,
import('@adonisjs/lucid/types/relations').RelationshipsContract
>;
$computedDefinitions: Map<
string,
import('@adonisjs/lucid/types/model').ComputedOptions
>;
primaryKey: string;
connection?: string | undefined;
namingStrategy: any;
table: string;
selfAssignPrimaryKey: boolean;
$adapter: any;
useAdapter: (adapter: any) => void;
$hooks: any;
$keys: {
attributesToColumns: import('@adonisjs/lucid/types/model').ModelKeysContract;
attributesToSerialized: import('@adonisjs/lucid/types/model').ModelKeysContract;
columnsToAttributes: import('@adonisjs/lucid/types/model').ModelKeysContract;
columnsToSerialized: import('@adonisjs/lucid/types/model').ModelKeysContract;
serializedToColumns: import('@adonisjs/lucid/types/model').ModelKeysContract;
serializedToAttributes: import('@adonisjs/lucid/types/model').ModelKeysContract;
};
$createFromAdapterResult: <T_4 extends any>(
this: T_4,
result?: import('@adonisjs/lucid/types/model').ModelObject | undefined,
sideloadAttributes?:
| import('@adonisjs/lucid/types/model').ModelObject
| undefined,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => InstanceType<T_4>;
$createMultipleFromAdapterResult: <T_5 extends any>(
this: T_5,
results: import('@adonisjs/lucid/types/model').ModelObject[],
sideloadAttributes?:
| import('@adonisjs/lucid/types/model').ModelObject
| undefined,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => InstanceType<T_5>[];
$addColumn: (name: string, options: any) => any;
$hasColumn: (name: string) => boolean;
$getColumn: (
name: string
) => import('@adonisjs/lucid/types/model').ModelColumnOptions | undefined;
$addComputed: (name: string, options: any) => any;
$hasComputed: (name: string) => boolean;
$getComputed: (
name: string
) => import('@adonisjs/lucid/types/model').ComputedOptions | undefined;
$addRelation: (
name: string,
type: 'hasOne' | 'hasMany' | 'belongsTo' | 'manyToMany' | 'hasManyThrough',
relatedModel: () => import('@adonisjs/lucid/types/model').LucidModel,
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_1 extends 'find' | 'fetch'>(
this: Model_4,
event: Event_1,
handler: any
): void;
<Model_5 extends any>(this: Model_5, event: 'paginate', handler: any): void;
<Model_6 extends any, Event_2 extends any>(
this: Model_6,
event: Event_2,
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_3 extends any>(
this: Model_9,
event: Event_3,
handler: any
): void;
};
create: <T_6 extends any>(
this: T_6,
values: any,
options?:
| import('@adonisjs/lucid/types/model').ModelAssignOptions
| undefined
) => Promise<InstanceType<T_6>>;
createMany: <T_7 extends any>(
this: T_7,
values: any[],
options?:
| import('@adonisjs/lucid/types/model').ModelAssignOptions
| undefined
) => Promise<InstanceType<T_7>[]>;
findOrFail: <T_8 extends any>(
this: T_8,
value: any,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => Promise<InstanceType<T_8>>;
findBy: <T_9 extends any>(
this: T_9,
key: string,
value: any,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => Promise<InstanceType<T_9>>;
findByOrFail: <T_10 extends any>(
this: T_10,
key: string,
value: any,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => Promise<InstanceType<T_10>>;
first: <T_11 extends any>(
this: T_11,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => Promise<InstanceType<T_11>>;
firstOrFail: <T_12 extends any>(
this: T_12,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => Promise<InstanceType<T_12>>;
findMany: <T_13 extends any>(
this: T_13,
value: any[],
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => Promise<InstanceType<T_13>[]>;
firstOrNew: <T_14 extends any>(
this: T_14,
searchPayload: any,
savePayload?: any,
options?:
| import('@adonisjs/lucid/types/model').ModelAssignOptions
| undefined
) => Promise<InstanceType<T_14>>;
firstOrCreate: <T_15 extends any>(
this: T_15,
searchPayload: any,
savePayload?: any,
options?:
| import('@adonisjs/lucid/types/model').ModelAssignOptions
| undefined
) => Promise<InstanceType<T_15>>;
updateOrCreate: <T_16 extends any>(
this: T_16,
searchPayload: any,
updatePayload: any,
options?:
| import('@adonisjs/lucid/types/model').ModelAssignOptions
| undefined
) => Promise<InstanceType<T_16>>;
fetchOrNewUpMany: <T_17 extends any>(
this: T_17,
predicate: string | number | symbol | (string | number | symbol)[],
payload: any[],
options?:
| import('@adonisjs/lucid/types/model').ModelAssignOptions
| undefined
) => Promise<InstanceType<T_17>[]>;
fetchOrCreateMany: <T_18 extends any>(
this: T_18,
predicate: string | number | symbol | (string | number | symbol)[],
payload: any[],
options?:
| import('@adonisjs/lucid/types/model').ModelAssignOptions
| undefined
) => Promise<InstanceType<T_18>[]>;
updateOrCreateMany: <T_19 extends any>(
this: T_19,
predicate: string | number | symbol | (string | number | symbol)[],
payload: any[],
options?:
| import('@adonisjs/lucid/types/model').ModelAssignOptions
| undefined
) => Promise<InstanceType<T_19>[]>;
all: <T_20 extends any>(
this: T_20,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => Promise<InstanceType<T_20>[]>;
query: <Model_10 extends any, Result = InstanceType<Model_10>>(
this: Model_10,
options?:
| import('@adonisjs/lucid/types/model').ModelAdapterOptions
| undefined
) => any;
truncate: (cascade?: boolean | undefined) => Promise<void>;
} & Model;
  • Mixing to add user lookup and password verification methods on a model.

    Under the hood, this mixin defines following methods and hooks

    - beforeSave hook to hash user password - findForAuth method to find a user during authentication - verifyCredentials method to verify user credentials and prevent timing attacks.

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 (9)

          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>