@adonisjs/auth 8.2.2 → 9.0.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 (134) 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 +41 -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 +18 -0
  22. package/build/src/auth/auth_manager.js +28 -0
  23. package/build/src/auth/authenticator.d.ts +18 -0
  24. package/build/src/auth/authenticator.js +55 -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 +8 -0
  30. package/build/src/auth/errors.js +17 -0
  31. package/build/src/auth/symbols.d.ts +9 -0
  32. package/build/src/auth/symbols.js +17 -0
  33. package/build/src/auth/types.d.ts +52 -0
  34. package/build/{adonis-typings/context.js → src/auth/types.js} +2 -1
  35. package/build/src/auth/user_providers/main.d.ts +15 -0
  36. package/build/src/auth/user_providers/main.js +22 -0
  37. package/build/src/core/guard_user.d.ts +26 -0
  38. package/build/src/core/guard_user.js +29 -0
  39. package/build/src/core/token.d.ts +86 -0
  40. package/build/src/core/token.js +112 -0
  41. package/build/src/core/token_providers/database.d.ts +77 -0
  42. package/build/src/core/token_providers/database.js +113 -0
  43. package/build/src/core/types.d.ts +178 -0
  44. package/build/{adonis-typings/auth.js → src/core/types.js} +2 -1
  45. package/build/src/core/user_providers/database.d.ts +78 -0
  46. package/build/src/core/user_providers/database.js +117 -0
  47. package/build/src/core/user_providers/lucid.d.ts +61 -0
  48. package/build/src/core/user_providers/lucid.js +122 -0
  49. package/build/src/guards/session/define_config.d.ts +23 -0
  50. package/build/src/guards/session/define_config.js +56 -0
  51. package/build/src/guards/session/guard.d.ts +92 -0
  52. package/build/src/guards/session/guard.js +380 -0
  53. package/build/src/guards/session/main.d.ts +3 -0
  54. package/build/src/guards/session/main.js +11 -0
  55. package/build/src/guards/session/token.d.ts +57 -0
  56. package/build/src/guards/session/token.js +58 -0
  57. package/build/src/guards/session/token_providers/main.d.ts +33 -0
  58. package/build/src/guards/session/token_providers/main.js +42 -0
  59. package/build/src/guards/session/types.d.ts +97 -0
  60. package/build/{adonis-typings/events.js → src/guards/session/types.js} +2 -1
  61. package/build/stubs/config/auth_middleware.stub +12 -0
  62. package/build/stubs/config.stub +35 -0
  63. package/build/stubs/main.d.ts +1 -0
  64. package/build/{adonis-typings/tests.js → stubs/main.js} +2 -3
  65. package/package.json +96 -91
  66. package/build/adonis-typings/auth.d.ts +0 -635
  67. package/build/adonis-typings/container.d.ts +0 -6
  68. package/build/adonis-typings/context.d.ts +0 -6
  69. package/build/adonis-typings/events.d.ts +0 -10
  70. package/build/adonis-typings/index.d.ts +0 -5
  71. package/build/adonis-typings/index.js +0 -13
  72. package/build/adonis-typings/tests.d.ts +0 -23
  73. package/build/instructions.js +0 -338
  74. package/build/providers/AuthProvider.d.ts +0 -30
  75. package/build/providers/AuthProvider.js +0 -69
  76. package/build/src/Auth/index.d.ts +0 -97
  77. package/build/src/Auth/index.js +0 -155
  78. package/build/src/AuthManager/index.d.ts +0 -117
  79. package/build/src/AuthManager/index.js +0 -262
  80. package/build/src/Bindings/Tests.d.ts +0 -6
  81. package/build/src/Bindings/Tests.js +0 -69
  82. package/build/src/Clients/Oat/index.d.ts +0 -50
  83. package/build/src/Clients/Oat/index.js +0 -123
  84. package/build/src/Clients/Session/index.d.ts +0 -34
  85. package/build/src/Clients/Session/index.js +0 -72
  86. package/build/src/Exceptions/AuthenticationException.d.ts +0 -47
  87. package/build/src/Exceptions/AuthenticationException.js +0 -142
  88. package/build/src/Exceptions/InvalidCredentialsException.d.ts +0 -34
  89. package/build/src/Exceptions/InvalidCredentialsException.js +0 -112
  90. package/build/src/Guards/Base/index.d.ts +0 -75
  91. package/build/src/Guards/Base/index.js +0 -138
  92. package/build/src/Guards/BasicAuth/index.d.ts +0 -67
  93. package/build/src/Guards/BasicAuth/index.js +0 -181
  94. package/build/src/Guards/Oat/index.d.ts +0 -149
  95. package/build/src/Guards/Oat/index.js +0 -347
  96. package/build/src/Guards/Session/index.d.ts +0 -127
  97. package/build/src/Guards/Session/index.js +0 -338
  98. package/build/src/TokenProviders/Database/index.d.ts +0 -43
  99. package/build/src/TokenProviders/Database/index.js +0 -126
  100. package/build/src/TokenProviders/Redis/index.d.ts +0 -44
  101. package/build/src/TokenProviders/Redis/index.js +0 -129
  102. package/build/src/Tokens/OpaqueToken/index.d.ts +0 -46
  103. package/build/src/Tokens/OpaqueToken/index.js +0 -43
  104. package/build/src/Tokens/ProviderToken/index.d.ts +0 -23
  105. package/build/src/Tokens/ProviderToken/index.js +0 -27
  106. package/build/src/UserProviders/Database/User.d.ts +0 -28
  107. package/build/src/UserProviders/Database/User.js +0 -74
  108. package/build/src/UserProviders/Database/index.d.ts +0 -75
  109. package/build/src/UserProviders/Database/index.js +0 -141
  110. package/build/src/UserProviders/Lucid/User.d.ts +0 -28
  111. package/build/src/UserProviders/Lucid/User.js +0 -74
  112. package/build/src/UserProviders/Lucid/index.d.ts +0 -72
  113. package/build/src/UserProviders/Lucid/index.js +0 -146
  114. package/build/standalone.d.ts +0 -1
  115. package/build/standalone.js +0 -13
  116. package/build/templates/config/auth.txt +0 -34
  117. package/build/templates/config/partials/api-guard.txt +0 -22
  118. package/build/templates/config/partials/basic-guard.txt +0 -19
  119. package/build/templates/config/partials/tokens-provider-database.txt +0 -19
  120. package/build/templates/config/partials/tokens-provider-redis.txt +0 -22
  121. package/build/templates/config/partials/user-provider-database.txt +0 -43
  122. package/build/templates/config/partials/user-provider-lucid.txt +0 -45
  123. package/build/templates/config/partials/web-guard.txt +0 -17
  124. package/build/templates/contract/auth.txt +0 -55
  125. package/build/templates/contract/partials/api-guard.txt +0 -14
  126. package/build/templates/contract/partials/basic-guard.txt +0 -14
  127. package/build/templates/contract/partials/user-provider-database.txt +0 -16
  128. package/build/templates/contract/partials/user-provider-lucid.txt +0 -16
  129. package/build/templates/contract/partials/web-guard.txt +0 -14
  130. package/build/templates/middleware/Auth.txt +0 -76
  131. package/build/templates/middleware/SilentAuth.txt +0 -21
  132. package/build/templates/migrations/api_tokens.txt +0 -25
  133. package/build/templates/migrations/auth.txt +0 -24
  134. package/build/templates/model.txt +0 -30
@@ -1,347 +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.OATGuard = void 0;
12
- const luxon_1 = require("luxon");
13
- const crypto_1 = require("crypto");
14
- const helpers_1 = require("@poppinss/utils/build/helpers");
15
- const Base_1 = require("../Base");
16
- const OpaqueToken_1 = require("../../Tokens/OpaqueToken");
17
- const ProviderToken_1 = require("../../Tokens/ProviderToken");
18
- const AuthenticationException_1 = require("../../Exceptions/AuthenticationException");
19
- /**
20
- * Exposes the API to generate and authenticate HTTP request using
21
- * opaque tokens
22
- */
23
- class OATGuard extends Base_1.BaseGuard {
24
- constructor(name, config, emitter, provider, ctx, tokenProvider) {
25
- super(name, config, provider);
26
- this.config = config;
27
- this.emitter = emitter;
28
- this.ctx = ctx;
29
- this.tokenProvider = tokenProvider;
30
- /**
31
- * Length of the raw token. The hash length will vary
32
- */
33
- this.tokenLength = 60;
34
- /**
35
- * Token type for the persistance store
36
- */
37
- this.tokenType = this.config.tokenProvider.type || 'opaque_token';
38
- /**
39
- * Whether or not the authentication has been attempted
40
- * for the current request
41
- */
42
- this.authenticationAttempted = false;
43
- /**
44
- * Find if the user has been logged out in the current request
45
- */
46
- this.isLoggedOut = false;
47
- /**
48
- * A boolean to know if user is retrieved by authenticating
49
- * the current request or not
50
- */
51
- this.isAuthenticated = false;
52
- }
53
- /**
54
- * Accessor to know if user is logged in
55
- */
56
- get isLoggedIn() {
57
- return !!this.user;
58
- }
59
- /**
60
- * Accessor to know if user is a guest. It is always opposite
61
- * of [[isLoggedIn]]
62
- */
63
- get isGuest() {
64
- return !this.isLoggedIn;
65
- }
66
- /**
67
- * Converts value to a sha256 hash
68
- */
69
- generateHash(token) {
70
- return (0, crypto_1.createHash)('sha256').update(token).digest('hex');
71
- }
72
- /**
73
- * Converts expiry duration to an absolute date/time value
74
- */
75
- getExpiresAtDate(expiresIn) {
76
- if (!expiresIn) {
77
- return;
78
- }
79
- const milliseconds = typeof expiresIn === 'string' ? helpers_1.string.toMs(expiresIn) : expiresIn;
80
- return luxon_1.DateTime.local().plus({ milliseconds });
81
- }
82
- /**
83
- * Generates a new token + hash for the persistance
84
- */
85
- generateTokenForPersistance(expiresIn) {
86
- const token = helpers_1.string.generateRandom(this.tokenLength);
87
- return {
88
- token,
89
- hash: this.generateHash(token),
90
- expiresAt: this.getExpiresAtDate(expiresIn),
91
- };
92
- }
93
- /**
94
- * Returns data packet for the login event. Arguments are
95
- *
96
- * - The mapping identifier
97
- * - Logged in user
98
- * - HTTP context
99
- * - API token
100
- */
101
- getLoginEventData(user, token) {
102
- return {
103
- name: this.name,
104
- ctx: this.ctx,
105
- user,
106
- token,
107
- };
108
- }
109
- /**
110
- * Returns data packet for the authenticate event. Arguments are
111
- *
112
- * - The mapping identifier
113
- * - Logged in user
114
- * - HTTP context
115
- * - A boolean to tell if logged in viaRemember or not
116
- */
117
- getAuthenticateEventData(user, token) {
118
- return {
119
- name: this.name,
120
- ctx: this.ctx,
121
- user,
122
- token,
123
- };
124
- }
125
- /**
126
- * Parses the token received in the request. The method also performs
127
- * some initial level of sanity checks.
128
- */
129
- parsePublicToken(token) {
130
- const parts = token.split('.');
131
- /**
132
- * Ensure the token has two parts
133
- */
134
- if (parts.length !== 2) {
135
- throw AuthenticationException_1.AuthenticationException.invalidToken(this.name);
136
- }
137
- /**
138
- * Ensure the first part is a base64 encode id
139
- */
140
- const tokenId = helpers_1.base64.urlDecode(parts[0], undefined, true);
141
- if (!tokenId) {
142
- throw AuthenticationException_1.AuthenticationException.invalidToken(this.name);
143
- }
144
- /**
145
- * Ensure 2nd part of the token has the expected length
146
- */
147
- if (parts[1].length !== this.tokenLength) {
148
- throw AuthenticationException_1.AuthenticationException.invalidToken(this.name);
149
- }
150
- /**
151
- * Set parsed token
152
- */
153
- this.parsedToken = {
154
- tokenId,
155
- value: parts[1],
156
- };
157
- return this.parsedToken;
158
- }
159
- /**
160
- * Returns the bearer token
161
- */
162
- getBearerToken() {
163
- /**
164
- * Ensure the "Authorization" header value exists
165
- */
166
- const token = this.ctx.request.header('Authorization');
167
- if (!token) {
168
- throw AuthenticationException_1.AuthenticationException.invalidToken(this.name);
169
- }
170
- /**
171
- * Ensure that token has minimum of two parts and the first
172
- * part is a constant string named `bearer`
173
- */
174
- const [type, value] = token.split(' ');
175
- if (!type || type.toLowerCase() !== 'bearer' || !value) {
176
- throw AuthenticationException_1.AuthenticationException.invalidToken(this.name);
177
- }
178
- return value;
179
- }
180
- /**
181
- * Returns the token by reading it from the token provider
182
- */
183
- async getProviderToken(tokenId, value) {
184
- const providerToken = await this.tokenProvider.read(tokenId, this.generateHash(value), this.tokenType);
185
- if (!providerToken) {
186
- throw AuthenticationException_1.AuthenticationException.invalidToken(this.name);
187
- }
188
- return providerToken;
189
- }
190
- /**
191
- * Returns user from the user session id
192
- */
193
- async getUserById(id) {
194
- const authenticatable = await this.provider.findById(id);
195
- if (!authenticatable.user) {
196
- throw AuthenticationException_1.AuthenticationException.invalidToken(this.name);
197
- }
198
- return authenticatable;
199
- }
200
- /**
201
- * Verify user credentials and perform login
202
- */
203
- async attempt(uid, password, options) {
204
- const user = await this.verifyCredentials(uid, password);
205
- return this.login(user, options);
206
- }
207
- /**
208
- * Login user using their id
209
- */
210
- async loginViaId(id, options) {
211
- const providerUser = await this.findById(id);
212
- return this.login(providerUser.user, options);
213
- }
214
- /**
215
- * Generate token for a user. It is merely an alias for `login`
216
- */
217
- async generate(user, options) {
218
- return this.login(user, options);
219
- }
220
- /**
221
- * Login a user
222
- */
223
- async login(user, options) {
224
- /**
225
- * Normalize options with defaults
226
- */
227
- const { expiresIn, name, ...meta } = Object.assign({
228
- name: 'Opaque Access Token',
229
- }, options);
230
- /**
231
- * Since the login method is not exposed to the end user, we cannot expect
232
- * them to instantiate and pass an instance of provider user, so we
233
- * create one manually.
234
- */
235
- const providerUser = await this.getUserForLogin(user, this.config.provider.identifierKey);
236
- /**
237
- * "getUserForLogin" raises exception when id is missing, so we can
238
- * safely assume it is defined
239
- */
240
- const id = providerUser.getId();
241
- const token = this.generateTokenForPersistance(expiresIn);
242
- /**
243
- * Persist token to the database. Make sure that we are always
244
- * passing the hash to the storage driver
245
- */
246
- const providerToken = new ProviderToken_1.ProviderToken(name, token.hash, id, this.tokenType);
247
- providerToken.expiresAt = token.expiresAt;
248
- providerToken.meta = meta;
249
- const tokenId = await this.tokenProvider.write(providerToken);
250
- /**
251
- * Construct a new API Token instance
252
- */
253
- const apiToken = new OpaqueToken_1.OpaqueToken(name, `${helpers_1.base64.urlEncode(tokenId)}.${token.token}`, providerUser.user);
254
- apiToken.tokenHash = token.hash;
255
- apiToken.expiresAt = token.expiresAt;
256
- apiToken.meta = meta || {};
257
- /**
258
- * Emit login event. It can be used to track user logins.
259
- */
260
- this.emitter.emit('adonis:api:login', this.getLoginEventData(providerUser.user, apiToken));
261
- /**
262
- * Marking user as logged in
263
- */
264
- this.markUserAsLoggedIn(providerUser.user);
265
- this.token = providerToken;
266
- return apiToken;
267
- }
268
- /**
269
- * Authenticates the current HTTP request by checking for the bearer token
270
- */
271
- async authenticate() {
272
- /**
273
- * Return early when authentication has already attempted for
274
- * the current request
275
- */
276
- if (this.authenticationAttempted) {
277
- return this.user;
278
- }
279
- this.authenticationAttempted = true;
280
- /**
281
- * Ensure the "Authorization" header value exists
282
- */
283
- const token = this.getBearerToken();
284
- const { tokenId, value } = this.parsePublicToken(token);
285
- /**
286
- * Query token and user
287
- */
288
- const providerToken = await this.getProviderToken(tokenId, value);
289
- const providerUser = await this.getUserById(providerToken.userId);
290
- this.markUserAsLoggedIn(providerUser.user, true);
291
- this.token = providerToken;
292
- this.emitter.emit('adonis:api:authenticate', this.getAuthenticateEventData(providerUser.user, this.token));
293
- return providerUser.user;
294
- }
295
- /**
296
- * Same as [[authenticate]] but returns a boolean over raising exceptions
297
- */
298
- async check() {
299
- try {
300
- await this.authenticate();
301
- }
302
- catch (error) {
303
- /**
304
- * Throw error when it is not an instance of the authentication
305
- */
306
- if (error instanceof AuthenticationException_1.AuthenticationException === false) {
307
- throw error;
308
- }
309
- this.ctx.logger.trace(error, 'Authentication failure');
310
- }
311
- return this.isAuthenticated;
312
- }
313
- /**
314
- * Alias for the logout method
315
- */
316
- async revoke() {
317
- return this.logout();
318
- }
319
- /**
320
- * Logout by removing the token from the storage
321
- */
322
- async logout() {
323
- if (!this.authenticationAttempted) {
324
- await this.check();
325
- }
326
- /**
327
- * Clean up token from storage
328
- */
329
- if (this.parsedToken) {
330
- await this.tokenProvider.destroy(this.parsedToken.tokenId, this.tokenType);
331
- }
332
- this.markUserAsLoggedOut();
333
- }
334
- /**
335
- * Serialize toJSON for JSON.stringify
336
- */
337
- toJSON() {
338
- return {
339
- isLoggedIn: this.isLoggedIn,
340
- isGuest: this.isGuest,
341
- authenticationAttempted: this.authenticationAttempted,
342
- isAuthenticated: this.isAuthenticated,
343
- user: this.user,
344
- };
345
- }
346
- }
347
- exports.OATGuard = OATGuard;
@@ -1,127 +0,0 @@
1
- /// <reference types="@adonisjs/events/build/adonis-typings" />
2
- import { EmitterContract } from '@ioc:Adonis/Core/Event';
3
- import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
4
- import { UserProviderContract, SessionGuardConfig, SessionGuardContract } from '@ioc:Adonis/Addons/Auth';
5
- import { BaseGuard } from '../Base';
6
- /**
7
- * Session guard enables user login using sessions. Also it allows for
8
- * setting remember me tokens for life long login
9
- */
10
- export declare class SessionGuard extends BaseGuard<any> implements SessionGuardContract<any, any> {
11
- private emitter;
12
- private ctx;
13
- constructor(name: string, config: SessionGuardConfig<any>, emitter: EmitterContract, provider: UserProviderContract<any>, ctx: HttpContextContract);
14
- /**
15
- * Number of years for the remember me token expiry
16
- */
17
- private rememberMeTokenExpiry;
18
- /**
19
- * The name of the session key name
20
- */
21
- get sessionKeyName(): string;
22
- /**
23
- * The name of the session key name
24
- */
25
- get rememberMeKeyName(): string;
26
- /**
27
- * Returns the session object from the context.
28
- */
29
- private getSession;
30
- /**
31
- * Set the user id inside the session. Also forces the session module
32
- * to re-generate the session id
33
- */
34
- private setSession;
35
- /**
36
- * Generate remember me token
37
- */
38
- private generateRememberMeToken;
39
- /**
40
- * Sets the remember me cookie with the remember me token
41
- */
42
- private setRememberMeCookie;
43
- /**
44
- * Clears the remember me cookie
45
- */
46
- private clearRememberMeCookie;
47
- /**
48
- * Clears user session and remember me cookie
49
- */
50
- private clearUserFromStorage;
51
- /**
52
- * Returns data packet for the login event. Arguments are
53
- *
54
- * - The mapping identifier
55
- * - Logged in user
56
- * - HTTP context
57
- * - Remember me token (optional)
58
- */
59
- private getLoginEventData;
60
- /**
61
- * Returns data packet for the authenticate event. Arguments are
62
- *
63
- * - The mapping identifier
64
- * - Logged in user
65
- * - HTTP context
66
- * - A boolean to tell if logged in viaRemember or not
67
- */
68
- private getAuthenticateEventData;
69
- /**
70
- * Returns the user id for the current HTTP request
71
- */
72
- private getRequestSessionId;
73
- /**
74
- * Verifies the remember me token
75
- */
76
- private verifyRememberMeToken;
77
- /**
78
- * Returns user from the user session id
79
- */
80
- private getUserForSessionId;
81
- /**
82
- * Returns user for the remember me token
83
- */
84
- private getUserForRememberMeToken;
85
- /**
86
- * Returns the remember me token of the user that is persisted
87
- * inside the db. If not persisted, we create one and persist
88
- * it
89
- */
90
- private getPersistedRememberMeToken;
91
- /**
92
- * Verify user credentials and perform login
93
- */
94
- attempt(uid: string, password: string, remember?: boolean): Promise<any>;
95
- /**
96
- * Login user using their id
97
- */
98
- loginViaId(id: string | number, remember?: boolean): Promise<void>;
99
- /**
100
- * Login a user
101
- */
102
- login(user: any, remember?: boolean): Promise<void>;
103
- /**
104
- * Authenticates the current HTTP request by checking for the user
105
- * session.
106
- */
107
- authenticate(): Promise<any>;
108
- /**
109
- * Same as [[authenticate]] but returns a boolean over raising exceptions
110
- */
111
- check(): Promise<boolean>;
112
- /**
113
- * Logout by clearing session and cookies
114
- */
115
- logout(recycleRememberToken?: boolean): Promise<void>;
116
- /**
117
- * Serialize toJSON for JSON.stringify
118
- */
119
- toJSON(): {
120
- isLoggedIn: boolean;
121
- isGuest: boolean;
122
- viaRemember: boolean;
123
- authenticationAttempted: boolean;
124
- isAuthenticated: boolean;
125
- user: any;
126
- };
127
- }