@adonisjs/auth 10.0.0-next.2 → 10.0.0-next.3

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.
@@ -1,351 +0,0 @@
1
- import {
2
- debug_default
3
- } from "./chunk-2VRS2VHB.js";
4
- import {
5
- E_UNAUTHORIZED_ACCESS
6
- } from "./chunk-S5G5RTJX.js";
7
-
8
- // src/authenticator.ts
9
- import { RuntimeException } from "@adonisjs/core/exceptions";
10
- var Authenticator = class {
11
- /**
12
- * Registered guards
13
- */
14
- #config;
15
- /**
16
- * Cache of guards created during the HTTP request
17
- */
18
- #guardsCache = {};
19
- /**
20
- * Last guard that was used to perform the authentication via
21
- * the "authenticateUsing" method.
22
- *
23
- * @note
24
- * Reset on every call made to "authenticate", "check" and
25
- * "authenticateUsing" method.
26
- */
27
- #authenticationAttemptedViaGuard;
28
- /**
29
- * Name of the guard using which the request has
30
- * been authenticated successfully.
31
- *
32
- * @note
33
- * Reset on every call made to "authenticate", "check" and
34
- * "authenticateUsing" method.
35
- */
36
- #authenticatedViaGuard;
37
- /**
38
- * Reference to HTTP context
39
- */
40
- #ctx;
41
- /**
42
- * Name of the default guard
43
- */
44
- get defaultGuard() {
45
- return this.#config.default;
46
- }
47
- /**
48
- * Reference to the guard using which the current
49
- * request has been authenticated.
50
- */
51
- get authenticatedViaGuard() {
52
- return this.#authenticatedViaGuard;
53
- }
54
- /**
55
- * A boolean to know if the current request has been authenticated. The
56
- * property returns false when "authenticate" or "authenticateUsing"
57
- * methods are not used.
58
- */
59
- get isAuthenticated() {
60
- if (!this.#authenticationAttemptedViaGuard) {
61
- return false;
62
- }
63
- return this.use(this.#authenticationAttemptedViaGuard).isAuthenticated;
64
- }
65
- /**
66
- * Reference to the currently authenticated user. The property returns
67
- * undefined when "authenticate" or "authenticateUsing" methods are
68
- * not used.
69
- */
70
- get user() {
71
- if (!this.#authenticationAttemptedViaGuard) {
72
- return void 0;
73
- }
74
- return this.use(this.#authenticationAttemptedViaGuard).user;
75
- }
76
- /**
77
- * Whether or not the authentication has been attempted during
78
- * the current request. The property returns false when the
79
- * "authenticate" or "authenticateUsing" methods are not
80
- * used.
81
- */
82
- get authenticationAttempted() {
83
- if (!this.#authenticationAttemptedViaGuard) {
84
- return false;
85
- }
86
- return this.use(this.#authenticationAttemptedViaGuard).authenticationAttempted;
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
- */
100
- constructor(ctx, config) {
101
- this.#ctx = ctx;
102
- this.#config = config;
103
- debug_default("creating authenticator. config %O", this.#config);
104
- }
105
- /**
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)
113
- */
114
- getUserOrFail() {
115
- if (!this.#authenticationAttemptedViaGuard) {
116
- throw new RuntimeException(
117
- 'Cannot access authenticated user. Please call "auth.authenticate" method first.'
118
- );
119
- }
120
- return this.use(this.#authenticationAttemptedViaGuard).getUserOrFail();
121
- }
122
- /**
123
- * Returns an instance of a known guard. Guards instances are
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()
131
- */
132
- use(guard) {
133
- const guardToUse = guard || this.#config.default;
134
- const cachedGuard = this.#guardsCache[guardToUse];
135
- if (cachedGuard) {
136
- debug_default('authenticator: using guard from cache. name: "%s"', guardToUse);
137
- return cachedGuard;
138
- }
139
- const guardFactory = this.#config.guards[guardToUse];
140
- debug_default('authenticator: creating guard. name: "%s"', guardToUse);
141
- const guardInstance = guardFactory(this.#ctx);
142
- this.#guardsCache[guardToUse] = guardInstance;
143
- return guardInstance;
144
- }
145
- /**
146
- * Authenticate current request using the default guard. Calling this
147
- * method multiple times triggers multiple authentication with the
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)
155
- */
156
- async authenticate() {
157
- await this.authenticateUsing();
158
- return this.getUserOrFail();
159
- }
160
- /**
161
- * Silently attempt to authenticate the request using the default
162
- * guard. Calling this method multiple times triggers multiple
163
- * authentication with the guard.
164
- *
165
- * @example
166
- * const isAuthenticated = await auth.check()
167
- * if (isAuthenticated) {
168
- * console.log('User is authenticated')
169
- * }
170
- */
171
- async check() {
172
- this.#authenticationAttemptedViaGuard = this.defaultGuard;
173
- const isAuthenticated = await this.use().check();
174
- if (isAuthenticated) {
175
- this.#authenticatedViaGuard = this.defaultGuard;
176
- }
177
- return isAuthenticated;
178
- }
179
- /**
180
- * Authenticate the request using all of the mentioned guards
181
- * or the default guard.
182
- *
183
- * The authentication process will stop after any of the mentioned
184
- * guards is able to authenticate the request successfully.
185
- *
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' })
196
- */
197
- async authenticateUsing(guards, options) {
198
- const guardsToUse = guards || [this.defaultGuard];
199
- let lastUsedDriver;
200
- for (let guardName of guardsToUse) {
201
- debug_default('attempting to authenticate using guard "%s"', guardName);
202
- this.#authenticationAttemptedViaGuard = guardName;
203
- const guard = this.use(guardName);
204
- lastUsedDriver = guard.driverName;
205
- if (await guard.check()) {
206
- this.#authenticatedViaGuard = guardName;
207
- return this.getUserOrFail();
208
- }
209
- }
210
- throw new E_UNAUTHORIZED_ACCESS("Unauthorized access", {
211
- guardDriverName: lastUsedDriver,
212
- redirectTo: options?.loginRoute
213
- });
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
- }
239
- };
240
-
241
- // src/authenticator_client.ts
242
- import { HttpContextFactory } from "@adonisjs/core/factories/http";
243
- var AuthenticatorClient = class {
244
- /**
245
- * Registered guards
246
- */
247
- #config;
248
- /**
249
- * Cache of guards
250
- */
251
- #guardsCache = {};
252
- /**
253
- * Name of the default guard
254
- */
255
- get defaultGuard() {
256
- return this.#config.default;
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
- */
269
- constructor(config) {
270
- this.#config = config;
271
- debug_default("creating authenticator client. config %O", this.#config);
272
- }
273
- /**
274
- * Returns an instance of a known guard. Guards instances are
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()
282
- */
283
- use(guard) {
284
- const guardToUse = guard || this.#config.default;
285
- const cachedGuard = this.#guardsCache[guardToUse];
286
- if (cachedGuard) {
287
- debug_default('authenticator client: using guard from cache. name: "%s"', guardToUse);
288
- return cachedGuard;
289
- }
290
- const guardFactory = this.#config.guards[guardToUse];
291
- debug_default('authenticator client: creating guard. name: "%s"', guardToUse);
292
- const guardInstance = guardFactory(new HttpContextFactory().create());
293
- this.#guardsCache[guardToUse] = guardInstance;
294
- return guardInstance;
295
- }
296
- };
297
-
298
- // src/auth_manager.ts
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
- */
311
- constructor(config) {
312
- this.config = config;
313
- this.config = config;
314
- }
315
- /**
316
- * Name of the default guard
317
- */
318
- get defaultGuard() {
319
- return this.config.default;
320
- }
321
- /**
322
- * Create an authenticator for a given HTTP request. The authenticator
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()
330
- */
331
- createAuthenticator(ctx) {
332
- return new Authenticator(ctx, this.config);
333
- }
334
- /**
335
- * Creates an instance of the authenticator client. The client is
336
- * used to setup authentication state during testing.
337
- *
338
- * @example
339
- * const client = manager.createAuthenticatorClient()
340
- * const guard = client.use('session')
341
- */
342
- createAuthenticatorClient() {
343
- return new AuthenticatorClient(this.config);
344
- }
345
- };
346
-
347
- export {
348
- Authenticator,
349
- AuthenticatorClient,
350
- AuthManager
351
- };
@@ -1,236 +0,0 @@
1
- import {
2
- __export
3
- } from "./chunk-UXA4FHST.js";
4
-
5
- // src/errors.ts
6
- var errors_exports = {};
7
- __export(errors_exports, {
8
- E_INVALID_CREDENTIALS: () => E_INVALID_CREDENTIALS,
9
- E_UNAUTHORIZED_ACCESS: () => E_UNAUTHORIZED_ACCESS
10
- });
11
- import { Exception } from "@adonisjs/core/exceptions";
12
- var E_UNAUTHORIZED_ACCESS = class extends Exception {
13
- static status = 401;
14
- static code = "E_UNAUTHORIZED_ACCESS";
15
- /**
16
- * Endpoint to redirect to. Only used by "session" driver
17
- * renderer
18
- */
19
- redirectTo;
20
- /**
21
- * Translation identifier. Can be customized
22
- */
23
- identifier = "errors.E_UNAUTHORIZED_ACCESS";
24
- /**
25
- * The guard name reference that raised the exception. It allows
26
- * us to customize the logic of handling the exception.
27
- */
28
- guardDriverName;
29
- /**
30
- * A collection of renderers to render the exception to a
31
- * response.
32
- *
33
- * The collection is a key-value pair, where the key is
34
- * the guard driver name and value is a factory function
35
- * to respond to the request.
36
- */
37
- renderers = {
38
- /**
39
- * Response when session driver is used
40
- */
41
- session: (message, error, ctx) => {
42
- switch (ctx.request.accepts(["html", "application/vnd.api+json", "json"])) {
43
- case "html":
44
- case null:
45
- ctx.session.flashExcept(["_csrf"]);
46
- ctx.session.flashErrors({ [error.code]: message });
47
- ctx.response.redirect(error.redirectTo || "/", true);
48
- break;
49
- case "json":
50
- ctx.response.status(error.status).send({
51
- errors: [
52
- {
53
- message
54
- }
55
- ]
56
- });
57
- break;
58
- case "application/vnd.api+json":
59
- ctx.response.status(error.status).send({
60
- errors: [
61
- {
62
- code: error.code,
63
- title: message
64
- }
65
- ]
66
- });
67
- break;
68
- }
69
- },
70
- /**
71
- * Response when basic auth driver is used
72
- */
73
- basic_auth: (message, _, ctx) => {
74
- ctx.response.status(this.status).header("WWW-Authenticate", `Basic realm="Authenticate", charset="UTF-8"`).send(message);
75
- },
76
- /**
77
- * Response when access tokens driver is used
78
- */
79
- access_tokens: (message, error, ctx) => {
80
- switch (ctx.request.accepts(["html", "application/vnd.api+json", "json"])) {
81
- case "html":
82
- case null:
83
- ctx.response.status(error.status).send(message);
84
- break;
85
- case "json":
86
- ctx.response.status(error.status).send({
87
- errors: [
88
- {
89
- message
90
- }
91
- ]
92
- });
93
- break;
94
- case "application/vnd.api+json":
95
- ctx.response.status(error.status).send({
96
- errors: [
97
- {
98
- code: error.code,
99
- title: message
100
- }
101
- ]
102
- });
103
- break;
104
- }
105
- }
106
- };
107
- /**
108
- * Returns the message to be sent in the HTTP response.
109
- * Feel free to override this method and return a custom
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)
118
- */
119
- getResponseMessage(error, ctx) {
120
- if ("i18n" in ctx) {
121
- return ctx.i18n.t(error.identifier, {}, error.message);
122
- }
123
- return error.message;
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
- */
137
- constructor(message, options) {
138
- super(message, {});
139
- this.guardDriverName = options.guardDriverName;
140
- this.redirectTo = options.redirectTo;
141
- }
142
- /**
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)
151
- */
152
- async handle(error, ctx) {
153
- const renderer = this.renderers[this.guardDriverName];
154
- const message = error.getResponseMessage(error, ctx);
155
- if (!renderer) {
156
- return ctx.response.status(error.status).send(message);
157
- }
158
- return renderer(message, error, ctx);
159
- }
160
- };
161
- var E_INVALID_CREDENTIALS = class extends Exception {
162
- static status = 400;
163
- static code = "E_INVALID_CREDENTIALS";
164
- /**
165
- * Translation identifier. Can be customized
166
- */
167
- identifier = "errors.E_INVALID_CREDENTIALS";
168
- /**
169
- * Returns the message to be sent in the HTTP response.
170
- * Feel free to override this method and return a custom
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)
179
- */
180
- getResponseMessage(error, ctx) {
181
- if ("i18n" in ctx) {
182
- return ctx.i18n.t(error.identifier, {}, error.message);
183
- }
184
- return error.message;
185
- }
186
- /**
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)
195
- */
196
- async handle(error, ctx) {
197
- const message = this.getResponseMessage(error, ctx);
198
- switch (ctx.request.accepts(["html", "application/vnd.api+json", "json"])) {
199
- case "html":
200
- case null:
201
- if (ctx.session) {
202
- ctx.session.flashExcept(["_csrf", "_method", "password", "password_confirmation"]);
203
- ctx.session.flashErrors({ [error.code]: message });
204
- ctx.response.redirect("back", true);
205
- } else {
206
- ctx.response.status(error.status).send(message);
207
- }
208
- break;
209
- case "json":
210
- ctx.response.status(error.status).send({
211
- errors: [
212
- {
213
- message
214
- }
215
- ]
216
- });
217
- break;
218
- case "application/vnd.api+json":
219
- ctx.response.status(error.status).send({
220
- errors: [
221
- {
222
- code: error.code,
223
- title: message
224
- }
225
- ]
226
- });
227
- break;
228
- }
229
- }
230
- };
231
-
232
- export {
233
- E_UNAUTHORIZED_ACCESS,
234
- E_INVALID_CREDENTIALS,
235
- errors_exports
236
- };
@@ -1,19 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __export = (target, all) => {
4
- for (var name in all)
5
- __defProp(target, name, { get: all[name], enumerable: true });
6
- };
7
- var __decorateClass = (decorators, target, key, kind) => {
8
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
9
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
10
- if (decorator = decorators[i])
11
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
12
- if (kind && result) __defProp(target, key, result);
13
- return result;
14
- };
15
-
16
- export {
17
- __export,
18
- __decorateClass
19
- };