@adonisjs/auth 9.0.0-8 → 9.0.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 (125) hide show
  1. package/build/chunk-3HZHOWKL.js +8 -0
  2. package/build/chunk-3HZHOWKL.js.map +1 -0
  3. package/build/chunk-52DVKHJR.js +246 -0
  4. package/build/chunk-52DVKHJR.js.map +1 -0
  5. package/build/chunk-BHB55PBJ.js +197 -0
  6. package/build/chunk-BHB55PBJ.js.map +1 -0
  7. package/build/chunk-CZCFTIBB.js +21 -0
  8. package/build/chunk-CZCFTIBB.js.map +1 -0
  9. package/build/index.d.ts +7 -6
  10. package/build/index.js +146 -15
  11. package/build/index.js.map +1 -0
  12. package/build/modules/access_tokens_guard/access_token.d.ts +137 -0
  13. package/build/modules/access_tokens_guard/crc32.d.ts +16 -0
  14. package/build/modules/access_tokens_guard/define_config.d.ts +17 -0
  15. package/build/modules/access_tokens_guard/guard.d.ts +81 -0
  16. package/build/modules/access_tokens_guard/main.d.ts +5 -0
  17. package/build/modules/access_tokens_guard/main.js +929 -0
  18. package/build/modules/access_tokens_guard/main.js.map +1 -0
  19. package/build/modules/access_tokens_guard/token_providers/db.d.ts +76 -0
  20. package/build/modules/access_tokens_guard/types.d.ts +208 -0
  21. package/build/modules/access_tokens_guard/types.js +1 -0
  22. package/build/modules/access_tokens_guard/types.js.map +1 -0
  23. package/build/modules/access_tokens_guard/user_providers/lucid.d.ts +53 -0
  24. package/build/modules/session_guard/define_config.d.ts +17 -0
  25. package/build/modules/session_guard/guard.d.ts +98 -0
  26. package/build/modules/session_guard/main.d.ts +5 -0
  27. package/build/modules/session_guard/main.js +741 -0
  28. package/build/modules/session_guard/main.js.map +1 -0
  29. package/build/modules/session_guard/remember_me_token.d.ts +88 -0
  30. package/build/modules/session_guard/token_providers/db.d.ts +69 -0
  31. package/build/modules/session_guard/types.d.ts +243 -0
  32. package/build/modules/session_guard/types.js +1 -0
  33. package/build/modules/session_guard/types.js.map +1 -0
  34. package/build/modules/session_guard/user_providers/lucid.d.ts +57 -0
  35. package/build/providers/auth_provider.d.ts +1 -1
  36. package/build/providers/auth_provider.js +31 -27
  37. package/build/providers/auth_provider.js.map +1 -0
  38. package/build/services/auth.d.ts +1 -1
  39. package/build/services/auth.js +10 -15
  40. package/build/services/auth.js.map +1 -0
  41. package/build/src/{auth/auth_manager.d.ts → auth_manager.d.ts} +8 -3
  42. package/build/src/authenticator.d.ts +81 -0
  43. package/build/src/{auth/authenticator_client.d.ts → authenticator_client.d.ts} +4 -4
  44. package/build/src/{auth/define_config.d.ts → define_config.d.ts} +0 -10
  45. package/build/src/errors.d.ts +105 -0
  46. package/build/src/{auth/middleware → middleware}/initialize_auth_middleware.d.ts +3 -2
  47. package/build/src/middleware/initialize_auth_middleware.js +17 -0
  48. package/build/src/middleware/initialize_auth_middleware.js.map +1 -0
  49. package/build/src/mixins/with_auth_finder.d.ts +156 -0
  50. package/build/src/{auth/plugins → plugins}/japa/api_client.d.ts +8 -8
  51. package/build/src/plugins/japa/api_client.js +59 -0
  52. package/build/src/plugins/japa/api_client.js.map +1 -0
  53. package/build/src/{auth/plugins → plugins}/japa/browser_client.d.ts +10 -7
  54. package/build/src/plugins/japa/browser_client.js +67 -0
  55. package/build/src/plugins/japa/browser_client.js.map +1 -0
  56. package/build/src/{auth/types.d.ts → types.d.ts} +31 -26
  57. package/build/src/types.js +1 -0
  58. package/build/src/types.js.map +1 -0
  59. package/package.json +90 -70
  60. package/build/configure.js +0 -47
  61. package/build/factories/basic_auth_guard_factory.d.ts +0 -12
  62. package/build/factories/basic_auth_guard_factory.js +0 -22
  63. package/build/factories/database_token_factory.d.ts +0 -36
  64. package/build/factories/database_token_factory.js +0 -54
  65. package/build/factories/database_user_provider.d.ts +0 -14
  66. package/build/factories/database_user_provider.js +0 -27
  67. package/build/factories/lucid_user_provider.d.ts +0 -28
  68. package/build/factories/lucid_user_provider.js +0 -68
  69. package/build/factories/main.d.ts +0 -4
  70. package/build/factories/main.js +0 -12
  71. package/build/factories/session_guard_factory.d.ts +0 -13
  72. package/build/factories/session_guard_factory.js +0 -24
  73. package/build/src/auth/auth_manager.js +0 -41
  74. package/build/src/auth/authenticator.d.ts +0 -63
  75. package/build/src/auth/authenticator.js +0 -129
  76. package/build/src/auth/authenticator_client.js +0 -59
  77. package/build/src/auth/debug.js +0 -10
  78. package/build/src/auth/define_config.js +0 -54
  79. package/build/src/auth/errors.d.ts +0 -90
  80. package/build/src/auth/errors.js +0 -201
  81. package/build/src/auth/middleware/initialize_auth_middleware.js +0 -25
  82. package/build/src/auth/plugins/japa/api_client.js +0 -63
  83. package/build/src/auth/plugins/japa/browser_client.js +0 -42
  84. package/build/src/auth/symbols.js +0 -17
  85. package/build/src/auth/types.js +0 -9
  86. package/build/src/auth/user_providers/main.d.ts +0 -15
  87. package/build/src/auth/user_providers/main.js +0 -22
  88. package/build/src/core/guard_user.d.ts +0 -26
  89. package/build/src/core/guard_user.js +0 -29
  90. package/build/src/core/token.d.ts +0 -89
  91. package/build/src/core/token.js +0 -114
  92. package/build/src/core/token_providers/database.d.ts +0 -77
  93. package/build/src/core/token_providers/database.js +0 -113
  94. package/build/src/core/types.d.ts +0 -178
  95. package/build/src/core/types.js +0 -9
  96. package/build/src/core/user_providers/database.d.ts +0 -78
  97. package/build/src/core/user_providers/database.js +0 -117
  98. package/build/src/core/user_providers/lucid.d.ts +0 -61
  99. package/build/src/core/user_providers/lucid.js +0 -122
  100. package/build/src/guards/basic_auth/define_config.d.ts +0 -16
  101. package/build/src/guards/basic_auth/define_config.js +0 -38
  102. package/build/src/guards/basic_auth/guard.d.ts +0 -70
  103. package/build/src/guards/basic_auth/guard.js +0 -190
  104. package/build/src/guards/basic_auth/main.d.ts +0 -2
  105. package/build/src/guards/basic_auth/main.js +0 -10
  106. package/build/src/guards/basic_auth/types.d.ts +0 -35
  107. package/build/src/guards/basic_auth/types.js +0 -9
  108. package/build/src/guards/session/define_config.d.ts +0 -23
  109. package/build/src/guards/session/define_config.js +0 -56
  110. package/build/src/guards/session/guard.d.ts +0 -123
  111. package/build/src/guards/session/guard.js +0 -510
  112. package/build/src/guards/session/main.d.ts +0 -3
  113. package/build/src/guards/session/main.js +0 -11
  114. package/build/src/guards/session/token.d.ts +0 -57
  115. package/build/src/guards/session/token.js +0 -58
  116. package/build/src/guards/session/token_providers/main.d.ts +0 -33
  117. package/build/src/guards/session/token_providers/main.js +0 -42
  118. package/build/src/guards/session/types.d.ts +0 -104
  119. package/build/src/guards/session/types.js +0 -9
  120. package/build/stubs/main.d.ts +0 -1
  121. package/build/stubs/main.js +0 -10
  122. package/build/stubs/middleware/auth_middleware.stub +0 -30
  123. package/build/stubs/middleware/guest_middleware.stub +0 -36
  124. /package/build/src/{auth/debug.d.ts → debug.d.ts} +0 -0
  125. /package/build/src/{auth/symbols.d.ts → symbols.d.ts} +0 -0
@@ -1,123 +0,0 @@
1
- import { Emitter } from '@adonisjs/core/events';
2
- import type { HttpContext } from '@adonisjs/core/http';
3
- import type { GuardContract } from '../../auth/types.js';
4
- import { GUARD_KNOWN_EVENTS, PROVIDER_REAL_USER } from '../../auth/symbols.js';
5
- import type { SessionGuardEvents, SessionGuardConfig, RememberMeProviderContract, SessionUserProviderContract } from './types.js';
6
- /**
7
- * Session guard uses sessions and cookies to login and authenticate
8
- * users.
9
- */
10
- export declare class SessionGuard<UserProvider extends SessionUserProviderContract<unknown>> implements GuardContract<UserProvider[typeof PROVIDER_REAL_USER]> {
11
- #private;
12
- [GUARD_KNOWN_EVENTS]: SessionGuardEvents<UserProvider[typeof PROVIDER_REAL_USER]>;
13
- /**
14
- * Driver name of the guard
15
- */
16
- driverName: 'session';
17
- /**
18
- * Whether or not the authentication has been attempted
19
- * during the current request
20
- */
21
- authenticationAttempted: boolean;
22
- /**
23
- * Find if the user has been logged out during
24
- * the current request
25
- */
26
- isLoggedOut: boolean;
27
- /**
28
- * A boolean to know if the current request has
29
- * been authenticated
30
- */
31
- isAuthenticated: boolean;
32
- /**
33
- * A boolean to know if the current request is authenticated
34
- * using the "rememember_me" token.
35
- */
36
- viaRemember: boolean;
37
- /**
38
- * Reference to an instance of the authenticated or logged-in
39
- * user. The value only exists after calling one of the
40
- * following methods.
41
- *
42
- * - login
43
- * - loginViaId
44
- * - attempt
45
- * - authenticate
46
- *
47
- * You can use the "getUserOrFail" method to throw an exception if
48
- * the request is not authenticated.
49
- */
50
- user?: UserProvider[typeof PROVIDER_REAL_USER];
51
- /**
52
- * The key used to store the logged-in user id inside
53
- * session
54
- */
55
- get sessionKeyName(): string;
56
- /**
57
- * The key used to store the remember me token cookie
58
- */
59
- get rememberMeKeyName(): string;
60
- constructor(name: string, config: SessionGuardConfig, ctx: HttpContext, userProvider: UserProvider);
61
- /**
62
- * Register the remember me tokens provider to create
63
- * remember me tokens during user login.
64
- *
65
- * Note: This method only registers the remember me tokens provider
66
- * and does not enable them. You must pass "rememberMe = true" during
67
- * the "login" method call.
68
- */
69
- withRememberMeTokens(tokensProvider: RememberMeProviderContract): this;
70
- /**
71
- * Register an event emitter to listen for global events for
72
- * authentication lifecycle.
73
- */
74
- withEmitter(emitter: Emitter<any>): this;
75
- /**
76
- * Returns an instance of the authenticated user. Or throws
77
- * an exception if the request is not authenticated.
78
- */
79
- getUserOrFail(): UserProvider[typeof PROVIDER_REAL_USER];
80
- /**
81
- * Verifies user credentials and returns an instance of
82
- * the user or throws "E_INVALID_CREDENTIALS" exception.
83
- */
84
- verifyCredentials(uid: string, password: string): Promise<UserProvider[typeof PROVIDER_REAL_USER]>;
85
- /**
86
- * Attempt to login a user after verifying their
87
- * credentials.
88
- */
89
- attempt(uid: string, password: string, remember?: boolean): Promise<UserProvider[typeof PROVIDER_REAL_USER]>;
90
- /**
91
- * Attempt to login a user using the user id. The
92
- * user will be first fetched from the db before
93
- * marking them as logged-in
94
- */
95
- loginViaId(id: string | number, remember?: boolean): Promise<UserProvider[typeof PROVIDER_REAL_USER]>;
96
- /**
97
- * Login a user using the user object.
98
- */
99
- login(user: UserProvider[typeof PROVIDER_REAL_USER], remember?: boolean): Promise<UserProvider[typeof PROVIDER_REAL_USER]>;
100
- /**
101
- * Authenticates the HTTP request to ensure the
102
- * user is logged-in
103
- */
104
- authenticate(): Promise<UserProvider[typeof PROVIDER_REAL_USER]>;
105
- /**
106
- * Silently attempt to authenticate the user.
107
- *
108
- * The method returns a boolean indicating if the authentication
109
- * succeeded or failed.
110
- */
111
- check(): Promise<boolean>;
112
- /**
113
- * Logout user and revoke remember me token (if any)
114
- */
115
- logout(): Promise<void>;
116
- /**
117
- * Returns the session state for the user to be
118
- * logged-in as a client
119
- */
120
- authenticateAsClient(user: UserProvider[typeof PROVIDER_REAL_USER]): Promise<{
121
- session: Record<string, string | number>;
122
- }>;
123
- }
@@ -1,510 +0,0 @@
1
- /*
2
- * @adonisjs/auth
3
- *
4
- * (c) AdonisJS
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import { RuntimeException } from '@poppinss/utils';
10
- import debug from '../../auth/debug.js';
11
- import { RememberMeToken } from './token.js';
12
- import { GUARD_KNOWN_EVENTS } from '../../auth/symbols.js';
13
- import { AuthenticationException, InvalidCredentialsException } from '../../auth/errors.js';
14
- /**
15
- * Session guard uses sessions and cookies to login and authenticate
16
- * users.
17
- */
18
- export class SessionGuard {
19
- /**
20
- * A unique name for the guard. It is used for prefixing
21
- * session data and remember me cookies
22
- */
23
- #name;
24
- /**
25
- * Reference to the current HTTP context
26
- */
27
- #ctx;
28
- /**
29
- * Configuration
30
- */
31
- #config;
32
- /**
33
- * Provider to lookup user details
34
- */
35
- #userProvider;
36
- /**
37
- * The remember me tokens provider to use to persist
38
- * remember me tokens
39
- */
40
- #rememberMeTokenProvider;
41
- /**
42
- * Emitter to emit events
43
- */
44
- #emitter;
45
- /**
46
- * Driver name of the guard
47
- */
48
- driverName = 'session';
49
- /**
50
- * Whether or not the authentication has been attempted
51
- * during the current request
52
- */
53
- authenticationAttempted = false;
54
- /**
55
- * Find if the user has been logged out during
56
- * the current request
57
- */
58
- isLoggedOut = false;
59
- /**
60
- * A boolean to know if the current request has
61
- * been authenticated
62
- */
63
- isAuthenticated = false;
64
- /**
65
- * A boolean to know if the current request is authenticated
66
- * using the "rememember_me" token.
67
- */
68
- viaRemember = false;
69
- /**
70
- * Reference to an instance of the authenticated or logged-in
71
- * user. The value only exists after calling one of the
72
- * following methods.
73
- *
74
- * - login
75
- * - loginViaId
76
- * - attempt
77
- * - authenticate
78
- *
79
- * You can use the "getUserOrFail" method to throw an exception if
80
- * the request is not authenticated.
81
- */
82
- user;
83
- /**
84
- * The key used to store the logged-in user id inside
85
- * session
86
- */
87
- get sessionKeyName() {
88
- return `auth_${this.#name}`;
89
- }
90
- /**
91
- * The key used to store the remember me token cookie
92
- */
93
- get rememberMeKeyName() {
94
- return `remember_${this.#name}`;
95
- }
96
- constructor(name, config, ctx, userProvider) {
97
- this.#name = name;
98
- this.#ctx = ctx;
99
- this.#config = config;
100
- this.#userProvider = userProvider;
101
- }
102
- /**
103
- * Returns an instance of the tokens provider, ensuring
104
- * it has been configured
105
- */
106
- #getTokenProvider() {
107
- if (!this.#rememberMeTokenProvider) {
108
- throw new RuntimeException('Cannot use "rememberMe" feature. Please configure the tokens provider inside config/auth file');
109
- }
110
- return this.#rememberMeTokenProvider;
111
- }
112
- /**
113
- * Returns the session instance for the given request,
114
- * ensuring the property exists
115
- */
116
- #getSession() {
117
- if (!('session' in this.#ctx)) {
118
- throw new RuntimeException('Cannot login user. Make sure you have installed the "@adonisjs/session" package and configured its middleware');
119
- }
120
- return this.#ctx.session;
121
- }
122
- /**
123
- * Notifies about authentication failure and throws the exception
124
- */
125
- #authenticationFailed(error, sessionId) {
126
- if (this.#emitter) {
127
- this.#emitter.emit('session_auth:authentication_failed', {
128
- guardName: this.#name,
129
- error,
130
- sessionId: sessionId,
131
- });
132
- }
133
- throw error;
134
- }
135
- /**
136
- * Notifies about login failure and throws the exception
137
- */
138
- #loginFailed(error, user) {
139
- if (this.#emitter) {
140
- this.#emitter.emit('session_auth:login_failed', {
141
- guardName: this.#name,
142
- error,
143
- user,
144
- });
145
- }
146
- throw error;
147
- }
148
- /**
149
- * Register the remember me tokens provider to create
150
- * remember me tokens during user login.
151
- *
152
- * Note: This method only registers the remember me tokens provider
153
- * and does not enable them. You must pass "rememberMe = true" during
154
- * the "login" method call.
155
- */
156
- withRememberMeTokens(tokensProvider) {
157
- this.#rememberMeTokenProvider = tokensProvider;
158
- return this;
159
- }
160
- /**
161
- * Register an event emitter to listen for global events for
162
- * authentication lifecycle.
163
- */
164
- withEmitter(emitter) {
165
- this.#emitter = emitter;
166
- return this;
167
- }
168
- /**
169
- * Returns an instance of the authenticated user. Or throws
170
- * an exception if the request is not authenticated.
171
- */
172
- getUserOrFail() {
173
- if (!this.user) {
174
- throw AuthenticationException.E_INVALID_AUTH_SESSION();
175
- }
176
- return this.user;
177
- }
178
- /**
179
- * Verifies user credentials and returns an instance of
180
- * the user or throws "E_INVALID_CREDENTIALS" exception.
181
- */
182
- async verifyCredentials(uid, password) {
183
- debug('session_guard: attempting to verify credentials for uid "%s"', uid);
184
- /**
185
- * Attempt to find a user by the uid and raise
186
- * error when unable to find one
187
- */
188
- const providerUser = await this.#userProvider.findByUid(uid);
189
- if (!providerUser) {
190
- this.#loginFailed(InvalidCredentialsException.E_INVALID_CREDENTIALS(this.driverName), null);
191
- }
192
- /**
193
- * Raise error when unable to verify password
194
- */
195
- const user = providerUser.getOriginal();
196
- /**
197
- * Raise error when unable to verify password
198
- */
199
- if (!(await providerUser.verifyPassword(password))) {
200
- this.#loginFailed(InvalidCredentialsException.E_INVALID_CREDENTIALS(this.driverName), user);
201
- }
202
- /**
203
- * Notify credentials have been verified
204
- */
205
- if (this.#emitter) {
206
- this.#emitter.emit('session_auth:credentials_verified', {
207
- guardName: this.#name,
208
- uid,
209
- user,
210
- });
211
- }
212
- return user;
213
- }
214
- /**
215
- * Attempt to login a user after verifying their
216
- * credentials.
217
- */
218
- async attempt(uid, password, remember) {
219
- const user = await this.verifyCredentials(uid, password);
220
- return this.login(user, remember);
221
- }
222
- /**
223
- * Attempt to login a user using the user id. The
224
- * user will be first fetched from the db before
225
- * marking them as logged-in
226
- */
227
- async loginViaId(id, remember) {
228
- debug('session_guard: attempting to login user via id "%s"', id);
229
- const providerUser = await this.#userProvider.findById(id);
230
- if (!providerUser) {
231
- this.#loginFailed(InvalidCredentialsException.E_INVALID_CREDENTIALS(this.driverName), null);
232
- }
233
- return this.login(providerUser.getOriginal(), remember);
234
- }
235
- /**
236
- * Login a user using the user object.
237
- */
238
- async login(user, remember = false) {
239
- if (this.#emitter) {
240
- this.#emitter.emit('session_auth:login_attempted', { user, guardName: this.#name });
241
- }
242
- const providerUser = await this.#userProvider.createUserForGuard(user);
243
- const session = this.#getSession();
244
- /**
245
- * Create session and recycle the session id
246
- */
247
- const userId = providerUser.getId();
248
- debug('session_guard: marking user with id "%s" as logged-in', userId);
249
- session.put(this.sessionKeyName, userId);
250
- session.regenerate();
251
- /**
252
- * Manage remember me cookie
253
- */
254
- let token;
255
- if (remember) {
256
- const tokenProvider = this.#getTokenProvider();
257
- /**
258
- * Create a token
259
- */
260
- token = RememberMeToken.create(providerUser.getId(), this.#config.rememberMeTokenAge || '2years');
261
- /**
262
- * Persist remember me token inside the database
263
- */
264
- await tokenProvider.createToken(token);
265
- /**
266
- * Drop token value inside the cookie
267
- */
268
- debug('session_guard: creating remember me cookie');
269
- this.#ctx.response.encryptedCookie(this.rememberMeKeyName, token.value, {
270
- maxAge: this.#config.rememberMeTokenAge,
271
- httpOnly: true,
272
- });
273
- }
274
- else {
275
- this.#ctx.response.clearCookie(this.rememberMeKeyName);
276
- }
277
- /**
278
- * Toggle properties to mark user as logged-in
279
- */
280
- this.user = user;
281
- this.isLoggedOut = false;
282
- /**
283
- * Notify the login is successful
284
- */
285
- if (this.#emitter) {
286
- this.#emitter.emit('session_auth:login_succeeded', {
287
- guardName: this.#name,
288
- user,
289
- sessionId: session.sessionId,
290
- rememberMeToken: token,
291
- });
292
- }
293
- return user;
294
- }
295
- /**
296
- * Authenticates the HTTP request to ensure the
297
- * user is logged-in
298
- */
299
- async authenticate() {
300
- if (this.authenticationAttempted) {
301
- return this.getUserOrFail();
302
- }
303
- this.authenticationAttempted = true;
304
- const session = this.#getSession();
305
- /**
306
- * Notify we are starting authentication process
307
- */
308
- if (this.#emitter) {
309
- this.#emitter.emit('session_auth:authentication_attempted', {
310
- guardName: this.#name,
311
- sessionId: session.sessionId,
312
- });
313
- }
314
- /**
315
- * Check if there is a user id inside the session store.
316
- * If yes, fetch the user from the persistent storage
317
- * and mark them as logged-in
318
- */
319
- const loggedInUserId = session.get(this.sessionKeyName);
320
- if (loggedInUserId) {
321
- debug('session_guard: authenticating user from session');
322
- const providerUser = await this.#userProvider.findById(loggedInUserId);
323
- /**
324
- * Throw error when user is not found inside the persistent
325
- * storage
326
- */
327
- if (!providerUser) {
328
- this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
329
- }
330
- debug('session_guard: marking user with id "%s" as authenticated', providerUser.getId());
331
- this.user = providerUser.getOriginal();
332
- this.isAuthenticated = true;
333
- this.isLoggedOut = false;
334
- this.viaRemember = false;
335
- /**
336
- * Authentication was successful
337
- */
338
- if (this.#emitter) {
339
- this.#emitter.emit('session_auth:authentication_succeeded', {
340
- guardName: this.#name,
341
- sessionId: session.sessionId,
342
- user: this.user,
343
- });
344
- }
345
- return this.user;
346
- }
347
- /**
348
- * Otherwise check for remember me cookie and attempt
349
- * to login user via that.
350
- *
351
- * Also, if the remember me token provider is not registered,
352
- * we will silently ignore the remember me cookie and
353
- * throw invalid session exception
354
- *
355
- * This is because, sometimes an app might use the remember me
356
- * tokens initially and then back out and stop using them. In
357
- * that case, we should not fail authentication attempts, just
358
- * ignore the remember me cookie.
359
- */
360
- const rememberMeCookie = this.#ctx.request.encryptedCookie(this.rememberMeKeyName);
361
- if (!rememberMeCookie || !this.#rememberMeTokenProvider) {
362
- this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
363
- }
364
- debug('session_guard: authenticating user from remember me cookie');
365
- /**
366
- * Decode remember me cookie and check for its existence inside
367
- * the database. Throw invalid session exception when token
368
- * is missing or invalid
369
- */
370
- const decodedToken = RememberMeToken.decode(rememberMeCookie);
371
- if (!decodedToken) {
372
- this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
373
- }
374
- const token = await this.#rememberMeTokenProvider.getTokenBySeries(decodedToken.series);
375
- if (!token || !token.verify(decodedToken.value)) {
376
- this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
377
- }
378
- debug('session_guard: found valid remember me token');
379
- /**
380
- * Find user for whom the token was created. Throw invalid
381
- * session exception when the user is missing
382
- */
383
- const providerUser = await this.#userProvider.findById(token.userId);
384
- if (!providerUser) {
385
- this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
386
- }
387
- /**
388
- * Finally, login the user from the remember me token
389
- */
390
- const userId = providerUser.getId();
391
- debug('session_guard: marking user with id "%s" as logged in from remember me cookie', userId);
392
- session.put(this.sessionKeyName, userId);
393
- session.regenerate();
394
- debug('session_guard: marking user with id "%s" as authenticated', userId);
395
- this.user = providerUser.getOriginal();
396
- this.isAuthenticated = true;
397
- this.isLoggedOut = false;
398
- this.viaRemember = true;
399
- /**
400
- * Authentication was successful via remember me token
401
- */
402
- if (this.#emitter) {
403
- this.#emitter.emit('session_auth:authentication_succeeded', {
404
- guardName: this.#name,
405
- sessionId: session.sessionId,
406
- user: this.user,
407
- rememberMeToken: token,
408
- });
409
- }
410
- /**
411
- * ----------------------------------------------------------------
412
- * User is logged in now. From here on we are refreshing the
413
- * remember me token.
414
- * ----------------------------------------------------------------
415
- *
416
- * Here we refresh the token value inside the db when the
417
- * current remember_me token is older than 1 minute.
418
- *
419
- * Otherwise, we re-use the same token. This is avoid race-conditions
420
- * when parallel requests uses the remember_me token to authenticate
421
- * the user.
422
- *
423
- * Finally, we will update remember_me cookie lifespan in both the cases.
424
- * Be it updated the token inside databse, or not.
425
- */
426
- const currentTime = new Date();
427
- const updatedAtWithBuffer = new Date(token.updatedAt);
428
- updatedAtWithBuffer.setSeconds(updatedAtWithBuffer.getSeconds() + 60);
429
- if (updatedAtWithBuffer < currentTime) {
430
- const newToken = RememberMeToken.create(token.userId, this.#config.rememberMeTokenAge || '2years');
431
- await this.#rememberMeTokenProvider.updateTokenBySeries(token.series, newToken.hash, newToken.expiresAt);
432
- this.#ctx.response.encryptedCookie(this.rememberMeKeyName, newToken.value, {
433
- maxAge: this.#config.rememberMeTokenAge,
434
- httpOnly: true,
435
- });
436
- }
437
- else {
438
- this.#ctx.response.encryptedCookie(this.rememberMeKeyName, rememberMeCookie, {
439
- maxAge: this.#config.rememberMeTokenAge,
440
- httpOnly: true,
441
- });
442
- }
443
- return this.user;
444
- }
445
- /**
446
- * Silently attempt to authenticate the user.
447
- *
448
- * The method returns a boolean indicating if the authentication
449
- * succeeded or failed.
450
- */
451
- async check() {
452
- try {
453
- await this.authenticate();
454
- return true;
455
- }
456
- catch (error) {
457
- if (error instanceof AuthenticationException) {
458
- return false;
459
- }
460
- throw error;
461
- }
462
- }
463
- /**
464
- * Logout user and revoke remember me token (if any)
465
- */
466
- async logout() {
467
- debug('session_auth: logging out');
468
- const session = this.#getSession();
469
- /**
470
- * Clear client side state
471
- */
472
- session.forget(this.sessionKeyName);
473
- this.#ctx.response.clearCookie(this.rememberMeKeyName);
474
- /**
475
- * Notify the user has been logged out
476
- */
477
- if (this.#emitter) {
478
- this.#emitter.emit('session_auth:logged_out', {
479
- guardName: this.#name,
480
- user: this.user || null,
481
- sessionId: session.sessionId,
482
- });
483
- }
484
- const rememberMeCookie = this.#ctx.request.encryptedCookie(this.rememberMeKeyName);
485
- if (!rememberMeCookie || !this.#rememberMeTokenProvider) {
486
- return;
487
- }
488
- debug('session_auth: decoding remember me token');
489
- const decodedToken = RememberMeToken.decode(rememberMeCookie);
490
- if (!decodedToken) {
491
- return;
492
- }
493
- debug('session_auth: deleting remember me token');
494
- await this.#rememberMeTokenProvider.deleteTokenBySeries(decodedToken.series);
495
- }
496
- /**
497
- * Returns the session state for the user to be
498
- * logged-in as a client
499
- */
500
- async authenticateAsClient(user) {
501
- const providerUser = await this.#userProvider.createUserForGuard(user);
502
- const userId = providerUser.getId();
503
- debug('session_guard: returning client session for user id "%s"', userId);
504
- return {
505
- session: {
506
- [this.sessionKeyName]: userId,
507
- },
508
- };
509
- }
510
- }
@@ -1,3 +0,0 @@
1
- export { SessionGuard } from './guard.js';
2
- export { RememberMeToken } from './token.js';
3
- export { sessionGuard, tokensProvider } from './define_config.js';
@@ -1,11 +0,0 @@
1
- /*
2
- * @adonisjs/auth
3
- *
4
- * (c) AdonisJS
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- export { SessionGuard } from './guard.js';
10
- export { RememberMeToken } from './token.js';
11
- export { sessionGuard, tokensProvider } from './define_config.js';
@@ -1,57 +0,0 @@
1
- import { Token } from '../../core/token.js';
2
- /**
3
- * Remember me token represents a remember me token created
4
- * for a peristed login flow.
5
- */
6
- export declare class RememberMeToken extends Token {
7
- /**
8
- * Reference to the user id for whom the token
9
- * is generated
10
- */
11
- userId: string | number;
12
- /**
13
- * Series is a random number stored inside the database as it is
14
- */
15
- series: string;
16
- /**
17
- * Value is a random number only available at the time of issuing
18
- * the token. Afterwards, the value is undefined.
19
- */
20
- value: string | undefined;
21
- /**
22
- * Hash reference to the token hash
23
- */
24
- hash: string;
25
- /**
26
- * Static name for the token to uniquely identify a
27
- * bucket of tokens
28
- */
29
- readonly type: 'remember_me_token';
30
- /**
31
- * Timestamp at which the token will expire
32
- */
33
- expiresAt: Date;
34
- constructor(
35
- /**
36
- * Reference to the user id for whom the token
37
- * is generated
38
- */
39
- userId: string | number,
40
- /**
41
- * Series is a random number stored inside the database as it is
42
- */
43
- series: string,
44
- /**
45
- * Value is a random number only available at the time of issuing
46
- * the token. Afterwards, the value is undefined.
47
- */
48
- value: string | undefined,
49
- /**
50
- * Hash reference to the token hash
51
- */
52
- hash: string);
53
- /**
54
- * Create remember me token instance for a user
55
- */
56
- static create(userId: string | number, expiry: string | number, size?: number): RememberMeToken;
57
- }