@adonisjs/auth

  • Version 8.0.9
  • Published
  • 168 kB
  • 3 dependencies
  • MIT license

Install

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

Overview

Offical authentication provider for Adonis framework

Index

Namespaces

namespace @ioc:Adonis/Addons/Auth

module '@ioc:Adonis/Addons/Auth' {}

    variable AuthManager

    const AuthManager: AuthManagerContract;

      interface AuthContract

      interface AuthContract
      extends GuardContract<keyof ProvidersList, keyof GuardsList> {}
      • Instance of the auth contract. The use method can be used to obtain an instance of a given guard mapping for a single HTTP request

      property defaultGuard

      defaultGuard: string;
      • The default guard for the current request

      method use

      use: {
      (): GuardContract<keyof ProvidersList, keyof GuardsList>;
      <K extends never>(guard: K): GuardsList[K]['implementation'];
      };
      • Use a given guard

      interface AuthManagerContract

      interface AuthManagerContract {}
      • Shape of the auth manager to register custom drivers and providers and make instances of them

      property application

      application: ApplicationContract;

        property defaultGuard

        defaultGuard: string;
        • The default guard

        method extend

        extend: {
        (type: 'provider', provider: string, callback: ExtendProviderCallback): void;
        (type: 'guard', guard: string, callback: ExtendGuardCallback): void;
        };
        • Extend by adding custom providers and guards

        method getAuthForRequest

        getAuthForRequest: (ctx: HttpContextContract) => AuthContract;
        • Returns the instance of [[AuthContract]] for a given HTTP request

        method makeMapping

        makeMapping: {
        (ctx: HttpContextContract, mapping: string): GuardContract<
        keyof ProvidersList,
        keyof GuardsList
        >;
        <K extends never>(
        ctx: HttpContextContract,
        mapping: K
        ): GuardsList[K]['implementation'];
        };
        • Make instance of a mapping

        interface BasicAuthGuardContract

        interface BasicAuthGuardContract<
        Provider extends keyof ProvidersList,
        Name extends keyof GuardsList
        > extends Omit<
        GuardContract<Provider, Name>,
        'attempt' | 'login' | 'loginViaId' | 'logout'
        > {}
        • Shape of the basic auth guard

        interface DatabaseProviderContract

        interface DatabaseProviderContract<User extends DatabaseProviderRow>
        extends UserProviderContract<User> {}
        • Database provider

        method after

        after: (
        event: 'findUser',
        callback: (user: DatabaseProviderRow) => Promise<void>
        ) => this;
        • After hooks

        method before

        before: (event: 'findUser', callback: (query: any) => Promise<void>) => this;
        • Before hooks

        method setConnection

        setConnection: (connection: string | QueryClientContract) => this;
        • Define a custom connection for all the provider queries

        interface DatabaseProviderUserBuilder

        interface DatabaseProviderUserBuilder {}
        • Shape of database provider user builder. It must always returns [[ProviderUserContract]]

        construct signature

        new (
        user: DatabaseProviderRow | null,
        config: DatabaseProviderConfig,
        ...args: any[]
        ): ProviderUserContract<DatabaseProviderRow>;

          interface GuardContract

          interface GuardContract<
          Provider extends keyof ProvidersList,
          Guard extends keyof GuardsList
          > {}

            property authenticationAttempted

            authenticationAttempted: boolean;
            • Whether or not the authentication has been attempted for the current request

            property config

            config: GuardsList[Guard]['config'];
            • Reference to the guard config

            property isAuthenticated

            isAuthenticated: boolean;
            • A boolean to know if user is retrieved by authenticating the current request or not.

            property isGuest

            isGuest: boolean;
            • A boolean to know if user is a guest or not. It is always opposite of [[isLoggedIn]]

            property isLoggedIn

            isLoggedIn: boolean;
            • A boolean to know if user is logged in or not

            property isLoggedOut

            isLoggedOut: boolean;
            • Find if the user has been logged out in the current request

            property name

            name: Guard;

              property provider

              provider: ProvidersList[Provider]['implementation'];
              • Reference to the provider for looking up the user

              property user

              user?: GetProviderRealUser<Provider>;
              • Reference to the logged in user.

              method attempt

              attempt: (uid: string, password: string, ...args: any[]) => Promise<any>;
              • Attempt to verify user credentials and perform login

              method authenticate

              authenticate: () => Promise<GetProviderRealUser<Provider>>;
              • Attempts to authenticate the user for the current HTTP request. An exception is raised when unable to do so

              method check

              check: () => Promise<boolean>;
              • Attempts to authenticate the user for the current HTTP request and supresses exceptions raised by the [[authenticate]] method and returns a boolean

              method login

              login: (user: GetProviderRealUser<Provider>, ...args: any[]) => Promise<any>;
              • Login a user without any verification

              method loginViaId

              loginViaId: (id: string | number, ...args: any[]) => Promise<any>;
              • Login a user using their id

              method logout

              logout: (...args: any[]) => Promise<void>;
              • Logout user

              method toJSON

              toJSON: () => any;
              • Serialize guard to JSON

              method verifyCredentials

              verifyCredentials: (
              uid: string,
              password: string
              ) => Promise<GetProviderRealUser<Provider>>;
              • Verify user credentials.

              interface GuardsList

              interface GuardsList {}
              • List of guards mappings used by the app. Using declaration merging, one must extend this interface.

                MUST BE SET IN THE USER LAND.

                Example:

                session: { config: SessionGuardConfig<'lucid'>, implementation: SessionGuardContract<'lucid'>, }

              interface LucidProviderContract

              interface LucidProviderContract<User extends LucidProviderModel>
              extends UserProviderContract<InstanceType<User>> {}
              • Lucid provider

              method after

              after: (
              event: 'findUser',
              callback: (user: InstanceType<User>) => Promise<void>
              ) => this;
              • After hooks

              method before

              before: (event: 'findUser', callback: (query: any) => Promise<void>) => this;
              • Before hooks

              method setConnection

              setConnection: (connection: string | QueryClientContract) => this;
              • Define a custom connection for all the provider queries

              interface LucidProviderUserBuilder

              interface LucidProviderUserBuilder<User extends LucidProviderModel> {}
              • Shape of the lucid provider user builder. It must return [[ProviderUserContract]]

              construct signature

              new (
              user: InstanceType<User> | null,
              config: LucidProviderConfig<User>,
              ...args: any[]
              ): ProviderUserContract<InstanceType<User>>;

                interface OATGuardContract

                interface OATGuardContract<
                Provider extends keyof ProvidersList,
                Name extends keyof GuardsList
                > extends GuardContract<Provider, Name> {}
                • Shape of the OAT guard

                property token

                token?: ProviderTokenContract;

                  property tokenProvider

                  tokenProvider: TokenProviderContract;

                    method attempt

                    attempt: (
                    uid: string,
                    password: string,
                    options?: OATLoginOptions
                    ) => Promise<OpaqueTokenContract<GetProviderRealUser<Provider>>>;
                    • Attempt to verify user credentials and perform login

                    method generate

                    generate: (
                    user: GetProviderRealUser<Provider>,
                    options?: OATLoginOptions
                    ) => Promise<OpaqueTokenContract<GetProviderRealUser<Provider>>>;
                    • Generate token for a user without any verification

                    method login

                    login: (
                    user: GetProviderRealUser<Provider>,
                    options?: OATLoginOptions
                    ) => Promise<OpaqueTokenContract<GetProviderRealUser<Provider>>>;
                    • Login a user without any verification

                    method loginViaId

                    loginViaId: (
                    id: string | number,
                    options?: OATLoginOptions
                    ) => Promise<OpaqueTokenContract<GetProviderRealUser<Provider>>>;
                    • Login a user using their id

                    method revoke

                    revoke: () => Promise<void>;
                    • Alias for logout

                    interface OpaqueTokenContract

                    interface OpaqueTokenContract<User extends any> {}
                    • Opaque token is generated during the login call by the OpaqueTokensGuard

                    property expiresAt

                    expiresAt?: DateTime;
                    • Date/time when the token will be expired

                    property expiresIn

                    expiresIn?: number;
                    • Time in seconds until the token is valid

                    property meta

                    meta: any;
                    • Any meta-data attached with the token

                    property name

                    name: string;
                    • Token name

                    property token

                    token: string;
                    • Token public value

                    property tokenHash

                    tokenHash: string;
                    • Token hash (persisted to the db as well)

                    property type

                    type: 'bearer';
                    • Always a bearer token

                    property user

                    user: User;
                    • The user for which the token was generated

                    method toJSON

                    toJSON: () => {
                    type: 'bearer';
                    token: string;
                    expires_at?: string;
                    expires_in?: number;
                    };
                    • Serialize token

                    interface ProvidersList

                    interface ProvidersList {}
                    • List of providers mappings used by the app. Using declaration merging, one must extend this interface.

                      MUST BE SET IN THE USER LAND.

                      Example:

                      lucid: { config: LucidProviderConfig, implementation: LucidProviderContract, }

                    interface ProviderTokenContract

                    interface ProviderTokenContract {}
                    • Shape of the token sent to/read from the tokens provider

                    property expiresAt

                    expiresAt?: DateTime;
                    • Expiry date

                    property meta

                    meta?: any;
                    • All other token details

                    property name

                    name: string;
                    • Token name

                    property tokenHash

                    tokenHash: string;
                    • Persisted token value. It is a sha256 hash

                    property type

                    type: string;
                    • Token type

                    property userId

                    userId: string | number;
                    • UserId for which the token was saved

                    interface ProviderUserContract

                    interface ProviderUserContract<User extends any> {}
                    • Provider user works as a bridge between the provider real user and the guard. It is never exposed to the end-user.

                    property user

                    user: User | null;

                      property verifyPassword

                      verifyPassword: (plainPassword: string) => Promise<boolean>;

                        method getId

                        getId: () => string | number | null;

                          method getRememberMeToken

                          getRememberMeToken: () => string | null;

                            method setRememberMeToken

                            setRememberMeToken: (token: string) => void;

                              interface SessionGuardContract

                              interface SessionGuardContract<
                              Provider extends keyof ProvidersList,
                              Name extends keyof GuardsList
                              > extends GuardContract<Provider, Name> {}
                              • Shape of the session guard

                              property viaRemember

                              viaRemember: boolean;
                              • A boolean to know if user is loggedin via remember me token or not.

                              method attempt

                              attempt: (uid: string, password: string, remember?: boolean) => Promise<any>;
                              • Attempt to verify user credentials and perform login

                              method login

                              login: (user: GetProviderRealUser<Provider>, remember?: boolean) => Promise<any>;
                              • Login a user without any verification

                              method loginViaId

                              loginViaId: (id: string | number, remember?: boolean) => Promise<any>;
                              • Login a user using their id

                              method logout

                              logout: (renewRememberToken?: boolean) => Promise<void>;
                              • Logout user

                              interface TokenProviderContract

                              interface TokenProviderContract {}
                              • Token providers provides the API to create/fetch and delete tokens for a given user. Any token based implementation can use token providers, given they only store a single token.

                              method destroy

                              destroy: (lookupId: string, type: string) => Promise<void>;
                              • Delete token using the lookup id or the token value

                              method read

                              read: (
                              lookupId: string,
                              token: string,
                              type: string
                              ) => Promise<ProviderTokenContract | null>;
                              • Find token using the lookup id or the token value

                              method setConnection

                              setConnection: (connection: any) => this;
                              • Define a custom connection for the driver in use

                              method write

                              write: (token: ProviderTokenContract) => Promise<string>;
                              • Saves the token to some persistance storage and returns an lookup id. We introduced the concept of lookup ids, since lookups by cryptographic tokens can have performance impacts on certain databases.

                                Also note that the return lookup id is also prepended to the raw token, so that we can later extract the id for reads. The real message is to keep the lookup ids small.

                              interface UserProviderContract

                              interface UserProviderContract<User extends any> {}
                              • The interface that every provider must implement

                              method findById

                              findById: (id: string | number) => Promise<ProviderUserContract<User>>;
                              • Find a user using the primary key value

                              method findByRememberMeToken

                              findByRememberMeToken: (
                              userId: string | number,
                              token: string
                              ) => Promise<ProviderUserContract<User>>;
                              • Find a user using the remember me token

                              method findByUid

                              findByUid: (uid: string) => Promise<ProviderUserContract<User>>;
                              • Find a user by searching for their uids

                              method getUserFor

                              getUserFor: (user: User) => Promise<ProviderUserContract<User>>;
                              • Return an instance of the user wrapped inside the Provider user contract

                              method updateRememberMeToken

                              updateRememberMeToken: (
                              authenticatable: ProviderUserContract<User>
                              ) => Promise<void>;
                              • Update remember token

                              type AuthConfig

                              type AuthConfig = {
                              guard: keyof GuardsList;
                              guards: {
                              [P in keyof GuardsList]: GuardsList[P]['config'];
                              };
                              };
                              • Shape of config accepted by the Auth module. It relies on the [[GuardsList]] interface

                              type BasicAuthAuthenticateEventData

                              type BasicAuthAuthenticateEventData<Provider extends keyof ProvidersList> = {
                              name: string;
                              user: GetProviderRealUser<Provider>;
                              ctx: HttpContextContract;
                              };
                              • Shape of data emitted by the authenticate event

                              type BasicAuthGuardConfig

                              type BasicAuthGuardConfig<Provider extends keyof ProvidersList> = {
                              driver: 'basic';
                              realm?: string;
                              provider: ProvidersList[Provider]['config'];
                              };
                              • Shape of basic auth guard config.

                              type DatabaseProviderConfig

                              type DatabaseProviderConfig = {
                              driver: 'database';
                              uids: string[];
                              usersTable: string;
                              identifierKey: string;
                              connection?: string;
                              hashDriver?: keyof HashersList;
                              user?: () =>
                              | Promise<DatabaseProviderUserBuilder>
                              | Promise<{
                              default: DatabaseProviderUserBuilder;
                              }>;
                              };
                              • The config accepted by the Database provider

                              type DatabaseProviderRow

                              type DatabaseProviderRow = {
                              password?: string;
                              remember_me_token?: string;
                              [key: string]: any;
                              };
                              • Shape of the row returned by the database provider. The table must have password and remember_me_token columns.

                              type DatabaseTokenProviderConfig

                              type DatabaseTokenProviderConfig = {
                              driver: 'database';
                              table: string;
                              foreignKey?: string;
                              connection?: string;
                              type?: string;
                              };
                              • Config for the database token provider

                              type ExtendGuardCallback

                              type ExtendGuardCallback = (
                              auth: AuthManagerContract,
                              mapping: string,
                              config: any,
                              provider: UserProviderContract<any>,
                              ctx: HttpContextContract
                              ) => GuardContract<keyof ProvidersList, keyof GuardsList>;
                              • Shape of the callback accepted to add new guards

                              type ExtendProviderCallback

                              type ExtendProviderCallback = (
                              auth: AuthManagerContract,
                              mapping: string,
                              config: any
                              ) => UserProviderContract<any>;
                              • Shape of the callback accepted to add new user providers

                              type GetProviderRealUser

                              type GetProviderRealUser<Provider extends keyof ProvidersList> = UnWrapProviderUser<
                              Awaited<ReturnType<ProvidersList[Provider]['implementation']['getUserFor']>>
                              >;
                              • Returns the real user from the provider user

                              type LucidProviderConfig

                              type LucidProviderConfig<User extends LucidProviderModel> = {
                              driver: 'lucid';
                              model: () =>
                              | Promise<User>
                              | Promise<{
                              default: User;
                              }>;
                              uids: (keyof InstanceType<User>)[];
                              identifierKey: string;
                              connection?: string;
                              hashDriver?: keyof HashersList;
                              user?: () =>
                              | Promise<LucidProviderUserBuilder<User>>
                              | Promise<{
                              default: LucidProviderUserBuilder<User>;
                              }>;
                              };
                              • The config accepted by the Lucid provider

                              type LucidProviderModel

                              type LucidProviderModel = LucidModel & {
                              findForAuth?: <T extends LucidModel>(
                              this: T,
                              uids: string[],
                              value: any
                              ) => Promise<InstanceType<T>>;
                              } & {
                              new (): LucidRow & {
                              password?: string;
                              rememberMeToken?: string | null;
                              };
                              };
                              • The shape of the user model accepted by the Lucid provider. The model must have password and rememberMeToken attributes.

                              type OATAuthenticateEventData

                              type OATAuthenticateEventData<Provider extends keyof ProvidersList> = {
                              name: string;
                              user: GetProviderRealUser<Provider>;
                              ctx: HttpContextContract;
                              token: ProviderTokenContract;
                              };
                              • Shape of the data emitted by the authenticate event

                              type OATGuardConfig

                              type OATGuardConfig<Provider extends keyof ProvidersList> = {
                              /**
                              * Driver name is always constant
                              */
                              driver: 'oat';
                              /**
                              * Provider for managing tokens
                              */
                              tokenProvider: DatabaseTokenProviderConfig | RedisTokenProviderConfig;
                              /**
                              * User provider
                              */
                              provider: ProvidersList[Provider]['config'];
                              };
                              • Shape of OAT guard config.

                              type OATLoginEventData

                              type OATLoginEventData<Provider extends keyof ProvidersList> = {
                              name: string;
                              user: GetProviderRealUser<Provider>;
                              ctx: HttpContextContract;
                              token: OpaqueTokenContract<GetProviderRealUser<Provider>>;
                              };
                              • Shape of data emitted by the login event

                              type OATLoginOptions

                              type OATLoginOptions = {
                              name?: string;
                              expiresIn?: number | string;
                              } & {
                              [key: string]: any;
                              };
                              • Login options

                              type RedisTokenProviderConfig

                              type RedisTokenProviderConfig = {
                              driver: 'redis';
                              redisConnection: string;
                              foreignKey?: string;
                              type?: string;
                              };
                              • Config for the redis token provider

                              type SessionAuthenticateEventData

                              type SessionAuthenticateEventData<Provider extends keyof ProvidersList> = {
                              name: string;
                              user: GetProviderRealUser<Provider>;
                              ctx: HttpContextContract;
                              viaRemember: boolean;
                              };
                              • Shape of data emitted by the authenticate event

                              type SessionGuardConfig

                              type SessionGuardConfig<Provider extends keyof ProvidersList> = {
                              driver: 'session';
                              provider: ProvidersList[Provider]['config'];
                              };
                              • Shape of session driver config.

                              type SessionLoginEventData

                              type SessionLoginEventData<Provider extends keyof ProvidersList> = {
                              name: string;
                              user: GetProviderRealUser<Provider>;
                              ctx: HttpContextContract;
                              token: string | null;
                              };
                              • Shape of data emitted by the login event

                              namespace @ioc:Adonis/Core/Application

                              module '@ioc:Adonis/Core/Application' {}

                                interface ContainerBindings

                                interface ContainerBindings {}

                                  property 'Adonis/Addons/Auth'

                                  'Adonis/Addons/Auth': AuthManagerContract;

                                    namespace @ioc:Adonis/Core/Event

                                    module '@ioc:Adonis/Core/Event' {}

                                      interface EventsList

                                      interface EventsList {}

                                        property 'adonis:api:authenticate'

                                        'adonis:api:authenticate': OATAuthenticateEventData<keyof ProvidersList>;

                                          property 'adonis:api:login'

                                          'adonis:api:login': OATLoginEventData<keyof ProvidersList>;

                                            property 'adonis:basic:authenticate'

                                            'adonis:basic:authenticate': BasicAuthAuthenticateEventData<keyof ProvidersList>;

                                              property 'adonis:session:authenticate'

                                              'adonis:session:authenticate': SessionAuthenticateEventData<keyof ProvidersList>;

                                                property 'adonis:session:login'

                                                'adonis:session:login': SessionLoginEventData<keyof ProvidersList>;

                                                  namespace @ioc:Adonis/Core/HttpContext

                                                  module '@ioc:Adonis/Core/HttpContext' {}

                                                    interface HttpContextContract

                                                    interface HttpContextContract {}

                                                      property auth

                                                      auth: AuthContract;

                                                        Package Files (5)

                                                        Dependencies (3)

                                                        Dev Dependencies (31)

                                                        Peer Dependencies (4)

                                                        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>