Skip to main content

Authentication

@webda/auth


Class: Authentication<T>

Defined in: packages/auth/src/authentication.service.ts:126

Shared authentication logic: providers hand a ResolvedIdentity to complete()

Webda Modda​

Authentication

Extends​

  • Service<T, AuthenticationEvents>

Type Parameters​

T​

T extends AuthenticationParameters = AuthenticationParameters

Implements​

  • IAuthenticationService

Constructors​

Constructor​

new Authentication<T>(name, params): Authentication<T>

Defined in: packages/core/lib/services/service.d.ts:72

Service

Parameters​

name​

string

The name of the service

params​

T

The parameters block define in the configuration file

Returns​

Authentication<T>

Inherited from​

Service<T, AuthenticationEvents>.constructor

Properties​

_compiledCapabilities​

protected _compiledCapabilities: Record<string, any>

Defined in: packages/core/lib/services/iservice.d.ts:39

Capabilities detected at compile-time from @WebdaCapability-tagged interfaces.

Populated during Service.resolve by reading the service's entry in webda.module.json. Each key is a capability name (e.g., "request-filter"), and the value is an empty object {} by default. Override getCapabilities to provide capability-specific configuration or to conditionally disable capabilities.

See​

getCapabilities

Implementation of​

IAuthenticationService._compiledCapabilities

Inherited from​

Service._compiledCapabilities


[WEBDA_EVENTS]​

[WEBDA_EVENTS]: AuthenticationEvents

Defined in: packages/core/lib/services/service.d.ts:50

Set the Webda events here

Implementation of​

IAuthenticationService.[WEBDA_EVENTS]

Inherited from​

Service.[WEBDA_EVENTS]


logger​

protected logger: Logger

Defined in: packages/core/lib/services/service.d.ts:59

Logger with class context

Implementation of​

IAuthenticationService.logger

Inherited from​

Service.logger


metrics?​

protected optional metrics?: object

Defined in: packages/auth/src/authentication.service.ts:132

Get metrics

login?​

optional login?: Counter

logout?​

optional logout?: Counter

registration?​

optional registration?: Counter

Implementation of​

IAuthenticationService.metrics

Overrides​

Service.metrics


name​

readonly name: string

Defined in: packages/core/lib/services/iservice.d.ts:19

Implementation of​

IAuthenticationService.name

Inherited from​

Service.name


parameters​

readonly parameters: T

Defined in: packages/core/lib/services/iservice.d.ts:20

Implementation of​

IAuthenticationService.parameters

Inherited from​

Service.parameters


providerMap​

protected providerMap: Map<string, AuthProvider>

Defined in: packages/auth/src/authentication.service.ts:138


createConfiguration?​

static optional createConfiguration?: (params) => any

Defined in: packages/core/lib/services/iservice.d.ts:24

Create configuration set by the application on load

Parameters​

params​

any

Returns​

any

Inherited from​

Service.createConfiguration


filterConfiguration?​

static optional filterConfiguration?: (params) => any

Defined in: packages/core/lib/services/iservice.d.ts:28

Create configuration set by the application on load

Parameters​

params​

any

Returns​

any

Inherited from​

Service.filterConfiguration


Parameters​

static Parameters: typeof AuthenticationParameters = AuthenticationParameters

Defined in: packages/auth/src/authentication.service.ts:130

Service parameters

Overrides​

Service.Parameters

Methods​

__clean()​

abstract __clean(): Promise<void>

Defined in: packages/core/lib/services/service.d.ts:215

Clean the service data, can only be used in test mode

Returns​

Promise<void>

Implementation of​

IAuthenticationService.__clean

Inherited from​

Service.__clean


addListener()​

addListener<Key>(eventName, listener): this

Defined in: packages/core/lib/events/asynceventemitter.d.ts:80

Type Parameters​

Key​

Key extends keyof AuthenticationEvents

Parameters​

eventName​

Key

the event name

listener​

(event) => void | Promise<void>

the event listener

Returns​

this

this for chaining

See​

EventEmitter.addListener

Implementation of​

IAuthenticationService.addListener

Inherited from​

Service.addListener


addRoute()​

protected addRoute(url, methods, executer, openapi?, override?): void

Defined in: packages/core/lib/services/service.d.ts:177

Add a route dynamicaly

Parameters​

url​

string

of the route can contains dynamic part like {uuid}

methods​

HttpMethodType[]

the HTTP methods

executer​

Function

Method to execute for this route

openapi?​

OpenAPIWebdaDefinition

the OpenAPI specification

override?​

boolean

whether to override existing

Returns​

void

Implementation of​

IAuthenticationService.addRoute

Inherited from​

Service.addRoute


applyPolicy()​

applyPolicy(identity): ResolvedIdentity

Defined in: packages/auth/src/authentication.service.ts:384

Apply the email policy of the identity provider (complete() does it too, idempotently) Lets a provider refuse an identity before creating anything

Parameters​

identity​

ResolvedIdentity

resolved identity

Returns​

ResolvedIdentity

the identity to use

Throws​

EmailDomainNotAllowed when the policy refuses it

Throws​

WebdaError.BadRequest when identity.provider is not a registered AuthProvider: an unknown name would escape the email policy of the provider it impersonates


authorizeClientEvent()​

authorizeClientEvent(_event, _context): boolean

Defined in: packages/core/lib/services/service.d.ts:153

Authorize a public event subscription

Parameters​

_event​

string

the event name

_context​

OperationContext

the execution context

Returns​

boolean

true if the condition is met

Implementation of​

IAuthenticationService.authorizeClientEvent

Inherited from​

Service.authorizeClientEvent


complete()​

complete(identity, options?): Promise<AuthResult>

Defined in: packages/auth/src/authentication.service.ts:369

Complete a login for an identity proven by a provider

Parameters​

identity​

ResolvedIdentity

resolved identity

options?​

complete options

newUser?​

boolean

identity.user was just created by the provider: its first ident is not a "link"

Returns​

Promise<AuthResult>

the result

Throws​

IdentLinkedElsewhere when the ident belongs to another user than the logged one

Throws​

AccountExists when the email matches an account the linking policy does not allow

Throws​

RegistrationDisabled when a new user is needed but registration is off

Throws​

WebdaError.BadRequest when identity.provider is not a registered AuthProvider

Implementation of​

IAuthenticationService.complete


completeAs()​

protected completeAs(identity, ctx, retried, newUser?): Promise<AuthResult>

Defined in: packages/auth/src/authentication.service.ts:399

Body of complete, running as system with the request context passed explicitly

Parameters​

identity​

ResolvedIdentity

resolved identity

ctx​

any

request context

retried​

boolean

already retried after a concurrent creation

newUser?​

boolean = false

identity.user was just created by the provider: its first ident is not a "link"

Returns​

Promise<AuthResult>

the result


computeParameters()​

computeParameters(): void

Defined in: packages/core/lib/services/service.d.ts:77

Used to compute or derivate input parameter to attribute

Returns​

void

Deprecated​

Implementation of​

IAuthenticationService.computeParameters

Inherited from​

Service.computeParameters


discoverProviders()​

protected discoverProviders(): void

Defined in: packages/auth/src/authentication.service.ts:179

Collect every service implementing AuthProvider

Returns​

void

Throws​

Error when two providers share the same name


emailPolicyFor()​

protected emailPolicyFor(name): ProviderEmailPolicy

Defined in: packages/auth/src/authentication.service.ts:210

Parameters​

name​

string

provider name

Returns​

ProviderEmailPolicy

the email policy of that provider, undefined for unknown providers or without policy


emit()​

emit<Key>(event, data): Promise<void>

Defined in: packages/core/lib/services/service.d.ts:204

Emit the event with data and wait for Promise to finish if listener returned a Promise

Type Parameters​

Key​

Key extends keyof AuthenticationEvents

Parameters​

event​

Key

the event name

data​

AuthenticationEvents[Key]

the data to process

Returns​

Promise<void>

Implementation of​

IAuthenticationService.emit

Inherited from​

Service.emit


establish()​

protected establish(user, ident, identity, ctx?): Promise<AuthResult>

Defined in: packages/auth/src/authentication.service.ts:516

Write the session, issue tokens, emit Login

Parameters​

user​

string | User

user or uuid

ident​

Ident

ident used

identity​

ResolvedIdentity

resolved identity

ctx?​

any = ...

request context (complete() runs as system, so it passes the real one)

Returns​

Promise<AuthResult>

the result


findIdent()​

protected findIdent(provider, providerUid): Promise<Ident>

Defined in: packages/auth/src/authentication.service.ts:292

Find an ident; with compatibility.v3, a miss falls back to the v3 record "<uid>_<provider>", upgraded on the fly

Parameters​

provider​

string

provider

providerUid​

string

uid

Returns​

Promise<Ident>

the ident when it exists


getCapabilities()​

getCapabilities(): Record<string, any>

Defined in: packages/core/lib/services/iservice.d.ts:61

Return the capabilities of this service.

By default returns capabilities detected at compile-time from

Returns​

Record<string, any>

the result

Webda Capability-tagged​

interfaces in webda.module.json.

Override to disable capabilities based on configuration:

getCapabilities() {
const caps = super.getCapabilities();
if (!this.parameters.enabled) delete caps["request-filter"];
return caps;
}

Implementation of​

IAuthenticationService.getCapabilities

Inherited from​

Service.getCapabilities


getClientEvents()​

getClientEvents(): string[]

Defined in: packages/core/lib/services/service.d.ts:144

Return the events that an external system can subscribe to

Returns​

string[]

the list of results

Implementation of​

IAuthenticationService.getClientEvents

Inherited from​

Service.getClientEvents


getIdentModel()​

getIdentModel(): ModelClass<Ident>

Defined in: packages/auth/src/authentication.service.ts:150

Returns​

ModelClass<Ident>

the configured ident model


getMaxListeners()​

getMaxListeners(): number

Defined in: packages/core/lib/events/asynceventemitter.d.ts:84

Returns​

number

Implementation of​

IAuthenticationService.getMaxListeners

Inherited from​

Service.getMaxListeners


getMetric()​

getMetric<T>(type, configuration): T

Defined in: packages/core/lib/services/service.d.ts:138

Add service name label

Type Parameters​

T​

T = Gauge<string> | Counter<string> | Histogram<string>

Parameters​

type​

CustomConstructor<T, [MetricConfiguration<T>]>

the type to look up

configuration​

MetricConfiguration<T>

the configuration

Returns​

T

the result

Implementation of​

IAuthenticationService.getMetric

Inherited from​

Service.getMetric


getName()​

getName(): string

Defined in: packages/core/lib/services/service.d.ts:209

Get service name

Returns​

string

the result string

Implementation of​

IAuthenticationService.getName

Inherited from​

Service.getName


getOpenApiReplacements()​

getOpenApiReplacements(): any

Defined in: packages/core/lib/services/service.d.ts:182

Return variables for replacement in openapi

Returns​

any

the result

Implementation of​

IAuthenticationService.getOpenApiReplacements

Inherited from​

Service.getOpenApiReplacements


getOperationId()​

getOperationId(id): string

Defined in: packages/core/lib/services/service.d.ts:167

If undefined is returned it cancel the operation registration

Parameters​

id​

string

the identifier

Returns​

string

the result

Implementation of​

IAuthenticationService.getOperationId

Inherited from​

Service.getOperationId


getParameters()​

getParameters(): T

Defined in: packages/core/lib/services/service.d.ts:82

Get the service parameters

Returns​

T

the result

Implementation of​

IAuthenticationService.getParameters

Inherited from​

Service.getParameters


getProvider()​

getProvider(name): AuthProvider

Defined in: packages/auth/src/authentication.service.ts:202

Parameters​

name​

string

provider name

Returns​

AuthProvider

the provider


getProviders()​

getProviders(): ProviderInfo[]

Defined in: packages/auth/src/authentication.service.ts:238

Returns​

ProviderInfo[]

public info of every provider

Implementation of​

IAuthenticationService.getProviders


getService()​

getService<T>(name): ServicesMap[T]

Defined in: packages/core/lib/services/service.d.ts:131

Get a service by name

Type Parameters​

T​

T extends keyof ServicesMap

Parameters​

name​

T

the name to use

Returns​

ServicesMap[T]

the result map

Deprecated​

Use useService, might reconsider

Implementation of​

IAuthenticationService.getService

Inherited from​

Service.getService


getState()​

getState(): ServiceStates

Defined in: packages/core/lib/services/service.d.ts:55

Get the current state

Returns​

ServiceStates

the result

Implementation of​

IAuthenticationService.getState

Inherited from​

Service.getState


getUrl()​

getUrl(url, _methods): string

Defined in: packages/core/lib/services/service.d.ts:161

Return the full path url based on parameters

Parameters​

url​

string

relative url to service

_methods​

HttpMethodType[]

in case we need filtering (like Store)

Returns​

string

absolute url or undefined if need to skip the Route

Implementation of​

IAuthenticationService.getUrl

Inherited from​

Service.getUrl


getUserModel()​

getUserModel(): ModelClass<User>

Defined in: packages/auth/src/authentication.service.ts:143

Returns​

ModelClass<User>

the configured user model


idents()​

idents(): Promise<object[]>

Defined in: packages/auth/src/authentication.service.ts:622

List the current user's idents; with compatibility.v3, listing upgrades the user's v3 ident records first

Returns​

Promise<object[]>

idents of the current user


init()​

init(): Promise<Authentication<T>>

Defined in: packages/auth/src/authentication.service.ts:168

Returns​

Promise<Authentication<T>>

Implementation of​

IAuthenticationService.init

Overrides​

Service.init


initMetrics()​

initMetrics(): void

Defined in: packages/auth/src/authentication.service.ts:267

Returns​

void

Implementation of​

IAuthenticationService.initMetrics

Overrides​

Service.initMetrics


initOperations()​

initOperations(): void

Defined in: packages/core/lib/services/service.d.ts:186

Init the operations from

Returns​

void

Operation​

decorators on this service

Implementation of​

IAuthenticationService.initOperations

Inherited from​

Service.initOperations


legacyIdentKeys()​

protected legacyIdentKeys(pageSize): AsyncGenerator<string>

Defined in: packages/auth/src/authentication.service.ts:758

Enumerate the v3 ident rows: through the ident model, and through the core Ident repository when the ident model is a subclass (its queries only see rows typed as itself or its subclasses)

Parameters​

pageSize​

number

page size

Returns​

AsyncGenerator<string>

the v3 keys found, each once per pass


listeners()​

listeners(eventName): Function[]

Defined in: packages/core/lib/events/asynceventemitter.d.ts:139

Get all listeners for an event

Parameters​

eventName​

keyof AuthenticationEvents

the event name

Returns​

Function[]

the list of results

Implementation of​

IAuthenticationService.listeners

Inherited from​

Service.listeners


listIdents()​

protected listIdents(userId): Promise<Ident[]>

Defined in: packages/auth/src/authentication.service.ts:639

Parameters​

userId​

string

user

Returns​

Promise<Ident[]>

all idents owned by the user


loadCapabilities()​

protected loadCapabilities(): void

Defined in: packages/core/lib/services/service.d.ts:120

Load capabilities from webda.module.json metadata into _compiledCapabilities.

Called during resolve after dependency injection. Reads the service's type name from parameters, looks it up in the application's module metadata (moddas or beans section), and populates _compiledCapabilities with an empty object for each declared capability name.

Fails silently if the application is not available (e.g., in unit tests where services are instantiated without a full application context).

Returns​

void

Example​

// If webda.module.json contains:
// { "moddas": { "MyApp/HawkService": { "capabilities": ["request-filter", "cors-filter"] } } }
// Then after resolve(), this.getCapabilities() returns:
// { "request-filter": {}, "cors-filter": {} }

See​

getCapabilities

Implementation of​

IAuthenticationService.loadCapabilities

Inherited from​

Service.loadCapabilities


loadUser()​

protected loadUser(userId): Promise<User>

Defined in: packages/auth/src/authentication.service.ts:504

Parameters​

userId​

string

uuid

Returns​

Promise<User>

the user


log()​

log(level, ...args): void

Defined in: packages/core/lib/services/service.d.ts:226

Parameters​

level​

WorkerLogLevel

to log

args​

...any[]

additional arguments

Returns​

void

Implementation of​

IAuthenticationService.log

Inherited from​

Service.log


logout()​

logout(): Promise<void>

Defined in: packages/auth/src/authentication.service.ts:591

Logout and revoke the current refresh family; also abandons a pending MFA session

Returns​

Promise<void>

Implementation of​

IAuthenticationService.logout


me()​

me(): Promise<any>

Defined in: packages/auth/src/authentication.service.ts:256

Current user

Returns​

Promise<any>

public entry of the logged user


mfaMethods()​

protected mfaMethods(user): string[]

Defined in: packages/auth/src/authentication.service.ts:324

MFA methods enabled for a user (implemented by sub-project 4)

Parameters​

user​

User

user

Returns​

string[]

enabled methods, empty when MFA is off


migrate()​

migrate(dryRun?, batch?): Promise<MigrationReport>

Defined in: packages/auth/src/authentication.service.ts:732

Migrate v3 authentication data to the v4 layout

Idents: every v3 record ("<providerUid>_<provider>" key) is upgraded to its "<providerUid>:<provider>" record (emails normalised) then deleted; with a custom ident model, the v3 rows typed as the core Webda/Ident are found through its repository too. Upgrading shifts position-based paging, so passes run until one upgrades nothing. Users: a user whose stored record still has the v3 __password is saved again in the v4 password shape. Idempotent: a second run migrates nothing. Failures are reported by key and logged, the migration goes on.

Operator notes:

  • A v3 ident whose upgraded key another user already holds (e.g. two v3 email keys differing only by case) is reported in idents.failed (IDENT_CONFLICT) and kept: decide which user keeps the email, then delete or rename the other v3 row and run the command again.
  • A malformed ident key in the store stops the scan: remove that row manually.
  • Re-running is always safe: migrated records are not touched again.

Parameters​

dryRun?​

boolean = false

only count, write nothing

batch?​

number = 100

page size of the scans

Returns​

Promise<MigrationReport>

the report


migrateIdents()​

protected migrateIdents(report, pageSize): Promise<void>

Defined in: packages/auth/src/authentication.service.ts:798

Upgrade the v3 idents

Parameters​

report​

MigrationReport

report to fill

pageSize​

number

page size

Returns​

Promise<void>


migrateUsers()​

protected migrateUsers(report, pageSize): Promise<void>

Defined in: packages/auth/src/authentication.service.ts:848

Save again the users whose stored record still has the v3 __password

Parameters​

report​

MigrationReport

report to fill

pageSize​

number

page size

Returns​

Promise<void>


off()​

off<Key>(eventName, listener): this

Defined in: packages/core/lib/events/asynceventemitter.d.ts:116

Type Parameters​

Key​

Key extends keyof AuthenticationEvents

Parameters​

eventName​

Key

the event name

listener​

(event) => void

the event listener

Returns​

this

this for chaining

See​

EventEmitter.off

Implementation of​

IAuthenticationService.off

Inherited from​

Service.off


on()​

on<Key>(eventName, listener): this

Defined in: packages/core/lib/events/asynceventemitter.d.ts:102

Type Parameters​

Key​

Key extends keyof AuthenticationEvents

Parameters​

eventName​

Key

the event name

listener​

(event) => void

the event listener

Returns​

this

this for chaining

See​

EventEmitter.once

Implementation of​

IAuthenticationService.on

Inherited from​

Service.on


once()​

once<Key>(eventName, listener): this

Defined in: packages/core/lib/events/asynceventemitter.d.ts:95

Type Parameters​

Key​

Key extends keyof AuthenticationEvents

Parameters​

eventName​

Key

the event name

listener​

(event) => void

the event listener

Returns​

this

this for chaining

See​

EventEmitter.once

Implementation of​

IAuthenticationService.once

Inherited from​

Service.once


providers()​

providers(): ProviderInfo[]

Defined in: packages/auth/src/authentication.service.ts:247

List available login methods

Returns​

ProviderInfo[]

providers


refresh()​

refresh(refreshToken): Promise<IssuedTokens>

Defined in: packages/auth/src/authentication.service.ts:612

Exchange a refresh token

Parameters​

refreshToken​

string

refresh token

Returns​

Promise<IssuedTokens>

new tokens


registerUser()​

registerUser(identity, data?, ctx?): Promise<User>

Defined in: packages/auth/src/authentication.service.ts:336

Create and save a user for an identity

Parameters​

identity​

ResolvedIdentity

resolved identity

data?​

any = {}

extra profile data

ctx?​

any = ...

request context (complete() runs as system, so it passes the real one)

Returns​

Promise<User>

the user


removeAllListeners()​

removeAllListeners<Key>(eventName?): this

Defined in: packages/core/lib/events/asynceventemitter.d.ts:122

Type Parameters​

Key​

Key extends keyof AuthenticationEvents

Parameters​

eventName?​

Key

the event name

Returns​

this

this for chaining

See​

EventEmitter.removeAllListeners

Implementation of​

IAuthenticationService.removeAllListeners

Inherited from​

Service.removeAllListeners


removeListener()​

removeListener<Key>(eventName, listener): this

Defined in: packages/core/lib/events/asynceventemitter.d.ts:109

Type Parameters​

Key​

Key extends keyof AuthenticationEvents

Parameters​

eventName​

Key

the event name

listener​

(event) => void

the event listener

Returns​

this

this for chaining

See​

EventEmitter.removeListener

Implementation of​

IAuthenticationService.removeListener

Inherited from​

Service.removeListener


requireUser()​

protected requireUser(): string

Defined in: packages/auth/src/authentication.service.ts:579

Returns​

string

the logged user id

Throws​

WebdaError.Unauthorized when no fully logged session exists


resolve()​

resolve(): this

Defined in: packages/auth/src/authentication.service.ts:155

Returns​

this

Implementation of​

IAuthenticationService.resolve

Overrides​

Service.resolve


setMaxListeners()​

setMaxListeners(n): this

Defined in: packages/core/lib/events/asynceventemitter.d.ts:88

Parameters​

n​

number

Returns​

this

Implementation of​

IAuthenticationService.setMaxListeners

Inherited from​

Service.setMaxListeners


stop()​

stop(): Promise<void>

Defined in: packages/auth/src/authentication.service.ts:193

Returns​

Promise<void>

Implementation of​

IAuthenticationService.stop

Overrides​

Service.stop


toJSON()​

toJSON(): string

Defined in: packages/core/lib/services/service.d.ts:191

Prevent service to be serialized

Returns​

string

the result

Implementation of​

IAuthenticationService.toJSON

Inherited from​

Service.toJSON


tokensUpdate()​

protected tokensUpdate(ident, tokens): Promise<any>

Defined in: packages/auth/src/authentication.service.ts:566

Patch storing new provider tokens encrypted; also drops plaintext tokens left by an earlier v4 beta (__tokens)

Parameters​

ident​

Ident

the ident

tokens​

any

tokens from the provider, if any

Returns​

Promise<any>

the attributes to patch


toString()​

toString(): string

Defined in: packages/core/lib/services/service.d.ts:91

Return service representation

Returns​

string

the result

Implementation of​

IAuthenticationService.toString

Inherited from​

Service.toString


unlink(provider, providerUid): Promise<void>

Defined in: packages/auth/src/authentication.service.ts:678

Remove one of the current user's idents

Parameters​

provider​

string

provider

providerUid​

string

uid

Returns​

Promise<void>

Throws​

LastLoginMethod when no usable login method would remain (non-email idents, plus email idents when the user has a password), or when it would remove the last email ident of a user with a password