@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
@@ -1,338 +0,0 @@
1
- "use strict";
2
- /*
3
- * @adonisjs/auth
4
- *
5
- * (c) Harminder Virk <virk@adonisjs.com>
6
- *
7
- * For the full copyright and license information, please view the LICENSE
8
- * file that was distributed with this source code.
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.SessionGuard = void 0;
12
- const utils_1 = require("@poppinss/utils");
13
- const helpers_1 = require("@poppinss/utils/build/helpers");
14
- const Base_1 = require("../Base");
15
- const AuthenticationException_1 = require("../../Exceptions/AuthenticationException");
16
- /**
17
- * Session guard enables user login using sessions. Also it allows for
18
- * setting remember me tokens for life long login
19
- */
20
- class SessionGuard extends Base_1.BaseGuard {
21
- constructor(name, config, emitter, provider, ctx) {
22
- super(name, config, provider);
23
- this.emitter = emitter;
24
- this.ctx = ctx;
25
- /**
26
- * Number of years for the remember me token expiry
27
- */
28
- this.rememberMeTokenExpiry = '5y';
29
- }
30
- /**
31
- * The name of the session key name
32
- */
33
- get sessionKeyName() {
34
- return `auth_${this.name}`;
35
- }
36
- /**
37
- * The name of the session key name
38
- */
39
- get rememberMeKeyName() {
40
- return `remember_${this.name}`;
41
- }
42
- /**
43
- * Returns the session object from the context.
44
- */
45
- getSession() {
46
- if (!this.ctx.session) {
47
- throw new utils_1.Exception('"@adonisjs/session" is required to use the "session" auth driver');
48
- }
49
- return this.ctx.session;
50
- }
51
- /**
52
- * Set the user id inside the session. Also forces the session module
53
- * to re-generate the session id
54
- */
55
- setSession(userId) {
56
- this.getSession().put(this.sessionKeyName, userId);
57
- this.getSession().regenerate();
58
- }
59
- /**
60
- * Generate remember me token
61
- */
62
- generateRememberMeToken() {
63
- return helpers_1.string.generateRandom(20);
64
- }
65
- /**
66
- * Sets the remember me cookie with the remember me token
67
- */
68
- setRememberMeCookie(userId, token) {
69
- const value = {
70
- id: userId,
71
- token: token,
72
- };
73
- this.ctx.response.encryptedCookie(this.rememberMeKeyName, value, {
74
- maxAge: this.rememberMeTokenExpiry,
75
- httpOnly: true,
76
- });
77
- }
78
- /**
79
- * Clears the remember me cookie
80
- */
81
- clearRememberMeCookie() {
82
- this.ctx.response.clearCookie(this.rememberMeKeyName);
83
- }
84
- /**
85
- * Clears user session and remember me cookie
86
- */
87
- clearUserFromStorage() {
88
- this.getSession().forget(this.sessionKeyName);
89
- this.clearRememberMeCookie();
90
- }
91
- /**
92
- * Returns data packet for the login event. Arguments are
93
- *
94
- * - The mapping identifier
95
- * - Logged in user
96
- * - HTTP context
97
- * - Remember me token (optional)
98
- */
99
- getLoginEventData(user, token) {
100
- return {
101
- name: this.name,
102
- ctx: this.ctx,
103
- user,
104
- token,
105
- };
106
- }
107
- /**
108
- * Returns data packet for the authenticate event. Arguments are
109
- *
110
- * - The mapping identifier
111
- * - Logged in user
112
- * - HTTP context
113
- * - A boolean to tell if logged in viaRemember or not
114
- */
115
- getAuthenticateEventData(user, viaRemember) {
116
- return {
117
- name: this.name,
118
- ctx: this.ctx,
119
- user,
120
- viaRemember,
121
- };
122
- }
123
- /**
124
- * Returns the user id for the current HTTP request
125
- */
126
- getRequestSessionId() {
127
- return this.getSession().get(this.sessionKeyName);
128
- }
129
- /**
130
- * Verifies the remember me token
131
- */
132
- verifyRememberMeToken(rememberMeToken) {
133
- if (!rememberMeToken || !rememberMeToken.id || !rememberMeToken.token) {
134
- throw AuthenticationException_1.AuthenticationException.invalidSession(this.name);
135
- }
136
- }
137
- /**
138
- * Returns user from the user session id
139
- */
140
- async getUserForSessionId(id) {
141
- const authenticatable = await this.provider.findById(id);
142
- if (!authenticatable.user) {
143
- throw AuthenticationException_1.AuthenticationException.invalidSession(this.name);
144
- }
145
- return authenticatable;
146
- }
147
- /**
148
- * Returns user for the remember me token
149
- */
150
- async getUserForRememberMeToken(id, token) {
151
- const authenticatable = await this.provider.findByRememberMeToken(id, token);
152
- if (!authenticatable.user) {
153
- throw AuthenticationException_1.AuthenticationException.invalidSession(this.name);
154
- }
155
- return authenticatable;
156
- }
157
- /**
158
- * Returns the remember me token of the user that is persisted
159
- * inside the db. If not persisted, we create one and persist
160
- * it
161
- */
162
- async getPersistedRememberMeToken(providerUser) {
163
- /**
164
- * Create and persist the user remember me token, when an existing one is missing
165
- */
166
- if (!providerUser.getRememberMeToken()) {
167
- this.ctx.logger.trace('generating fresh remember me token');
168
- providerUser.setRememberMeToken(this.generateRememberMeToken());
169
- await this.provider.updateRememberMeToken(providerUser);
170
- }
171
- return providerUser.getRememberMeToken();
172
- }
173
- /**
174
- * Verify user credentials and perform login
175
- */
176
- async attempt(uid, password, remember) {
177
- const user = await this.verifyCredentials(uid, password);
178
- await this.login(user, remember);
179
- return user;
180
- }
181
- /**
182
- * Login user using their id
183
- */
184
- async loginViaId(id, remember) {
185
- const providerUser = await this.findById(id);
186
- await this.login(providerUser.user, remember);
187
- return providerUser.user;
188
- }
189
- /**
190
- * Login a user
191
- */
192
- async login(user, remember) {
193
- /**
194
- * Since the login method is exposed to the end user, we cannot expect
195
- * them to instantiate and return an instance of authenticatable, so
196
- * we create one manually.
197
- */
198
- const providerUser = await this.getUserForLogin(user, this.config.provider.identifierKey);
199
- /**
200
- * getUserForLogin raises exception when id is missing, so we can
201
- * safely assume it is defined
202
- */
203
- const id = providerUser.getId();
204
- /**
205
- * Set session
206
- */
207
- this.setSession(id);
208
- /**
209
- * Set remember me token when enabled
210
- */
211
- if (remember) {
212
- const rememberMeToken = await this.getPersistedRememberMeToken(providerUser);
213
- this.ctx.logger.trace('setting remember me cookie', { name: this.rememberMeKeyName });
214
- this.setRememberMeCookie(id, rememberMeToken);
215
- }
216
- else {
217
- /**
218
- * Clear remember me cookie, which may have been set previously.
219
- */
220
- this.clearRememberMeCookie();
221
- }
222
- /**
223
- * Emit login event. It can be used to track user logins and their devices.
224
- */
225
- this.emitter.emit('adonis:session:login', this.getLoginEventData(providerUser.user, providerUser.getRememberMeToken()));
226
- this.markUserAsLoggedIn(providerUser.user);
227
- return providerUser.user;
228
- }
229
- /**
230
- * Authenticates the current HTTP request by checking for the user
231
- * session.
232
- */
233
- async authenticate() {
234
- if (this.authenticationAttempted) {
235
- return this.user;
236
- }
237
- this.authenticationAttempted = true;
238
- const sessionId = this.getRequestSessionId();
239
- /**
240
- * If session id exists, then attempt to login the user using the
241
- * session and return early
242
- */
243
- if (sessionId) {
244
- const providerUser = await this.getUserForSessionId(sessionId);
245
- this.markUserAsLoggedIn(providerUser.user, true);
246
- this.emitter.emit('adonis:session:authenticate', this.getAuthenticateEventData(providerUser.user, false));
247
- return this.user;
248
- }
249
- /**
250
- * Otherwise look for remember me token. Raise exception, if both remember
251
- * me token and session id are missing.
252
- */
253
- const rememberMeToken = this.ctx.request.encryptedCookie(this.rememberMeKeyName);
254
- if (!rememberMeToken) {
255
- throw AuthenticationException_1.AuthenticationException.invalidSession(this.name);
256
- }
257
- /**
258
- * Ensure remember me token is valid after reading it from the cookie
259
- */
260
- this.verifyRememberMeToken(rememberMeToken);
261
- /**
262
- * Attempt to locate the user for remember me token
263
- */
264
- const providerUser = await this.getUserForRememberMeToken(rememberMeToken.id, rememberMeToken.token);
265
- this.setSession(providerUser.getId());
266
- this.setRememberMeCookie(rememberMeToken.id, rememberMeToken.token);
267
- this.markUserAsLoggedIn(providerUser.user, true, true);
268
- this.emitter.emit('adonis:session:authenticate', this.getAuthenticateEventData(providerUser.user, true));
269
- return this.user;
270
- }
271
- /**
272
- * Same as [[authenticate]] but returns a boolean over raising exceptions
273
- */
274
- async check() {
275
- try {
276
- await this.authenticate();
277
- }
278
- catch (error) {
279
- /**
280
- * Throw error when it is not an instance of the authentication
281
- */
282
- if (error instanceof AuthenticationException_1.AuthenticationException === false) {
283
- throw error;
284
- }
285
- this.ctx.logger.trace(error, 'Authentication failure');
286
- }
287
- return this.isAuthenticated;
288
- }
289
- /**
290
- * Logout by clearing session and cookies
291
- */
292
- async logout(recycleRememberToken) {
293
- /**
294
- * Return early when not attempting to re-generate the remember me token
295
- */
296
- if (!recycleRememberToken) {
297
- this.clearUserFromStorage();
298
- this.markUserAsLoggedOut();
299
- return;
300
- }
301
- /**
302
- * Attempt to authenticate the current request if not already authenticated. This
303
- * will help us get an instance of the current user
304
- */
305
- if (!this.authenticationAttempted) {
306
- await this.check();
307
- }
308
- /**
309
- * If authentication passed, then re-generate the remember me token
310
- * for the current user.
311
- */
312
- if (this.user) {
313
- const providerUser = await this.provider.getUserFor(this.user);
314
- this.ctx.logger.trace('re-generating remember me token');
315
- providerUser.setRememberMeToken(this.generateRememberMeToken());
316
- await this.provider.updateRememberMeToken(providerUser);
317
- }
318
- /**
319
- * Logout user
320
- */
321
- this.clearUserFromStorage();
322
- this.markUserAsLoggedOut();
323
- }
324
- /**
325
- * Serialize toJSON for JSON.stringify
326
- */
327
- toJSON() {
328
- return {
329
- isLoggedIn: this.isLoggedIn,
330
- isGuest: this.isGuest,
331
- viaRemember: this.viaRemember,
332
- authenticationAttempted: this.authenticationAttempted,
333
- isAuthenticated: this.isAuthenticated,
334
- user: this.user,
335
- };
336
- }
337
- }
338
- exports.SessionGuard = SessionGuard;
@@ -1,43 +0,0 @@
1
- import { DatabaseContract, QueryClientContract } from '@ioc:Adonis/Lucid/Database';
2
- import { TokenProviderContract, ProviderTokenContract, DatabaseTokenProviderConfig } from '@ioc:Adonis/Addons/Auth';
3
- import { ProviderToken } from '../../Tokens/ProviderToken';
4
- /**
5
- * Database backend tokens provider
6
- */
7
- export declare class TokenDatabaseProvider implements TokenProviderContract {
8
- private config;
9
- private db;
10
- constructor(config: DatabaseTokenProviderConfig, db: DatabaseContract);
11
- /**
12
- * Custom connection or query client
13
- */
14
- private connection?;
15
- /**
16
- * Returns the query client for database queries
17
- */
18
- private getQueryClient;
19
- /**
20
- * The foreign key column
21
- */
22
- private foreignKey;
23
- /**
24
- * Returns the builder query for a given token + type
25
- */
26
- private getLookupQuery;
27
- /**
28
- * Define custom connection
29
- */
30
- setConnection(connection: string | QueryClientContract): this;
31
- /**
32
- * Reads the token using the lookup token id
33
- */
34
- read(tokenId: string, tokenHash: string, tokenType: string): Promise<ProviderTokenContract | null>;
35
- /**
36
- * Saves the token and returns the persisted token lookup id.
37
- */
38
- write(token: ProviderToken): Promise<string>;
39
- /**
40
- * Removes a given token
41
- */
42
- destroy(tokenId: string, tokenType: string): Promise<void>;
43
- }
@@ -1,126 +0,0 @@
1
- "use strict";
2
- /*
3
- * @adonisjs/auth
4
- *
5
- * (c) Harminder Virk <virk@adonisjs.com>
6
- *
7
- * For the full copyright and license information, please view the LICENSE
8
- * file that was distributed with this source code.
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.TokenDatabaseProvider = void 0;
12
- const luxon_1 = require("luxon");
13
- const helpers_1 = require("@poppinss/utils/build/helpers");
14
- const ProviderToken_1 = require("../../Tokens/ProviderToken");
15
- /**
16
- * Database backend tokens provider
17
- */
18
- class TokenDatabaseProvider {
19
- constructor(config, db) {
20
- this.config = config;
21
- this.db = db;
22
- /**
23
- * The foreign key column
24
- */
25
- this.foreignKey = this.config.foreignKey || 'user_id';
26
- }
27
- /**
28
- * Returns the query client for database queries
29
- */
30
- getQueryClient() {
31
- if (!this.connection) {
32
- return this.db.connection(this.config.connection);
33
- }
34
- return typeof this.connection === 'string'
35
- ? this.db.connection(this.connection)
36
- : this.connection;
37
- }
38
- /**
39
- * Returns the builder query for a given token + type
40
- */
41
- getLookupQuery(tokenId, tokenType) {
42
- return this.getQueryClient()
43
- .from(this.config.table)
44
- .where('id', tokenId)
45
- .where('type', tokenType);
46
- }
47
- /**
48
- * Define custom connection
49
- */
50
- setConnection(connection) {
51
- this.connection = connection;
52
- return this;
53
- }
54
- /**
55
- * Reads the token using the lookup token id
56
- */
57
- async read(tokenId, tokenHash, tokenType) {
58
- const client = this.getQueryClient();
59
- /**
60
- * Find token using id
61
- */
62
- const tokenRow = await this.getLookupQuery(tokenId, tokenType).first();
63
- if (!tokenRow || !tokenRow.token) {
64
- return null;
65
- }
66
- /**
67
- * Ensure hash of the user provided value is same as the one inside
68
- * the database
69
- */
70
- if (!(0, helpers_1.safeEqual)(tokenRow.token, tokenHash)) {
71
- return null;
72
- }
73
- const { name, [this.foreignKey]: userId, token: value, expires_at: expiresAt, type, ...meta } = tokenRow;
74
- let normalizedExpiryDate;
75
- /**
76
- * Parse dialect date to an instance of Luxon
77
- */
78
- if (expiresAt instanceof Date) {
79
- normalizedExpiryDate = luxon_1.DateTime.fromJSDate(expiresAt);
80
- }
81
- else if (expiresAt && typeof expiresAt === 'string') {
82
- normalizedExpiryDate = luxon_1.DateTime.fromFormat(expiresAt, client.dialect.dateTimeFormat);
83
- }
84
- else if (expiresAt && typeof expiresAt === 'number') {
85
- normalizedExpiryDate = luxon_1.DateTime.fromMillis(expiresAt);
86
- }
87
- /**
88
- * Ensure token isn't expired
89
- */
90
- if (normalizedExpiryDate &&
91
- normalizedExpiryDate.diff(luxon_1.DateTime.local(), 'milliseconds').milliseconds <= 0) {
92
- return null;
93
- }
94
- const token = new ProviderToken_1.ProviderToken(name, value, userId, type);
95
- token.expiresAt = expiresAt;
96
- token.meta = meta;
97
- return token;
98
- }
99
- /**
100
- * Saves the token and returns the persisted token lookup id.
101
- */
102
- async write(token) {
103
- const client = this.getQueryClient();
104
- /**
105
- * Payload to save to the database
106
- */
107
- const payload = {
108
- [this.foreignKey]: token.userId,
109
- name: token.name,
110
- token: token.tokenHash,
111
- type: token.type,
112
- expires_at: token.expiresAt ? token.expiresAt.toFormat(client.dialect.dateTimeFormat) : null,
113
- created_at: luxon_1.DateTime.local().toFormat(client.dialect.dateTimeFormat),
114
- ...token.meta,
115
- };
116
- const [row] = await client.table(this.config.table).insert(payload).returning('id');
117
- return String(typeof row === 'number' ? row : row.id);
118
- }
119
- /**
120
- * Removes a given token
121
- */
122
- async destroy(tokenId, tokenType) {
123
- await this.getLookupQuery(tokenId, tokenType).delete();
124
- }
125
- }
126
- exports.TokenDatabaseProvider = TokenDatabaseProvider;
@@ -1,44 +0,0 @@
1
- import { RedisManagerContract, RedisConnectionContract, RedisClusterConnectionContract } from '@ioc:Adonis/Addons/Redis';
2
- import { TokenProviderContract, ProviderTokenContract, RedisTokenProviderConfig } from '@ioc:Adonis/Addons/Auth';
3
- import { ProviderToken } from '../../Tokens/ProviderToken';
4
- /**
5
- * Redis backed tokens provider.
6
- */
7
- export declare class TokenRedisProvider implements TokenProviderContract {
8
- private config;
9
- private redis;
10
- constructor(config: RedisTokenProviderConfig, redis: RedisManagerContract);
11
- /**
12
- * Custom connection or query client
13
- */
14
- private connection?;
15
- /**
16
- * Returns the singleton instance of the redis connection
17
- */
18
- private getRedisConnection;
19
- /**
20
- * The foreign key column
21
- */
22
- private foreignKey;
23
- /**
24
- * Parse the stringified redis token value to an object
25
- */
26
- private parseToken;
27
- /**
28
- * Define custom connection
29
- */
30
- setConnection(connection: string | RedisConnectionContract | RedisClusterConnectionContract): this;
31
- /**
32
- * Reads the token using the lookup token id
33
- */
34
- read(tokenId: string, tokenHash: string, tokenType: string): Promise<ProviderTokenContract | null>;
35
- /**
36
- * Saves the token and returns the persisted token lookup id, which
37
- * is a cuid.
38
- */
39
- write(token: ProviderToken): Promise<string>;
40
- /**
41
- * Removes a given token
42
- */
43
- destroy(tokenId: string, tokenType: string): Promise<void>;
44
- }
@@ -1,129 +0,0 @@
1
- "use strict";
2
- /*
3
- * @adonisjs/auth
4
- *
5
- * (c) Harminder Virk <virk@adonisjs.com>
6
- *
7
- * For the full copyright and license information, please view the LICENSE
8
- * file that was distributed with this source code.
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.TokenRedisProvider = void 0;
12
- const utils_1 = require("@poppinss/utils");
13
- const helpers_1 = require("@poppinss/utils/build/helpers");
14
- const ProviderToken_1 = require("../../Tokens/ProviderToken");
15
- /**
16
- * Redis backed tokens provider.
17
- */
18
- class TokenRedisProvider {
19
- constructor(config, redis) {
20
- this.config = config;
21
- this.redis = redis;
22
- /**
23
- * The foreign key column
24
- */
25
- this.foreignKey = this.config.foreignKey || 'user_id';
26
- }
27
- /**
28
- * Returns the singleton instance of the redis connection
29
- */
30
- getRedisConnection() {
31
- /**
32
- * Use custom connection if defined
33
- */
34
- if (this.connection) {
35
- return typeof this.connection === 'string'
36
- ? this.redis.connection(this.connection)
37
- : this.connection;
38
- }
39
- /**
40
- * Config must have a connection defined
41
- */
42
- if (!this.config.redisConnection) {
43
- throw new utils_1.Exception('Missing "redisConnection" property for auth redis provider inside "config/auth" file', 500, 'E_INVALID_AUTH_REDIS_CONFIG');
44
- }
45
- return this.redis.connection(this.config.redisConnection);
46
- }
47
- /**
48
- * Parse the stringified redis token value to an object
49
- */
50
- parseToken(token) {
51
- if (!token) {
52
- return null;
53
- }
54
- try {
55
- const tokenRow = JSON.parse(token);
56
- if (!tokenRow.token || !tokenRow.name || !tokenRow[this.foreignKey]) {
57
- return null;
58
- }
59
- return tokenRow;
60
- }
61
- catch {
62
- return null;
63
- }
64
- }
65
- /**
66
- * Define custom connection
67
- */
68
- setConnection(connection) {
69
- this.connection = connection;
70
- return this;
71
- }
72
- /**
73
- * Reads the token using the lookup token id
74
- */
75
- async read(tokenId, tokenHash, tokenType) {
76
- /**
77
- * Find token using id
78
- */
79
- const tokenRow = this.parseToken(await this.getRedisConnection().get(`${tokenType}:${tokenId}`));
80
- if (!tokenRow) {
81
- return null;
82
- }
83
- /**
84
- * Ensure hash of the user provided value is same as the one inside
85
- * the database
86
- */
87
- if (!(0, helpers_1.safeEqual)(tokenRow.token, tokenHash)) {
88
- return null;
89
- }
90
- const { name, [this.foreignKey]: userId, token: value, ...meta } = tokenRow;
91
- const token = new ProviderToken_1.ProviderToken(name, value, userId, tokenType);
92
- token.meta = meta;
93
- return token;
94
- }
95
- /**
96
- * Saves the token and returns the persisted token lookup id, which
97
- * is a cuid.
98
- */
99
- async write(token) {
100
- /**
101
- * Payload to save to the database
102
- */
103
- const payload = {
104
- [this.foreignKey]: token.userId,
105
- name: token.name,
106
- token: token.tokenHash,
107
- ...token.meta,
108
- };
109
- const ttl = token.expiresAt ? Math.ceil(token.expiresAt.diffNow('seconds').seconds) : 0;
110
- const tokenId = (0, helpers_1.cuid)();
111
- if (token.expiresAt && ttl <= 0) {
112
- throw new utils_1.Exception('The expiry date/time should be in the future', 500, 'E_INVALID_TOKEN_EXPIRY');
113
- }
114
- if (token.expiresAt) {
115
- await this.getRedisConnection().setex(`${token.type}:${tokenId}`, ttl, JSON.stringify(payload));
116
- }
117
- else {
118
- await this.getRedisConnection().set(`${token.type}:${tokenId}`, JSON.stringify(payload));
119
- }
120
- return tokenId;
121
- }
122
- /**
123
- * Removes a given token
124
- */
125
- async destroy(tokenId, tokenType) {
126
- await this.getRedisConnection().del(`${tokenType}:${tokenId}`);
127
- }
128
- }
129
- exports.TokenRedisProvider = TokenRedisProvider;