@adonisjs/auth 9.4.2 → 10.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/build/{chunk-JFTYQIKS.js → chunk-MSPAYMZE.js} +110 -4
  2. package/build/{chunk-MUPAP5IP.js → chunk-S5G5RTJX.js} +40 -0
  3. package/build/index.d.ts +8 -8
  4. package/build/index.js +2 -2
  5. package/build/modules/access_tokens_guard/access_token.d.ts +103 -0
  6. package/build/modules/access_tokens_guard/crc32.d.ts +39 -0
  7. package/build/modules/access_tokens_guard/define_config.d.ts +4 -4
  8. package/build/modules/access_tokens_guard/guard.d.ts +82 -5
  9. package/build/modules/access_tokens_guard/main.d.ts +5 -5
  10. package/build/modules/access_tokens_guard/main.js +339 -4
  11. package/build/modules/access_tokens_guard/token_providers/db.d.ts +102 -4
  12. package/build/modules/access_tokens_guard/types.d.ts +2 -2
  13. package/build/modules/access_tokens_guard/user_providers/lucid.d.ts +77 -4
  14. package/build/modules/basic_auth_guard/define_config.d.ts +4 -4
  15. package/build/modules/basic_auth_guard/guard.d.ts +16 -3
  16. package/build/modules/basic_auth_guard/main.d.ts +3 -3
  17. package/build/modules/basic_auth_guard/main.js +11 -1
  18. package/build/modules/basic_auth_guard/types.d.ts +1 -1
  19. package/build/modules/basic_auth_guard/user_providers/lucid.d.ts +19 -2
  20. package/build/modules/session_guard/define_config.d.ts +4 -4
  21. package/build/modules/session_guard/guard.d.ts +42 -3
  22. package/build/modules/session_guard/main.d.ts +5 -5
  23. package/build/modules/session_guard/main.js +349 -124
  24. package/build/modules/session_guard/remember_me_token.d.ts +64 -0
  25. package/build/modules/session_guard/token_providers/db.d.ts +92 -2
  26. package/build/modules/session_guard/types.d.ts +2 -2
  27. package/build/modules/session_guard/user_providers/lucid.d.ts +78 -5
  28. package/build/providers/auth_provider.d.ts +22 -1
  29. package/build/providers/auth_provider.js +16 -3
  30. package/build/services/auth.d.ts +1 -1
  31. package/build/src/auth_manager.d.ts +25 -4
  32. package/build/src/authenticator.d.ts +61 -3
  33. package/build/src/authenticator_client.d.ts +18 -1
  34. package/build/src/define_config.d.ts +19 -1
  35. package/build/src/errors.d.ts +35 -2
  36. package/build/src/middleware/initialize_auth_middleware.d.ts +15 -2
  37. package/build/src/middleware/initialize_auth_middleware.js +10 -0
  38. package/build/src/mixins/lucid.d.ts +13 -0
  39. package/build/src/mixins/lucid.js +27 -2
  40. package/build/src/plugins/japa/api_client.d.ts +10 -1
  41. package/build/src/plugins/japa/browser_client.d.ts +10 -1
  42. package/build/src/types.d.ts +141 -29
  43. package/package.json +38 -37
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-2VRS2VHB.js";
4
4
  import {
5
5
  E_UNAUTHORIZED_ACCESS
6
- } from "./chunk-MUPAP5IP.js";
6
+ } from "./chunk-S5G5RTJX.js";
7
7
 
8
8
  // src/authenticator.ts
9
9
  import { RuntimeException } from "@adonisjs/core/exceptions";
@@ -85,14 +85,31 @@ var Authenticator = class {
85
85
  }
86
86
  return this.use(this.#authenticationAttemptedViaGuard).authenticationAttempted;
87
87
  }
88
+ /**
89
+ * Creates a new Authenticator instance
90
+ *
91
+ * @param ctx - The HTTP context for the current request
92
+ * @param config - Configuration object containing default guard and available guards
93
+ *
94
+ * @example
95
+ * const authenticator = new Authenticator(ctx, {
96
+ * default: 'web',
97
+ * guards: { web: sessionGuard }
98
+ * })
99
+ */
88
100
  constructor(ctx, config) {
89
101
  this.#ctx = ctx;
90
102
  this.#config = config;
91
103
  debug_default("creating authenticator. config %O", this.#config);
92
104
  }
93
105
  /**
94
- * Returns an instance of the logged-in user or throws an
95
- * exception
106
+ * Returns an instance of the logged-in user or throws an exception
107
+ *
108
+ * @throws {RuntimeException} When authentication has not been attempted
109
+ *
110
+ * @example
111
+ * const user = auth.getUserOrFail()
112
+ * console.log(user.id)
96
113
  */
97
114
  getUserOrFail() {
98
115
  if (!this.#authenticationAttemptedViaGuard) {
@@ -105,6 +122,12 @@ var Authenticator = class {
105
122
  /**
106
123
  * Returns an instance of a known guard. Guards instances are
107
124
  * cached during the lifecycle of an HTTP request.
125
+ *
126
+ * @param guard - Optional guard name. Uses default guard if not provided
127
+ *
128
+ * @example
129
+ * const sessionGuard = auth.use('session')
130
+ * const defaultGuard = auth.use()
108
131
  */
109
132
  use(guard) {
110
133
  const guardToUse = guard || this.#config.default;
@@ -123,6 +146,12 @@ var Authenticator = class {
123
146
  * Authenticate current request using the default guard. Calling this
124
147
  * method multiple times triggers multiple authentication with the
125
148
  * guard.
149
+ *
150
+ * @throws {E_UNAUTHORIZED_ACCESS} When authentication fails
151
+ *
152
+ * @example
153
+ * const user = await auth.authenticate()
154
+ * console.log('Authenticated user:', user.email)
126
155
  */
127
156
  async authenticate() {
128
157
  await this.authenticateUsing();
@@ -132,6 +161,12 @@ var Authenticator = class {
132
161
  * Silently attempt to authenticate the request using the default
133
162
  * guard. Calling this method multiple times triggers multiple
134
163
  * authentication with the guard.
164
+ *
165
+ * @example
166
+ * const isAuthenticated = await auth.check()
167
+ * if (isAuthenticated) {
168
+ * console.log('User is authenticated')
169
+ * }
135
170
  */
136
171
  async check() {
137
172
  this.#authenticationAttemptedViaGuard = this.defaultGuard;
@@ -149,6 +184,15 @@ var Authenticator = class {
149
184
  * guards is able to authenticate the request successfully.
150
185
  *
151
186
  * Otherwise, "E_UNAUTHORIZED_ACCESS" will be raised.
187
+ *
188
+ * @param guards - Array of guard names to try for authentication
189
+ * @param options - Options object with optional loginRoute for redirects
190
+ *
191
+ * @throws {E_UNAUTHORIZED_ACCESS} When none of the guards can authenticate
192
+ *
193
+ * @example
194
+ * const user = await auth.authenticateUsing(['session', 'api'])
195
+ * const userWithRedirect = await auth.authenticateUsing(['web'], { loginRoute: '/login' })
152
196
  */
153
197
  async authenticateUsing(guards, options) {
154
198
  const guardsToUse = guards || [this.defaultGuard];
@@ -168,6 +212,30 @@ var Authenticator = class {
168
212
  redirectTo: options?.loginRoute
169
213
  });
170
214
  }
215
+ /**
216
+ * Silently attempt to authenticate the request using all of the mentioned guards
217
+ * or the default guard. Calling this method multiple times triggers multiple
218
+ * authentication with the guard.
219
+ *
220
+ * @param guards - Array of guard names to check. Defaults to default guard
221
+ *
222
+ * @example
223
+ * const isAuthenticated = await auth.checkUsing(['session', 'api'])
224
+ * if (isAuthenticated) {
225
+ * const user = auth.user
226
+ * }
227
+ */
228
+ async checkUsing(guards = [this.defaultGuard]) {
229
+ for (const name of guards) {
230
+ this.#authenticationAttemptedViaGuard = name;
231
+ const isAuthenticated = await this.use(name).check();
232
+ if (isAuthenticated) {
233
+ this.#authenticatedViaGuard = name;
234
+ return true;
235
+ }
236
+ }
237
+ return false;
238
+ }
171
239
  };
172
240
 
173
241
  // src/authenticator_client.ts
@@ -187,6 +255,17 @@ var AuthenticatorClient = class {
187
255
  get defaultGuard() {
188
256
  return this.#config.default;
189
257
  }
258
+ /**
259
+ * Creates a new AuthenticatorClient instance for testing
260
+ *
261
+ * @param config - Configuration object containing default guard and available guards
262
+ *
263
+ * @example
264
+ * const client = new AuthenticatorClient({
265
+ * default: 'web',
266
+ * guards: { web: sessionGuard }
267
+ * })
268
+ */
190
269
  constructor(config) {
191
270
  this.#config = config;
192
271
  debug_default("creating authenticator client. config %O", this.#config);
@@ -194,6 +273,12 @@ var AuthenticatorClient = class {
194
273
  /**
195
274
  * Returns an instance of a known guard. Guards instances are
196
275
  * cached during the lifecycle of an HTTP request.
276
+ *
277
+ * @param guard - Optional guard name. Uses default guard if not provided
278
+ *
279
+ * @example
280
+ * const sessionGuard = client.use('session')
281
+ * const defaultGuard = client.use()
197
282
  */
198
283
  use(guard) {
199
284
  const guardToUse = guard || this.#config.default;
@@ -212,6 +297,17 @@ var AuthenticatorClient = class {
212
297
 
213
298
  // src/auth_manager.ts
214
299
  var AuthManager = class {
300
+ /**
301
+ * Creates a new AuthManager instance
302
+ *
303
+ * @param config - Configuration object containing default guard and available guards
304
+ *
305
+ * @example
306
+ * const manager = new AuthManager({
307
+ * default: 'web',
308
+ * guards: { web: sessionGuard, api: tokenGuard }
309
+ * })
310
+ */
215
311
  constructor(config) {
216
312
  this.config = config;
217
313
  this.config = config;
@@ -224,7 +320,13 @@ var AuthManager = class {
224
320
  }
225
321
  /**
226
322
  * Create an authenticator for a given HTTP request. The authenticator
227
- * is used to authenticated in incoming HTTP request
323
+ * is used to authenticate incoming HTTP requests
324
+ *
325
+ * @param ctx - The HTTP context for the current request
326
+ *
327
+ * @example
328
+ * const authenticator = manager.createAuthenticator(ctx)
329
+ * const user = await authenticator.authenticate()
228
330
  */
229
331
  createAuthenticator(ctx) {
230
332
  return new Authenticator(ctx, this.config);
@@ -232,6 +334,10 @@ var AuthManager = class {
232
334
  /**
233
335
  * Creates an instance of the authenticator client. The client is
234
336
  * used to setup authentication state during testing.
337
+ *
338
+ * @example
339
+ * const client = manager.createAuthenticatorClient()
340
+ * const guard = client.use('session')
235
341
  */
236
342
  createAuthenticatorClient() {
237
343
  return new AuthenticatorClient(this.config);
@@ -108,6 +108,13 @@ var E_UNAUTHORIZED_ACCESS = class extends Exception {
108
108
  * Returns the message to be sent in the HTTP response.
109
109
  * Feel free to override this method and return a custom
110
110
  * response.
111
+ *
112
+ * @param error - The error instance
113
+ * @param ctx - The HTTP context
114
+ *
115
+ * @example
116
+ * const message = error.getResponseMessage(error, ctx)
117
+ * console.log('Error message:', message)
111
118
  */
112
119
  getResponseMessage(error, ctx) {
113
120
  if ("i18n" in ctx) {
@@ -115,6 +122,18 @@ var E_UNAUTHORIZED_ACCESS = class extends Exception {
115
122
  }
116
123
  return error.message;
117
124
  }
125
+ /**
126
+ * Creates a new E_UNAUTHORIZED_ACCESS exception
127
+ *
128
+ * @param message - The error message
129
+ * @param options - Options including redirectTo and guardDriverName
130
+ *
131
+ * @example
132
+ * throw new E_UNAUTHORIZED_ACCESS('Access denied', {
133
+ * guardDriverName: 'session',
134
+ * redirectTo: '/login'
135
+ * })
136
+ */
118
137
  constructor(message, options) {
119
138
  super(message, {});
120
139
  this.guardDriverName = options.guardDriverName;
@@ -122,6 +141,13 @@ var E_UNAUTHORIZED_ACCESS = class extends Exception {
122
141
  }
123
142
  /**
124
143
  * Converts exception to an HTTP response
144
+ *
145
+ * @param error - The error instance
146
+ * @param ctx - The HTTP context
147
+ *
148
+ * @example
149
+ * // This method is called automatically by AdonisJS
150
+ * await error.handle(error, ctx)
125
151
  */
126
152
  async handle(error, ctx) {
127
153
  const renderer = this.renderers[this.guardDriverName];
@@ -143,6 +169,13 @@ var E_INVALID_CREDENTIALS = class extends Exception {
143
169
  * Returns the message to be sent in the HTTP response.
144
170
  * Feel free to override this method and return a custom
145
171
  * response.
172
+ *
173
+ * @param error - The error instance
174
+ * @param ctx - The HTTP context
175
+ *
176
+ * @example
177
+ * const message = error.getResponseMessage(error, ctx)
178
+ * console.log('Error message:', message)
146
179
  */
147
180
  getResponseMessage(error, ctx) {
148
181
  if ("i18n" in ctx) {
@@ -152,6 +185,13 @@ var E_INVALID_CREDENTIALS = class extends Exception {
152
185
  }
153
186
  /**
154
187
  * Converts exception to an HTTP response
188
+ *
189
+ * @param error - The error instance
190
+ * @param ctx - The HTTP context
191
+ *
192
+ * @example
193
+ * // This method is called automatically by AdonisJS
194
+ * await error.handle(error, ctx)
155
195
  */
156
196
  async handle(error, ctx) {
157
197
  const message = this.getResponseMessage(error, ctx);
package/build/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- export * as errors from './src/errors.js';
2
- export { configure } from './configure.js';
3
- export * as symbols from './src/symbols.js';
4
- export { AuthManager } from './src/auth_manager.js';
5
- export { defineConfig } from './src/define_config.js';
6
- export { Authenticator } from './src/authenticator.js';
7
- export { AuthenticatorClient } from './src/authenticator_client.js';
8
- import type { withAuthFinder as withAuthFinderType } from './src/mixins/lucid.js';
1
+ export * as errors from './src/errors.ts';
2
+ export { configure } from './configure.ts';
3
+ export * as symbols from './src/symbols.ts';
4
+ export { AuthManager } from './src/auth_manager.ts';
5
+ export { defineConfig } from './src/define_config.ts';
6
+ export { Authenticator } from './src/authenticator.ts';
7
+ export { AuthenticatorClient } from './src/authenticator_client.ts';
8
+ import type { withAuthFinder as withAuthFinderType } from './src/mixins/lucid.ts';
9
9
  /**
10
10
  * @deprecated Import `withAuthFinder` from `@adonisjs/auth/mixins/lucid` instead
11
11
  */
package/build/index.js CHANGED
@@ -2,11 +2,11 @@ import {
2
2
  AuthManager,
3
3
  Authenticator,
4
4
  AuthenticatorClient
5
- } from "./chunk-JFTYQIKS.js";
5
+ } from "./chunk-MSPAYMZE.js";
6
6
  import "./chunk-2VRS2VHB.js";
7
7
  import {
8
8
  errors_exports
9
- } from "./chunk-MUPAP5IP.js";
9
+ } from "./chunk-S5G5RTJX.js";
10
10
  import {
11
11
  __export
12
12
  } from "./chunk-UXA4FHST.js";
@@ -5,6 +5,20 @@ import { Secret } from '@adonisjs/core/helpers';
5
5
  *
6
6
  * It encapsulates the logic of creating an opaque token, generating
7
7
  * its hash and verifying its hash.
8
+ *
9
+ * @example
10
+ * const token = new AccessToken({
11
+ * identifier: 1,
12
+ * tokenableId: 123,
13
+ * type: 'api',
14
+ * hash: 'sha256hash',
15
+ * createdAt: new Date(),
16
+ * updatedAt: new Date(),
17
+ * lastUsedAt: null,
18
+ * expiresAt: null,
19
+ * name: 'API Token',
20
+ * abilities: ['read', 'write']
21
+ * })
8
22
  */
9
23
  export declare class AccessToken {
10
24
  /**
@@ -13,6 +27,16 @@ export declare class AccessToken {
13
27
  *
14
28
  * Returns null when unable to decode the token because of
15
29
  * invalid format or encoding.
30
+ *
31
+ * @param prefix - The token prefix to validate against
32
+ * @param value - The token value to decode
33
+ *
34
+ * @example
35
+ * const decoded = AccessToken.decode('oat_', 'oat_abc123.def456')
36
+ * if (decoded) {
37
+ * console.log('Token ID:', decoded.identifier)
38
+ * console.log('Secret:', decoded.secret.release())
39
+ * }
16
40
  */
17
41
  static decode(prefix: string, value: string): null | {
18
42
  identifier: string;
@@ -21,6 +45,14 @@ export declare class AccessToken {
21
45
  /**
22
46
  * Creates a transient token that can be shared with the persistence
23
47
  * layer.
48
+ *
49
+ * @param userId - The ID of the user for whom the token is created
50
+ * @param size - The size of the random secret to generate
51
+ * @param expiresIn - Optional expiration time (seconds or duration string)
52
+ *
53
+ * @example
54
+ * const transientToken = AccessToken.createTransientToken(123, 32, '7d')
55
+ * // Store transientToken in database
24
56
  */
25
57
  static createTransientToken(userId: string | number | BigInt, size: number, expiresIn?: string | number): {
26
58
  secret: Secret<string>;
@@ -32,6 +64,13 @@ export declare class AccessToken {
32
64
  * Creates a secret opaque token and its hash. The secret is
33
65
  * suffixed with a crc32 checksum for secret scanning tools
34
66
  * to easily identify the token.
67
+ *
68
+ * @param size - The size of the random string to generate
69
+ *
70
+ * @example
71
+ * const { secret, hash } = AccessToken.seed(32)
72
+ * console.log('Secret:', secret.release())
73
+ * console.log('Hash:', hash)
35
74
  */
36
75
  static seed(size: number): {
37
76
  secret: Secret<string>;
@@ -88,6 +127,25 @@ export declare class AccessToken {
88
127
  * is an array of abritary string values
89
128
  */
90
129
  abilities: string[];
130
+ /**
131
+ * Creates a new AccessToken instance
132
+ *
133
+ * @param attributes - Token attributes including identifier, user ID, type, hash, etc.
134
+ *
135
+ * @example
136
+ * const token = new AccessToken({
137
+ * identifier: 1,
138
+ * tokenableId: 123,
139
+ * type: 'api',
140
+ * hash: 'sha256hash',
141
+ * createdAt: new Date(),
142
+ * updatedAt: new Date(),
143
+ * lastUsedAt: null,
144
+ * expiresAt: new Date(Date.now() + 86400000),
145
+ * name: 'Mobile App Token',
146
+ * abilities: ['read:posts', 'write:posts']
147
+ * })
148
+ */
91
149
  constructor(attributes: {
92
150
  identifier: string | number | BigInt;
93
151
  tokenableId: string | number | BigInt;
@@ -104,14 +162,36 @@ export declare class AccessToken {
104
162
  });
105
163
  /**
106
164
  * Check if the token allows the given ability.
165
+ *
166
+ * @param ability - The ability to check
167
+ *
168
+ * @example
169
+ * if (token.allows('read:posts')) {
170
+ * console.log('User can read posts')
171
+ * }
107
172
  */
108
173
  allows(ability: string): boolean;
109
174
  /**
110
175
  * Check if the token denies the ability.
176
+ *
177
+ * @param ability - The ability to check
178
+ *
179
+ * @example
180
+ * if (token.denies('delete:posts')) {
181
+ * console.log('User cannot delete posts')
182
+ * }
111
183
  */
112
184
  denies(ability: string): boolean;
113
185
  /**
114
186
  * Authorize ability access using the current access token
187
+ *
188
+ * @param ability - The ability to authorize
189
+ *
190
+ * @throws {E_UNAUTHORIZED_ACCESS} When the token denies the ability
191
+ *
192
+ * @example
193
+ * token.authorize('write:posts') // Throws if not allowed
194
+ * console.log('Authorization successful')
115
195
  */
116
196
  authorize(ability: string): void;
117
197
  /**
@@ -120,12 +200,35 @@ export declare class AccessToken {
120
200
  * date.
121
201
  *
122
202
  * Tokens with no expiry never expire
203
+ *
204
+ * @example
205
+ * if (token.isExpired()) {
206
+ * console.log('Token has expired')
207
+ * } else {
208
+ * console.log('Token is still valid')
209
+ * }
123
210
  */
124
211
  isExpired(): boolean;
125
212
  /**
126
213
  * Verifies the value of a token against the pre-defined hash
214
+ *
215
+ * @param secret - The secret to verify against the stored hash
216
+ *
217
+ * @example
218
+ * const isValid = token.verify(new Secret('user-provided-secret'))
219
+ * if (isValid) {
220
+ * console.log('Token is valid')
221
+ * }
127
222
  */
128
223
  verify(secret: Secret<string>): boolean;
224
+ /**
225
+ * Converts the token to a JSON representation suitable for API responses
226
+ *
227
+ * @example
228
+ * const tokenData = token.toJSON()
229
+ * console.log(tokenData.type) // 'bearer'
230
+ * console.log(tokenData.token) // 'oat_abc123.def456'
231
+ */
129
232
  toJSON(): {
130
233
  type: string;
131
234
  name: string | null;
@@ -8,9 +8,48 @@
8
8
  * Code taken from:
9
9
  * https://github.com/tsxper/crc32/blob/main/src/CRC32.ts
10
10
  */
11
+ /**
12
+ * CRC32 implementation for adding recognizable checksums to tokens.
13
+ * This helps secret scanning tools easily detect tokens generated by AdonisJS.
14
+ *
15
+ * @example
16
+ * const crc = new CRC32()
17
+ * const checksum = crc.calculate('my-secret-token')
18
+ * console.log('Checksum:', checksum)
19
+ */
11
20
  export declare class CRC32 {
12
21
  #private;
22
+ /**
23
+ * Calculate CRC32 checksum for a string input
24
+ *
25
+ * @param input - The string to calculate checksum for
26
+ *
27
+ * @example
28
+ * const crc = new CRC32()
29
+ * const checksum = crc.calculate('hello-world')
30
+ * console.log('CRC32:', checksum)
31
+ */
13
32
  calculate(input: string): number;
33
+ /**
34
+ * Calculate CRC32 checksum for a string
35
+ *
36
+ * @param input - The string to process
37
+ *
38
+ * @example
39
+ * const crc = new CRC32()
40
+ * const result = crc.forString('test-string')
41
+ */
14
42
  forString(input: string): number;
43
+ /**
44
+ * Calculate CRC32 checksum for byte array
45
+ *
46
+ * @param bytes - The byte array to process
47
+ * @param accumulator - Optional accumulator for chained calculations
48
+ *
49
+ * @example
50
+ * const crc = new CRC32()
51
+ * const bytes = new TextEncoder().encode('hello')
52
+ * const result = crc.forBytes(bytes)
53
+ */
15
54
  forBytes(bytes: Uint8Array, accumulator?: number): number;
16
55
  }
@@ -1,9 +1,9 @@
1
1
  import type { HttpContext } from '@adonisjs/core/http';
2
2
  import type { ConfigProvider } from '@adonisjs/core/types';
3
- import { AccessTokensGuard } from './guard.js';
4
- import type { GuardConfigProvider } from '../../src/types.js';
5
- import { AccessTokensLucidUserProvider } from './user_providers/lucid.js';
6
- import type { LucidTokenable, AccessTokensUserProviderContract, AccessTokensLucidUserProviderOptions } from './types.js';
3
+ import { AccessTokensGuard } from './guard.ts';
4
+ import type { GuardConfigProvider } from '../../src/types.ts';
5
+ import { AccessTokensLucidUserProvider } from './user_providers/lucid.ts';
6
+ import type { LucidTokenable, AccessTokensUserProviderContract, AccessTokensLucidUserProviderOptions } from './types.ts';
7
7
  /**
8
8
  * Configures access tokens guard for authentication
9
9
  */
@@ -1,13 +1,26 @@
1
1
  import type { HttpContext } from '@adonisjs/core/http';
2
2
  import type { EmitterLike } from '@adonisjs/core/types/events';
3
- import type { AccessToken } from './access_token.js';
4
- import type { AuthClientResponse, GuardContract } from '../../src/types.js';
5
- import { GUARD_KNOWN_EVENTS, PROVIDER_REAL_USER } from '../../src/symbols.js';
6
- import type { AccessTokensGuardEvents, AccessTokensUserProviderContract } from './types.js';
3
+ import type { AccessToken } from './access_token.ts';
4
+ import type { AuthClientResponse, GuardContract } from '../../src/types.ts';
5
+ import { GUARD_KNOWN_EVENTS, type PROVIDER_REAL_USER } from '../../src/symbols.ts';
6
+ import type { AccessTokensGuardEvents, AccessTokensUserProviderContract } from './types.ts';
7
7
  /**
8
8
  * Implementation of access tokens guard for the Auth layer. The heavy lifting
9
9
  * of verifying tokens is done by the user provider. However, the guard is
10
10
  * used to seamlessly integrate with the auth layer of the package.
11
+ *
12
+ * @template UserProvider - The user provider contract
13
+ *
14
+ * @example
15
+ * const guard = new AccessTokensGuard(
16
+ * 'api',
17
+ * ctx,
18
+ * emitter,
19
+ * userProvider
20
+ * )
21
+ *
22
+ * const user = await guard.authenticate()
23
+ * console.log('Authenticated user:', user.email)
11
24
  */
12
25
  export declare class AccessTokensGuard<UserProvider extends AccessTokensUserProviderContract<unknown>> implements GuardContract<UserProvider[typeof PROVIDER_REAL_USER] & {
13
26
  currentAccessToken: AccessToken;
@@ -47,12 +60,35 @@ export declare class AccessTokensGuard<UserProvider extends AccessTokensUserProv
47
60
  user?: UserProvider[typeof PROVIDER_REAL_USER] & {
48
61
  currentAccessToken: AccessToken;
49
62
  };
63
+ /**
64
+ * Creates a new AccessTokensGuard instance
65
+ *
66
+ * @param name - Unique name for the guard instance
67
+ * @param ctx - HTTP context for the current request
68
+ * @param emitter - Event emitter for guard events
69
+ * @param userProvider - User provider for token verification
70
+ *
71
+ * @example
72
+ * const guard = new AccessTokensGuard(
73
+ * 'api',
74
+ * ctx,
75
+ * emitter,
76
+ * new TokenUserProvider()
77
+ * )
78
+ */
50
79
  constructor(name: string, ctx: HttpContext, emitter: EmitterLike<AccessTokensGuardEvents<UserProvider[typeof PROVIDER_REAL_USER] & {
51
80
  currentAccessToken: AccessToken;
52
81
  }>>, userProvider: UserProvider);
53
82
  /**
54
83
  * Returns an instance of the authenticated user. Or throws
55
84
  * an exception if the request is not authenticated.
85
+ *
86
+ * @throws {E_UNAUTHORIZED_ACCESS} When user is not authenticated
87
+ *
88
+ * @example
89
+ * const user = guard.getUserOrFail()
90
+ * console.log('User ID:', user.id)
91
+ * console.log('Current token:', user.currentAccessToken.name)
56
92
  */
57
93
  getUserOrFail(): UserProvider[typeof PROVIDER_REAL_USER] & {
58
94
  currentAccessToken: AccessToken;
@@ -60,12 +96,34 @@ export declare class AccessTokensGuard<UserProvider extends AccessTokensUserProv
60
96
  /**
61
97
  * Authenticate the current HTTP request by verifying the bearer
62
98
  * token or fails with an exception
99
+ *
100
+ * @throws {E_UNAUTHORIZED_ACCESS} When authentication fails
101
+ *
102
+ * @example
103
+ * try {
104
+ * const user = await guard.authenticate()
105
+ * console.log('Authenticated as:', user.email)
106
+ * console.log('Token abilities:', user.currentAccessToken.abilities)
107
+ * } catch (error) {
108
+ * console.log('Authentication failed')
109
+ * }
63
110
  */
64
111
  authenticate(): Promise<UserProvider[typeof PROVIDER_REAL_USER] & {
65
112
  currentAccessToken: AccessToken;
66
113
  }>;
67
114
  /**
68
115
  * Create a token for a user (sign in)
116
+ *
117
+ * @param user - The user to create a token for
118
+ * @param abilities - Optional array of abilities the token should have
119
+ * @param options - Optional token configuration
120
+ *
121
+ * @example
122
+ * const token = await guard.createToken(user, ['read', 'write'], {
123
+ * name: 'Mobile App',
124
+ * expiresIn: '7d'
125
+ * })
126
+ * console.log('Token:', token.value.release())
69
127
  */
70
128
  createToken(user: UserProvider[typeof PROVIDER_REAL_USER], abilities?: string[], options?: {
71
129
  expiresIn?: string | number;
@@ -73,11 +131,23 @@ export declare class AccessTokensGuard<UserProvider extends AccessTokensUserProv
73
131
  }): Promise<AccessToken>;
74
132
  /**
75
133
  * Invalidates the currently authenticated token (sign out)
134
+ *
135
+ * @example
136
+ * await guard.invalidateToken()
137
+ * console.log('Token invalidated successfully')
76
138
  */
77
139
  invalidateToken(): Promise<boolean>;
78
140
  /**
79
141
  * Returns the Authorization header clients can use to authenticate
80
142
  * the request.
143
+ *
144
+ * @param user - The user to authenticate as
145
+ * @param abilities - Optional array of abilities
146
+ * @param options - Optional token configuration
147
+ *
148
+ * @example
149
+ * const clientAuth = await guard.authenticateAsClient(user, ['read'])
150
+ * // Use clientAuth.headers.authorization in API tests
81
151
  */
82
152
  authenticateAsClient(user: UserProvider[typeof PROVIDER_REAL_USER], abilities?: string[], options?: {
83
153
  expiresIn?: string | number;
@@ -85,8 +155,15 @@ export declare class AccessTokensGuard<UserProvider extends AccessTokensUserProv
85
155
  }): Promise<AuthClientResponse>;
86
156
  /**
87
157
  * Silently check if the user is authenticated or not. The
88
- * method is same the "authenticate" method but does not
158
+ * method is same as the "authenticate" method but does not
89
159
  * throw any exceptions.
160
+ *
161
+ * @example
162
+ * const isAuthenticated = await guard.check()
163
+ * if (isAuthenticated) {
164
+ * const user = guard.user
165
+ * console.log('User is authenticated:', user.email)
166
+ * }
90
167
  */
91
168
  check(): Promise<boolean>;
92
169
  }
@@ -1,5 +1,5 @@
1
- export { AccessToken } from './access_token.js';
2
- export { AccessTokensGuard } from './guard.js';
3
- export { DbAccessTokensProvider } from './token_providers/db.js';
4
- export { tokensGuard, tokensUserProvider } from './define_config.js';
5
- export { AccessTokensLucidUserProvider } from './user_providers/lucid.js';
1
+ export { AccessToken } from './access_token.ts';
2
+ export { AccessTokensGuard } from './guard.ts';
3
+ export { DbAccessTokensProvider } from './token_providers/db.ts';
4
+ export { tokensGuard, tokensUserProvider } from './define_config.ts';
5
+ export { AccessTokensLucidUserProvider } from './user_providers/lucid.ts';