@adonisjs/auth 8.2.3 → 9.0.0-1

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 (137) hide show
  1. package/LICENSE.md +1 -1
  2. package/README.md +19 -40
  3. package/build/configure.d.ts +5 -0
  4. package/build/configure.js +55 -0
  5. package/build/factories/database_token_factory.d.ts +36 -0
  6. package/build/factories/database_token_factory.js +54 -0
  7. package/build/factories/database_user_provider.d.ts +14 -0
  8. package/build/factories/database_user_provider.js +27 -0
  9. package/build/factories/lucid_user_provider.d.ts +28 -0
  10. package/build/factories/lucid_user_provider.js +68 -0
  11. package/build/factories/main.d.ts +4 -0
  12. package/build/factories/main.js +12 -0
  13. package/build/factories/session_guard_factory.d.ts +13 -0
  14. package/build/factories/session_guard_factory.js +24 -0
  15. package/build/index.d.ts +7 -0
  16. package/build/index.js +15 -0
  17. package/build/providers/auth_provider.d.ts +12 -0
  18. package/build/providers/auth_provider.js +27 -0
  19. package/build/services/auth.d.ts +3 -0
  20. package/build/services/auth.js +17 -0
  21. package/build/src/auth/auth_manager.d.ts +22 -0
  22. package/build/src/auth/auth_manager.js +34 -0
  23. package/build/src/auth/authenticator.d.ts +56 -0
  24. package/build/src/auth/authenticator.js +122 -0
  25. package/build/src/auth/debug.d.ts +3 -0
  26. package/build/{adonis-typings/container.js → src/auth/debug.js} +3 -1
  27. package/build/src/auth/define_config.d.ts +30 -0
  28. package/build/src/auth/define_config.js +54 -0
  29. package/build/src/auth/errors.d.ts +82 -0
  30. package/build/src/auth/errors.js +181 -0
  31. package/build/src/auth/middleware/auth_middleware.d.ts +13 -0
  32. package/build/src/auth/middleware/auth_middleware.js +6 -0
  33. package/build/src/auth/middleware/initialize_auth_middleware.d.ts +18 -0
  34. package/build/src/auth/middleware/initialize_auth_middleware.js +25 -0
  35. package/build/src/auth/symbols.d.ts +9 -0
  36. package/build/src/auth/symbols.js +17 -0
  37. package/build/src/auth/types.d.ts +75 -0
  38. package/build/{adonis-typings/context.js → src/auth/types.js} +2 -1
  39. package/build/src/auth/user_providers/main.d.ts +15 -0
  40. package/build/src/auth/user_providers/main.js +22 -0
  41. package/build/src/core/guard_user.d.ts +26 -0
  42. package/build/src/core/guard_user.js +29 -0
  43. package/build/src/core/token.d.ts +89 -0
  44. package/build/src/core/token.js +114 -0
  45. package/build/src/core/token_providers/database.d.ts +77 -0
  46. package/build/src/core/token_providers/database.js +113 -0
  47. package/build/src/core/types.d.ts +178 -0
  48. package/build/{adonis-typings/auth.js → src/core/types.js} +2 -1
  49. package/build/src/core/user_providers/database.d.ts +78 -0
  50. package/build/src/core/user_providers/database.js +117 -0
  51. package/build/src/core/user_providers/lucid.d.ts +61 -0
  52. package/build/src/core/user_providers/lucid.js +122 -0
  53. package/build/src/guards/session/define_config.d.ts +23 -0
  54. package/build/src/guards/session/define_config.js +56 -0
  55. package/build/src/guards/session/guard.d.ts +112 -0
  56. package/build/src/guards/session/guard.js +454 -0
  57. package/build/src/guards/session/main.d.ts +3 -0
  58. package/build/src/guards/session/main.js +11 -0
  59. package/build/src/guards/session/token.d.ts +57 -0
  60. package/build/src/guards/session/token.js +58 -0
  61. package/build/src/guards/session/token_providers/main.d.ts +33 -0
  62. package/build/src/guards/session/token_providers/main.js +42 -0
  63. package/build/src/guards/session/types.d.ts +96 -0
  64. package/build/{adonis-typings/events.js → src/guards/session/types.js} +2 -1
  65. package/build/stubs/config.stub +35 -0
  66. package/build/stubs/main.d.ts +1 -0
  67. package/build/{adonis-typings/tests.js → stubs/main.js} +2 -3
  68. package/package.json +99 -91
  69. package/build/adonis-typings/auth.d.ts +0 -635
  70. package/build/adonis-typings/container.d.ts +0 -6
  71. package/build/adonis-typings/context.d.ts +0 -6
  72. package/build/adonis-typings/events.d.ts +0 -10
  73. package/build/adonis-typings/index.d.ts +0 -5
  74. package/build/adonis-typings/index.js +0 -13
  75. package/build/adonis-typings/tests.d.ts +0 -23
  76. package/build/instructions.js +0 -338
  77. package/build/providers/AuthProvider.d.ts +0 -30
  78. package/build/providers/AuthProvider.js +0 -69
  79. package/build/src/Auth/index.d.ts +0 -97
  80. package/build/src/Auth/index.js +0 -155
  81. package/build/src/AuthManager/index.d.ts +0 -117
  82. package/build/src/AuthManager/index.js +0 -262
  83. package/build/src/Bindings/Tests.d.ts +0 -6
  84. package/build/src/Bindings/Tests.js +0 -69
  85. package/build/src/Clients/Oat/index.d.ts +0 -50
  86. package/build/src/Clients/Oat/index.js +0 -123
  87. package/build/src/Clients/Session/index.d.ts +0 -34
  88. package/build/src/Clients/Session/index.js +0 -72
  89. package/build/src/Exceptions/AuthenticationException.d.ts +0 -47
  90. package/build/src/Exceptions/AuthenticationException.js +0 -142
  91. package/build/src/Exceptions/InvalidCredentialsException.d.ts +0 -34
  92. package/build/src/Exceptions/InvalidCredentialsException.js +0 -112
  93. package/build/src/Guards/Base/index.d.ts +0 -75
  94. package/build/src/Guards/Base/index.js +0 -138
  95. package/build/src/Guards/BasicAuth/index.d.ts +0 -67
  96. package/build/src/Guards/BasicAuth/index.js +0 -181
  97. package/build/src/Guards/Oat/index.d.ts +0 -149
  98. package/build/src/Guards/Oat/index.js +0 -347
  99. package/build/src/Guards/Session/index.d.ts +0 -127
  100. package/build/src/Guards/Session/index.js +0 -338
  101. package/build/src/TokenProviders/Database/index.d.ts +0 -43
  102. package/build/src/TokenProviders/Database/index.js +0 -126
  103. package/build/src/TokenProviders/Redis/index.d.ts +0 -44
  104. package/build/src/TokenProviders/Redis/index.js +0 -129
  105. package/build/src/Tokens/OpaqueToken/index.d.ts +0 -46
  106. package/build/src/Tokens/OpaqueToken/index.js +0 -43
  107. package/build/src/Tokens/ProviderToken/index.d.ts +0 -23
  108. package/build/src/Tokens/ProviderToken/index.js +0 -27
  109. package/build/src/UserProviders/Database/User.d.ts +0 -28
  110. package/build/src/UserProviders/Database/User.js +0 -74
  111. package/build/src/UserProviders/Database/index.d.ts +0 -75
  112. package/build/src/UserProviders/Database/index.js +0 -141
  113. package/build/src/UserProviders/Lucid/User.d.ts +0 -28
  114. package/build/src/UserProviders/Lucid/User.js +0 -74
  115. package/build/src/UserProviders/Lucid/index.d.ts +0 -72
  116. package/build/src/UserProviders/Lucid/index.js +0 -146
  117. package/build/standalone.d.ts +0 -1
  118. package/build/standalone.js +0 -13
  119. package/build/templates/config/auth.txt +0 -34
  120. package/build/templates/config/partials/api-guard.txt +0 -22
  121. package/build/templates/config/partials/basic-guard.txt +0 -19
  122. package/build/templates/config/partials/tokens-provider-database.txt +0 -19
  123. package/build/templates/config/partials/tokens-provider-redis.txt +0 -22
  124. package/build/templates/config/partials/user-provider-database.txt +0 -43
  125. package/build/templates/config/partials/user-provider-lucid.txt +0 -45
  126. package/build/templates/config/partials/web-guard.txt +0 -17
  127. package/build/templates/contract/auth.txt +0 -55
  128. package/build/templates/contract/partials/api-guard.txt +0 -14
  129. package/build/templates/contract/partials/basic-guard.txt +0 -14
  130. package/build/templates/contract/partials/user-provider-database.txt +0 -16
  131. package/build/templates/contract/partials/user-provider-lucid.txt +0 -16
  132. package/build/templates/contract/partials/web-guard.txt +0 -14
  133. package/build/templates/middleware/Auth.txt +0 -76
  134. package/build/templates/middleware/SilentAuth.txt +0 -21
  135. package/build/templates/migrations/api_tokens.txt +0 -25
  136. package/build/templates/migrations/auth.txt +0 -24
  137. package/build/templates/model.txt +0 -30
@@ -0,0 +1,454 @@
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
+ error,
129
+ sessionId: sessionId,
130
+ });
131
+ }
132
+ throw error;
133
+ }
134
+ /**
135
+ * Notifies about login failure and throws the exception
136
+ */
137
+ #loginFailed(error, user) {
138
+ if (this.#emitter) {
139
+ this.#emitter.emit('session_auth:login_failed', {
140
+ error,
141
+ user,
142
+ });
143
+ }
144
+ throw error;
145
+ }
146
+ /**
147
+ * Register the remember me tokens provider to create
148
+ * remember me tokens during user login.
149
+ *
150
+ * Note: This method only registers the remember me tokens provider
151
+ * and does not enable them. You must pass "rememberMe = true" during
152
+ * the "login" method call.
153
+ */
154
+ withRememberMeTokens(tokensProvider) {
155
+ this.#rememberMeTokenProvider = tokensProvider;
156
+ return this;
157
+ }
158
+ /**
159
+ * Register an event emitter to listen for global events for
160
+ * authentication lifecycle.
161
+ */
162
+ withEmitter(emitter) {
163
+ this.#emitter = emitter;
164
+ return this;
165
+ }
166
+ /**
167
+ * Returns an instance of the authenticated user. Or throws
168
+ * an exception if the request is not authenticated.
169
+ */
170
+ getUserOrFail() {
171
+ if (!this.user) {
172
+ throw AuthenticationException.E_INVALID_AUTH_SESSION();
173
+ }
174
+ return this.user;
175
+ }
176
+ /**
177
+ * Verifies user credentials and returns an instance of
178
+ * the user or throws "E_INVALID_CREDENTIALS" exception.
179
+ */
180
+ async verifyCredentials(uid, password) {
181
+ debug('session_guard: attempting to verify credentials for uid "%s"', uid);
182
+ /**
183
+ * Attempt to find a user by the uid and raise
184
+ * error when unable to find one
185
+ */
186
+ const providerUser = await this.#userProvider.findByUid(uid);
187
+ if (!providerUser) {
188
+ this.#loginFailed(InvalidCredentialsException.E_INVALID_CREDENTIALS(this.driverName), null);
189
+ }
190
+ /**
191
+ * Raise error when unable to verify password
192
+ */
193
+ const user = providerUser.getOriginal();
194
+ /**
195
+ * Raise error when unable to verify password
196
+ */
197
+ if (!(await providerUser.verifyPassword(password))) {
198
+ this.#loginFailed(InvalidCredentialsException.E_INVALID_CREDENTIALS(this.driverName), user);
199
+ }
200
+ /**
201
+ * Notify credentials have been verified
202
+ */
203
+ if (this.#emitter) {
204
+ this.#emitter.emit('session_auth:credentials_verified', {
205
+ uid,
206
+ user,
207
+ });
208
+ }
209
+ return user;
210
+ }
211
+ /**
212
+ * Attempt to login a user after verifying their
213
+ * credentials.
214
+ */
215
+ async attempt(uid, password) {
216
+ const user = await this.verifyCredentials(uid, password);
217
+ return this.login(user);
218
+ }
219
+ /**
220
+ * Attempt to login a user using the user id. The
221
+ * user will be first fetched from the db before
222
+ * marking them as logged-in
223
+ */
224
+ async loginViaId(id) {
225
+ debug('session_guard: attempting to login user via id "%s"', id);
226
+ const providerUser = await this.#userProvider.findById(id);
227
+ if (!providerUser) {
228
+ this.#loginFailed(InvalidCredentialsException.E_INVALID_CREDENTIALS(this.driverName), null);
229
+ }
230
+ return this.login(providerUser.getOriginal());
231
+ }
232
+ /**
233
+ * Login a user using the user object.
234
+ */
235
+ async login(user, remember = false) {
236
+ if (this.#emitter) {
237
+ this.#emitter.emit('session_auth:login_attempted', { user });
238
+ }
239
+ const providerUser = await this.#userProvider.createUserForGuard(user);
240
+ const session = this.#getSession();
241
+ /**
242
+ * Create session and recycle the session id
243
+ */
244
+ const userId = providerUser.getId();
245
+ debug('session_guard: marking user with id "%s" as logged-in', userId);
246
+ session.put(this.sessionKeyName, userId);
247
+ session.regenerate();
248
+ /**
249
+ * Manage remember me cookie
250
+ */
251
+ let token;
252
+ if (remember) {
253
+ const tokenProvider = this.#getTokenProvider();
254
+ /**
255
+ * Create a token
256
+ */
257
+ token = RememberMeToken.create(providerUser.getId(), this.#config.rememberMeTokenAge || '2years');
258
+ /**
259
+ * Persist remember me token inside the database
260
+ */
261
+ await tokenProvider.createToken(token);
262
+ /**
263
+ * Drop token value inside the cookie
264
+ */
265
+ debug('session_guard: creating remember me cookie');
266
+ this.#ctx.response.encryptedCookie(this.rememberMeKeyName, token.value, {
267
+ maxAge: this.#config.rememberMeTokenAge,
268
+ httpOnly: true,
269
+ });
270
+ }
271
+ else {
272
+ this.#ctx.response.clearCookie(this.rememberMeKeyName);
273
+ }
274
+ /**
275
+ * Toggle properties to mark user as logged-in
276
+ */
277
+ this.user = user;
278
+ this.isLoggedOut = false;
279
+ /**
280
+ * Notify the login is successful
281
+ */
282
+ if (this.#emitter) {
283
+ this.#emitter.emit('session_auth:login_succeeded', {
284
+ user,
285
+ sessionId: session.sessionId,
286
+ rememberMeToken: token,
287
+ });
288
+ }
289
+ return user;
290
+ }
291
+ /**
292
+ * Authenticates the HTTP request to ensure the
293
+ * user is logged-in
294
+ */
295
+ async authenticate() {
296
+ if (this.authenticationAttempted) {
297
+ return this.getUserOrFail();
298
+ }
299
+ this.authenticationAttempted = true;
300
+ const session = this.#getSession();
301
+ /**
302
+ * Notify we are starting authentication process
303
+ */
304
+ if (this.#emitter) {
305
+ this.#emitter.emit('session_auth:authentication_attempted', {
306
+ sessionId: session.sessionId,
307
+ });
308
+ }
309
+ /**
310
+ * Check if there is a user id inside the session store.
311
+ * If yes, fetch the user from the persistent storage
312
+ * and mark them as logged-in
313
+ */
314
+ const loggedInUserId = session.get(this.sessionKeyName);
315
+ if (loggedInUserId) {
316
+ debug('session_guard: authenticating user from session');
317
+ const providerUser = await this.#userProvider.findById(loggedInUserId);
318
+ /**
319
+ * Throw error when user is not found inside the persistent
320
+ * storage
321
+ */
322
+ if (!providerUser) {
323
+ this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
324
+ }
325
+ this.user = providerUser.getOriginal();
326
+ this.isAuthenticated = true;
327
+ this.isLoggedOut = false;
328
+ this.viaRemember = false;
329
+ /**
330
+ * Authentication was successful
331
+ */
332
+ if (this.#emitter) {
333
+ this.#emitter.emit('session_auth:authentication_succeeded', {
334
+ sessionId: session.sessionId,
335
+ user: this.user,
336
+ });
337
+ }
338
+ return this.user;
339
+ }
340
+ /**
341
+ * Otherwise check for remember me cookie and attempt
342
+ * to login user via that.
343
+ *
344
+ * Also, if the remember me token provider is not registered,
345
+ * we will silently ignore the remember me cookie and
346
+ * throw invalid session exception
347
+ *
348
+ * This is because, sometimes an app might use the remember me
349
+ * tokens initially and then back out and stop using them. In
350
+ * that case, we should not fail authentication attempts, just
351
+ * ignore the remember me cookie.
352
+ */
353
+ const rememberMeCookie = this.#ctx.request.encryptedCookie(this.rememberMeKeyName);
354
+ if (!rememberMeCookie || !this.#rememberMeTokenProvider) {
355
+ this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
356
+ }
357
+ debug('session_guard: authenticating user from remember me cookie');
358
+ /**
359
+ * Decode remember me cookie and check for its existence inside
360
+ * the database. Throw invalid session exception when token
361
+ * is missing or invalid
362
+ */
363
+ const decodedToken = RememberMeToken.decode(rememberMeCookie);
364
+ if (!decodedToken) {
365
+ this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
366
+ }
367
+ const token = await this.#rememberMeTokenProvider.getTokenBySeries(decodedToken.series);
368
+ if (!token || !token.verify(decodedToken.value)) {
369
+ this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
370
+ }
371
+ debug('session_guard: found valid remember me token');
372
+ /**
373
+ * Find user for whom the token was created. Throw invalid
374
+ * session exception when the user is missing
375
+ */
376
+ const providerUser = await this.#userProvider.findById(token.userId);
377
+ if (!providerUser) {
378
+ this.#authenticationFailed(AuthenticationException.E_INVALID_AUTH_SESSION(), session.sessionId);
379
+ }
380
+ /**
381
+ * Finally, login the user from the remember me token
382
+ */
383
+ const userId = providerUser.getId();
384
+ debug('session_guard: marking user with id "%s" as logged in from remember me cookie', userId);
385
+ session.put(this.sessionKeyName, userId);
386
+ session.regenerate();
387
+ this.user = providerUser.getOriginal();
388
+ this.isAuthenticated = true;
389
+ this.isLoggedOut = false;
390
+ this.viaRemember = true;
391
+ /**
392
+ * Authentication was successful via remember me token
393
+ */
394
+ if (this.#emitter) {
395
+ this.#emitter.emit('session_auth:authentication_succeeded', {
396
+ sessionId: session.sessionId,
397
+ user: this.user,
398
+ rememberMeToken: token,
399
+ });
400
+ }
401
+ /**
402
+ * ----------------------------------------------------------------
403
+ * User is logged in now. From here on we are refreshing the
404
+ * remember me token.
405
+ * ----------------------------------------------------------------
406
+ *
407
+ * Here we refresh the token value inside the db when the
408
+ * current remember_me token is older than 1 minute.
409
+ *
410
+ * Otherwise, we re-use the same token. This is avoid race-conditions
411
+ * when parallel requests uses the remember_me token to authenticate
412
+ * the user.
413
+ *
414
+ * Finally, we will update remember_me cookie lifespan in both the cases.
415
+ * Be it updated the token inside databse, or not.
416
+ */
417
+ const currentTime = new Date();
418
+ const updatedAtWithBuffer = new Date(token.updatedAt);
419
+ updatedAtWithBuffer.setSeconds(updatedAtWithBuffer.getSeconds() + 60);
420
+ if (updatedAtWithBuffer < currentTime) {
421
+ const newToken = RememberMeToken.create(token.userId, this.#config.rememberMeTokenAge || '2years');
422
+ await this.#rememberMeTokenProvider.updateTokenBySeries(token.series, newToken.hash, newToken.expiresAt);
423
+ this.#ctx.response.encryptedCookie(this.rememberMeKeyName, newToken.value, {
424
+ maxAge: this.#config.rememberMeTokenAge,
425
+ httpOnly: true,
426
+ });
427
+ }
428
+ else {
429
+ this.#ctx.response.encryptedCookie(this.rememberMeKeyName, rememberMeCookie, {
430
+ maxAge: this.#config.rememberMeTokenAge,
431
+ httpOnly: true,
432
+ });
433
+ }
434
+ return this.user;
435
+ }
436
+ /**
437
+ * Silently attempt to authenticate the user.
438
+ *
439
+ * The method returns a boolean indicating if the authentication
440
+ * succeeded or failed.
441
+ */
442
+ async check() {
443
+ try {
444
+ await this.authenticate();
445
+ return true;
446
+ }
447
+ catch (error) {
448
+ if (error instanceof AuthenticationException) {
449
+ return false;
450
+ }
451
+ throw error;
452
+ }
453
+ }
454
+ }
@@ -0,0 +1,3 @@
1
+ export { SessionGuard } from './guard.js';
2
+ export { RememberMeToken } from './token.js';
3
+ export { sessionGuard, tokensProvider } from './define_config.js';
@@ -0,0 +1,11 @@
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';
@@ -0,0 +1,57 @@
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
+ }
@@ -0,0 +1,58 @@
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 { Token } from '../../core/token.js';
10
+ /**
11
+ * Remember me token represents a remember me token created
12
+ * for a peristed login flow.
13
+ */
14
+ export class RememberMeToken extends Token {
15
+ userId;
16
+ series;
17
+ value;
18
+ hash;
19
+ /**
20
+ * Static name for the token to uniquely identify a
21
+ * bucket of tokens
22
+ */
23
+ type = 'remember_me_token';
24
+ constructor(
25
+ /**
26
+ * Reference to the user id for whom the token
27
+ * is generated
28
+ */
29
+ userId,
30
+ /**
31
+ * Series is a random number stored inside the database as it is
32
+ */
33
+ series,
34
+ /**
35
+ * Value is a random number only available at the time of issuing
36
+ * the token. Afterwards, the value is undefined.
37
+ */
38
+ value,
39
+ /**
40
+ * Hash reference to the token hash
41
+ */
42
+ hash) {
43
+ super(series, value, hash);
44
+ this.userId = userId;
45
+ this.series = series;
46
+ this.value = value;
47
+ this.hash = hash;
48
+ }
49
+ /**
50
+ * Create remember me token instance for a user
51
+ */
52
+ static create(userId, expiry, size) {
53
+ const { series, value, hash } = this.seed(size);
54
+ const token = new RememberMeToken(userId, series, value, hash);
55
+ token.setExpiry(expiry);
56
+ return token;
57
+ }
58
+ }
@@ -0,0 +1,33 @@
1
+ import { RememberMeToken } from '../token.js';
2
+ import type { RememberMeProviderContract } from '../types.js';
3
+ import { DatabaseTokenProvider } from '../../../core/token_providers/database.js';
4
+ /**
5
+ * Remember me token provider to persist tokens inside the database
6
+ * using db query builder.
7
+ */
8
+ export declare class DatabaseRememberTokenProvider extends DatabaseTokenProvider<RememberMeToken> implements RememberMeProviderContract {
9
+ /**
10
+ * Prepares a token from the database result
11
+ */
12
+ protected prepareToken(dbRow: {
13
+ series: string;
14
+ user_id: string | number;
15
+ type: string;
16
+ token: string;
17
+ created_at: Date;
18
+ updated_at: Date;
19
+ expires_at: Date | null;
20
+ }): RememberMeToken;
21
+ /**
22
+ * Converts the remember me token into a database row
23
+ */
24
+ protected parseToken(token: RememberMeToken): {
25
+ series: string;
26
+ user_id: string | number;
27
+ type: string;
28
+ token: string;
29
+ created_at: Date;
30
+ updated_at: Date;
31
+ expires_at: Date | null;
32
+ };
33
+ }
@@ -0,0 +1,42 @@
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 { RememberMeToken } from '../token.js';
10
+ import { DatabaseTokenProvider } from '../../../core/token_providers/database.js';
11
+ /**
12
+ * Remember me token provider to persist tokens inside the database
13
+ * using db query builder.
14
+ */
15
+ export class DatabaseRememberTokenProvider extends DatabaseTokenProvider {
16
+ /**
17
+ * Prepares a token from the database result
18
+ */
19
+ prepareToken(dbRow) {
20
+ const token = new RememberMeToken(dbRow.user_id, dbRow.series, undefined, dbRow.token);
21
+ if (dbRow.expires_at) {
22
+ token.expiresAt = dbRow.expires_at;
23
+ }
24
+ token.createdAt = dbRow.created_at;
25
+ token.updatedAt = dbRow.updated_at;
26
+ return token;
27
+ }
28
+ /**
29
+ * Converts the remember me token into a database row
30
+ */
31
+ parseToken(token) {
32
+ return {
33
+ series: token.series,
34
+ user_id: token.userId,
35
+ type: token.type,
36
+ token: token.hash,
37
+ created_at: token.createdAt,
38
+ updated_at: token.updatedAt,
39
+ expires_at: token.expiresAt,
40
+ };
41
+ }
42
+ }