Skip to main content
zerotal

Documentation


Documentation / zerotal / auth / createToken

Function: createToken()

createToken(options): Promise<NewToken>

Defined in: packages/auth/src/PersonalAccessToken.ts:106

Generate a new personal access token for a user.

Parameters

options

tokenableId

number

Primary key of the owning subject (e.g. user.id).

tokenableType?

string

Polymorphic subject type; defaults to "user".

name

string

Human label for the token (shown in a token-management UI).

abilities?

string[]

Scopes granted; omit or use ['*'] for full access.

expiresAt?

Date

Optional absolute expiry; omit for a non-expiring token.

Returns

Promise<NewToken>

A NewToken — the one-time plaintext and the row to insert.

Remarks

Returns the plaintext once — it is never persisted. Only its SHA-256 hash goes into row.token. Persist row yourself and hand plaintext back to the client to use as an Authorization: Bearer <plaintext> credential. A TokenIssued framework event is emitted (keyed by the token hash, since no numeric DB id exists until the row is inserted). Omitting abilities records null on the row, which tokenCan treats as full access.

Example

const { plaintext, row } = await createToken({
  tokenableId: user.id,
  name:        'mobile-app',
  abilities:   ['read', 'write'],
});
// Persist the row, then return `plaintext` to the client once — it is never stored.
await PersonalAccessToken.query().insert(row);

// The client then authenticates with it:
//   fetch('/api/posts', { headers: { Authorization: `Bearer ${plaintext}` } });