Options
All
  • Public
  • Public/Protected
  • All
Menu

Module auth

Auth Module

This package is the underlying auth module of webview platform. You might want to use @machinat/webview unless you want to serve your own web service.

Install

npm install @machinat/core @machinat/http @machinat/auth
# or with yarn
yarn add @machinat/core @machinat/http @machinat/auth

Docs

Check the package reference.

Setup

Here is a simple example to protect your API with auth module:

Back-end

import Machinat, { makeFactoryProvider } from '@machinat/core';
import Http from '@machinat/http';
import Auth from '@machinat/auth';
// add the platforms and the authenticator you need
import { LineServerAuthenticator } from '@machinat/line/auth';

const app = Machinat.createApp({
modules: [
Http.initModule({ /* ... */ }),
Auth.initModule({
apiPath: '/auth',
secret: 'xxx-xxx-xxx-xxx',
}),
],
services: [
// provide authenticators of chat platforms
{ porvide: Auth.AuthenticatorList, withProvider: LineServerAuthenticator },
{ // a simple API route
provide: Http.RequestRouteList,
withProvider: makeFactoryProvider({ deps: [Auth.Controller] })(
authController => ({
path: '/myAPI',
handler: async (req, res) => {
// verify request authorization with AuthController
const verifyResult = await authController.verifyAuth(req);

if (verifyResult.ok) {
res.end(JSON.string({ hello: verifyResult.auth.user.uid }));
} else {
res.writeHead(verifyResult.code);
res.end(JSON.string({ error: verifyResult.reason }));
}
}
})
}),
}
]
});

app.start();

Front-end

import AuthClient from '@machinat/auth/client';
import LineClientAuthenticator from '@machinat/line/auth/client';

(async function main () {
const authClient = new AuthClient({
platform: 'line',
serverUrl: '/auth',
authenticators: [new LineClientAuthenticator({ /* ... */ })],
});

const { token, context } = await authClient.auth();

// use the bearer token to call your API
const response = await fetch({
url: '/myAPI',
headers: { Authorization: `Bearer ${token}` },
});
// use response...
})();

Index

Other

AnyClientAuthenticator: ClientAuthenticator<unknown, unknown, AnyAuthContext>
AnyServerAuthenticator: ServerAuthenticator<unknown, unknown, AnyAuthContext>
AuthApiErrorBody: { error: ErrorMessage; platform: undefined | string }

Type declaration

AuthApiResponseBody: { platform: string; token: string }

Type declaration

  • platform: string
  • token: string
AuthConfigs: { apiRoot?: string; basicAuth?: { appIconUrl?: string; appName?: string; codeMessageComponent?: CodeMessageComponent; loginDuration?: number; maxLoginAttempt?: number; mode?: "loose" | "strict"; verifyCodeDigits?: number }; cookieDomain?: string; cookiePath?: string; cookieSameSite?: "strict" | "lax" | "none"; dataCookieMaxAge?: number; redirectRoot?: string; refreshDuration?: number; secret: string; secure?: boolean; serverUrl: string; tokenLifetime?: number }

Type declaration

  • Optional apiRoot?: string

    The path to the auth api. Default to /

  • Optional basicAuth?: { appIconUrl?: string; appName?: string; codeMessageComponent?: CodeMessageComponent; loginDuration?: number; maxLoginAttempt?: number; mode?: "loose" | "strict"; verifyCodeDigits?: number }

    Initiate basic auth service

    • Optional appIconUrl?: string

      The app image to show while login using basic auth flow

    • Optional appName?: string

      The app name to show while login using basic auth flow

    • Optional codeMessageComponent?: CodeMessageComponent

      The customized component to render code message

    • Optional loginDuration?: number

      Login session duration in seconds. Default to 10 min

    • Optional maxLoginAttempt?: number

      Max time to verify login code. Default to 5

    • Optional mode?: "loose" | "strict"

      The user needs to enter a verify code in strict mode. Default to strict

    • Optional verifyCodeDigits?: number

      The digits of the verify code number. Default to 6

  • Optional cookieDomain?: string

    The domain scope of the auth cookies

  • Optional cookiePath?: string

    The path scope of the auth cookies. Default to '/'

  • Optional cookieSameSite?: "strict" | "lax" | "none"

    The SameSite attribute of the auth cookies. Default to strict

  • Optional dataCookieMaxAge?: number

    The MaxAge of the data cookies in seconds. Default to 5 minute

  • Optional redirectRoot?: string

    The web page entry point to redirect the authorized users to. Can be absolute or relative to serverUrl

  • Optional refreshDuration?: number

    The duration a token can be refreshed in seconds. Default to Infinity

  • secret: string

    The secret for signing auth token

  • Optional secure?: boolean

    Force using HTTPS if set to true

  • serverUrl: string

    The complete server entry point URL

  • Optional tokenLifetime?: number

    The lifetime of the token in seconds. Default to an hour

AuthContext<User, Channel>: { channel: Channel; platform: string; user: User } & AuthContextBase

Type parameters

AuthContextBase: { expireAt: Date; loginAt: Date }

Type declaration

  • expireAt: Date
  • loginAt: Date
AuthPayload<Data>: { data: Data; init: number; platform: string; scope: { domain?: string; path: string } }

Type parameters

  • Data

Type declaration

  • data: Data
  • init: number
  • platform: string
  • scope: { domain?: string; path: string }
    • Optional domain?: string
    • path: string
AuthTokenPayload<Data>: TokenBase & AuthPayload<Data>

Type parameters

  • Data

AuthenticatorCredentialResult<Credential>: { credential: Credential; ok: true } | ErrorResult

Type parameters

  • Credential

CheckDataResult<Context>: { contextDetails: ContextDetails<Context>; ok: true } | ErrorResult

Type parameters

ContextDetails<Context>: Omit<Context, "platform" | "loginAt" | "expireAt">

Type parameters

ContextOfAuthenticator<Authenticator>: Authenticator extends ServerAuthenticator<unknown, unknown, infer Context> ? Context : Authenticator extends ClientAuthenticator<unknown, unknown, infer Context> ? Context : never

Type parameters

DelegateRoutingInfo: Required<RoutingInfo>
ErrorMessage: { code: number; reason: string }

Type declaration

  • code: number
  • reason: string
ErrorPayload: { error: ErrorMessage; platform: string; scope: { domain?: string; path: string } }

Type declaration

  • error: ErrorMessage
  • platform: string
  • scope: { domain?: string; path: string }
    • Optional domain?: string
    • path: string
ErrorTokenPayload: TokenBase & ErrorPayload
RefreshRequestBody: { token: string }

Type declaration

  • token: string
SignRequestBody<Credential>: { credential: Credential; platform: string }

Type parameters

  • Credential

Type declaration

  • credential: Credential
  • platform: string
StatePayload<State>: { platform: string; state: State }

Type parameters

  • State

Type declaration

  • platform: string
  • state: State
StateTokenPayload<State>: TokenBase & StatePayload<State>

Type parameters

  • State

UserOfAuthenticator<Authenticator>: UserOfContext<ContextOfAuthenticator<Authenticator>>

Type parameters

VerifyRequestBody: { token: string }

Type declaration

  • token: string
VerifyResult<Data>: { data: Data; ok: true } | ErrorResult

Type parameters

  • Data

WithHeaders: { headers: IncomingHttpHeaders }

Type declaration

  • headers: IncomingHttpHeaders

Generated using TypeDoc