@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,201 +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 { Exception } from '@poppinss/utils';
10
- /**
11
- * Authentication exception is raised when an attempt is
12
- * made to authenticate an HTTP request
13
- */
14
- export class AuthenticationException extends Exception {
15
- static status = 401;
16
- static code = 'E_UNAUTHORIZED_ACCESS';
17
- /**
18
- * Raises authentication exception when session guard
19
- * is unable to authenticate the request
20
- */
21
- static E_INVALID_AUTH_SESSION() {
22
- return new AuthenticationException('Invalid or expired authentication session', {
23
- code: 'E_INVALID_AUTH_SESSION',
24
- status: 401,
25
- guardDriverName: 'session',
26
- });
27
- }
28
- /**
29
- * Raises authentication exception when session guard
30
- * is unable to authenticate the request
31
- */
32
- static E_INVALID_BASIC_AUTH_CREDENTIALS() {
33
- return new AuthenticationException('Invalid basic auth credentials', {
34
- code: 'E_INVALID_BASIC_AUTH_CREDENTIALS',
35
- status: 401,
36
- guardDriverName: 'basic_auth',
37
- });
38
- }
39
- guardDriverName;
40
- redirectTo;
41
- identifier = 'auth.authenticate';
42
- constructor(message, options) {
43
- super(message, options);
44
- this.guardDriverName = options.guardDriverName;
45
- this.redirectTo = options.redirectTo;
46
- }
47
- /**
48
- * Returns the message to be sent in the HTTP response.
49
- * Feel free to override this method and return a custom
50
- * response.
51
- */
52
- getResponseMessage(error, ctx) {
53
- if ('i18n' in ctx) {
54
- return ctx.i18n.t(error.identifier, {}, error.message);
55
- }
56
- return error.message;
57
- }
58
- /**
59
- * A collection of authentication exception
60
- * renderers to render the exception to a
61
- * response.
62
- *
63
- * The collection is a key-value pair, where the
64
- * key is the guard driver name and value is
65
- * a factory function to respond to the
66
- * request.
67
- */
68
- renderers = {
69
- session: (message, error, ctx) => {
70
- switch (ctx.request.accepts(['html', 'application/vnd.api+json', 'json'])) {
71
- case 'html':
72
- case null:
73
- ctx.session.flashExcept(['_csrf']);
74
- ctx.session.flash({ errors: { [error.identifier]: [message] } });
75
- ctx.response.redirect(error.redirectTo || '/', true);
76
- break;
77
- case 'json':
78
- ctx.response.status(error.status).send({
79
- errors: [
80
- {
81
- message,
82
- },
83
- ],
84
- });
85
- break;
86
- case 'application/vnd.api+json':
87
- ctx.response.status(error.status).send({
88
- errors: [
89
- {
90
- code: error.identifier,
91
- title: message,
92
- },
93
- ],
94
- });
95
- break;
96
- }
97
- },
98
- basic_auth: (message, _, ctx) => {
99
- ctx.response
100
- .status(this.status)
101
- .header('WWW-Authenticate', `Basic realm="Authenticate", charset="UTF-8"`)
102
- .send(message);
103
- },
104
- };
105
- /**
106
- * Self handles the auth exception and converts it to an
107
- * HTTP response
108
- */
109
- async handle(error, ctx) {
110
- const renderer = this.renderers[this.guardDriverName];
111
- const message = error.getResponseMessage(error, ctx);
112
- if (!renderer) {
113
- return ctx.response.status(error.status).send(message);
114
- }
115
- return renderer(message, error, ctx);
116
- }
117
- }
118
- /**
119
- * Invalid credentials exception is raised when unable
120
- * to verify user credentials during login
121
- */
122
- export class InvalidCredentialsException extends Exception {
123
- static message = 'Invalid credentials';
124
- static code = 'E_INVALID_CREDENTIALS';
125
- static status = 400;
126
- static E_INVALID_CREDENTIALS(guardDriverName) {
127
- return new InvalidCredentialsException(InvalidCredentialsException.message, {
128
- guardDriverName,
129
- });
130
- }
131
- guardDriverName;
132
- identifier = 'auth.login';
133
- constructor(message, options) {
134
- super(message, options);
135
- this.guardDriverName = options.guardDriverName;
136
- }
137
- /**
138
- * Returns the message to be sent in the HTTP response.
139
- * Feel free to override this method and return a custom
140
- * response.
141
- */
142
- getResponseMessage(error, ctx) {
143
- if ('i18n' in ctx) {
144
- return ctx.i18n.t(this.identifier, {}, error.message);
145
- }
146
- return error.message;
147
- }
148
- /**
149
- * A collection of authentication exception
150
- * renderers to render the exception to a
151
- * response.
152
- *
153
- * The collection is a key-value pair, where the
154
- * key is the guard driver name and value is
155
- * a factory function to respond to the
156
- * request.
157
- */
158
- renderers = {
159
- session: (message, error, ctx) => {
160
- switch (ctx.request.accepts(['html', 'application/vnd.api+json', 'json'])) {
161
- case 'html':
162
- case null:
163
- ctx.session.flashExcept(['_csrf']);
164
- ctx.session.flash({ errors: { [this.identifier]: [message] } });
165
- ctx.response.redirect().withQs().back();
166
- break;
167
- case 'json':
168
- ctx.response.status(error.status).send({
169
- errors: [
170
- {
171
- message: message,
172
- },
173
- ],
174
- });
175
- break;
176
- case 'application/vnd.api+json':
177
- ctx.response.status(error.status).send({
178
- errors: [
179
- {
180
- code: this.identifier,
181
- title: message,
182
- },
183
- ],
184
- });
185
- break;
186
- }
187
- },
188
- };
189
- /**
190
- * Self handles the auth exception and converts it to an
191
- * HTTP response
192
- */
193
- async handle(error, ctx) {
194
- const renderer = this.renderers[this.guardDriverName];
195
- const message = this.getResponseMessage(error, ctx);
196
- if (!renderer) {
197
- return ctx.response.status(error.status).send(message);
198
- }
199
- return renderer(message, error, ctx);
200
- }
201
- }
@@ -1,25 +0,0 @@
1
- /// <reference types="@adonisjs/core/providers/edge_provider" />
2
- import auth from '@adonisjs/auth/services/main';
3
- /**
4
- * The "InitializeAuthMiddleware" is used to create a request
5
- * specific authenticator instance for every HTTP request.
6
- *
7
- * This middleware does not protect routes from unauthenticated
8
- * users. Please use the "auth" middleware for that.
9
- */
10
- export default class InitializeAuthMiddleware {
11
- async handle(ctx, next) {
12
- /**
13
- * Initialize the authenticator for the current HTTP
14
- * request
15
- */
16
- ctx.auth = auth.createAuthenticator(ctx);
17
- /**
18
- * Sharing authenticator with templates
19
- */
20
- if ('view' in ctx) {
21
- ctx.view.share({ auth: ctx.auth });
22
- }
23
- return next();
24
- }
25
- }
@@ -1,63 +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 { ApiClient, ApiRequest } from '@japa/api-client';
10
- import debug from '../../debug.js';
11
- /**
12
- * Auth API client to authenticate users when making
13
- * HTTP requests using the Japa API client
14
- */
15
- export const authApiClient = (app) => {
16
- const pluginFn = function () {
17
- debug('installing auth api client plugin');
18
- ApiRequest.macro('loginAs', function (user) {
19
- this.authData = {
20
- guard: '__default__',
21
- user: user,
22
- };
23
- return this;
24
- });
25
- ApiRequest.macro('withGuard', function (guard) {
26
- return {
27
- loginAs: (user) => {
28
- this.authData = {
29
- guard,
30
- user: user,
31
- };
32
- return this;
33
- },
34
- };
35
- });
36
- /**
37
- * Hook into the request and login the user
38
- */
39
- ApiClient.setup(async (request) => {
40
- const auth = await app.container.make('auth.manager');
41
- const authData = request['authData'];
42
- if (!authData) {
43
- return;
44
- }
45
- const client = auth.createAuthenticatorClient();
46
- const guard = authData.guard === '__default__' ? client.use() : client.use(authData.guard);
47
- const requestData = await guard.authenticateAsClient(authData.user);
48
- if (requestData.headers) {
49
- debug('defining headers with api client request %O', requestData.headers);
50
- request.headers(requestData.headers);
51
- }
52
- if (requestData.session) {
53
- debug('defining session with api client request %O', requestData.session);
54
- request.withSession(requestData.session);
55
- }
56
- if (requestData.cookies) {
57
- debug('defining session with api client request %O', requestData.session);
58
- request.cookies(requestData.cookies);
59
- }
60
- });
61
- };
62
- return pluginFn;
63
- };
@@ -1,42 +0,0 @@
1
- /*
2
- * @adoniss/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
- /// <reference types="@japa/plugin-adonisjs" />
10
- /// <reference types="@adonisjs/session/plugins/browser_client" />
11
- import { RuntimeException } from '@poppinss/utils';
12
- import { decoratorsCollection } from '@japa/browser-client';
13
- import debug from '../../debug.js';
14
- export const authBrowserClient = (app) => {
15
- const pluginFn = async function () {
16
- debug('installing auth browser client plugin');
17
- const auth = await app.container.make('auth.manager');
18
- decoratorsCollection.register({
19
- context(context) {
20
- context.loginAs = async function (user) {
21
- const client = auth.createAuthenticatorClient();
22
- const guard = client.use();
23
- const requestData = await guard.authenticateAsClient(user);
24
- if (requestData.headers) {
25
- throw new RuntimeException(`Cannot use "${guard.driverName}" guard with browser client`);
26
- }
27
- if (requestData.cookies) {
28
- debug('defining cookies with browser context %O', requestData.cookies);
29
- Object.keys(requestData.cookies).forEach((cookie) => {
30
- context.setCookie(cookie, requestData.cookies[cookie]);
31
- });
32
- }
33
- if (requestData.session) {
34
- debug('defining session with browser context %O', requestData.session);
35
- context.setSession(requestData.session);
36
- }
37
- };
38
- },
39
- });
40
- };
41
- return pluginFn;
42
- };
@@ -1,17 +0,0 @@
1
- /*
2
- * @adonisjs/lucid
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
- /**
10
- * A symbol to identify the type of the real user for a given
11
- * user provider
12
- */
13
- export const PROVIDER_REAL_USER = Symbol.for('PROVIDER_REAL_USER');
14
- /**
15
- * A symbol to identify the type for the events emitted by a guard
16
- */
17
- export const GUARD_KNOWN_EVENTS = Symbol.for('GUARD_KNOWN_EVENTS');
@@ -1,9 +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 {};
@@ -1,15 +0,0 @@
1
- import { BaseLucidUserProvider } from '../../core/user_providers/lucid.js';
2
- import { BaseDatabaseUserProvider } from '../../core/user_providers/database.js';
3
- import type { LucidAuthenticatable, UserProviderContract } from '../../core/types.js';
4
- /**
5
- * Using lucid models to find users for session
6
- * auth
7
- */
8
- export declare class LucidUserProvider<UserModel extends LucidAuthenticatable> extends BaseLucidUserProvider<UserModel> implements UserProviderContract<InstanceType<UserModel>> {
9
- }
10
- /**
11
- * Using database query builder to find users for
12
- * session auth
13
- */
14
- export declare class DatabaseUserProvider<User extends Record<string, any>> extends BaseDatabaseUserProvider<User> implements UserProviderContract<User> {
15
- }
@@ -1,22 +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 { BaseLucidUserProvider } from '../../core/user_providers/lucid.js';
10
- import { BaseDatabaseUserProvider } from '../../core/user_providers/database.js';
11
- /**
12
- * Using lucid models to find users for session
13
- * auth
14
- */
15
- export class LucidUserProvider extends BaseLucidUserProvider {
16
- }
17
- /**
18
- * Using database query builder to find users for
19
- * session auth
20
- */
21
- export class DatabaseUserProvider extends BaseDatabaseUserProvider {
22
- }
@@ -1,26 +0,0 @@
1
- /**
2
- * Guard user represents a user independent of the storage
3
- * provider. It contains a standard set of properties
4
- * used by authentication guards to interact with
5
- * a user.
6
- *
7
- * Think of it as a bridge between a user and the authentication
8
- * guard.
9
- */
10
- export declare abstract class GuardUser<RealUser> {
11
- protected realUser: RealUser;
12
- constructor(realUser: RealUser);
13
- /**
14
- * Verifies the plain text password against the user password
15
- * hash
16
- */
17
- abstract verifyPassword(plainTextPassword: string): Promise<boolean>;
18
- /**
19
- * Returns a value to uniquely identify the user.
20
- */
21
- abstract getId(): number | string;
22
- /**
23
- * Returns the original provider specific user object.
24
- */
25
- getOriginal(): RealUser;
26
- }
@@ -1,29 +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
- /**
10
- * Guard user represents a user independent of the storage
11
- * provider. It contains a standard set of properties
12
- * used by authentication guards to interact with
13
- * a user.
14
- *
15
- * Think of it as a bridge between a user and the authentication
16
- * guard.
17
- */
18
- export class GuardUser {
19
- realUser;
20
- constructor(realUser) {
21
- this.realUser = realUser;
22
- }
23
- /**
24
- * Returns the original provider specific user object.
25
- */
26
- getOriginal() {
27
- return this.realUser;
28
- }
29
- }
@@ -1,89 +0,0 @@
1
- import type { TokenContract } from './types.js';
2
- /**
3
- * A token represents an opaque token issued to a client
4
- * to perform a specific task.
5
- *
6
- * The raw value of a token is only visible at the time of
7
- * issuing it and one must persist hash to the database.
8
- */
9
- export declare abstract class Token implements TokenContract {
10
- /**
11
- * Series is a random number stored inside the database as it is
12
- */
13
- series: string;
14
- /**
15
- * Value is a random number only available at the time of issuing
16
- * the token. Afterwards, the value is undefined.
17
- */
18
- value: string | undefined;
19
- /**
20
- * Hash reference to the token hash
21
- */
22
- hash: string;
23
- /**
24
- * Token type to uniquely identify a bucket of tokens
25
- */
26
- abstract readonly type: string;
27
- /**
28
- * Arbitary meta-data associated with the token
29
- */
30
- metaData?: Record<string, any>;
31
- /**
32
- * Timestamp when the token will expire
33
- */
34
- expiresAt?: Date;
35
- /**
36
- * Date/time when the token instance was created
37
- */
38
- createdAt: Date;
39
- /**
40
- * Date/time when the token was updated
41
- */
42
- updatedAt: Date;
43
- constructor(
44
- /**
45
- * Series is a random number stored inside the database as it is
46
- */
47
- series: string,
48
- /**
49
- * Value is a random number only available at the time of issuing
50
- * the token. Afterwards, the value is undefined.
51
- */
52
- value: string | undefined,
53
- /**
54
- * Hash reference to the token hash
55
- */
56
- hash: string);
57
- /**
58
- * Define metadata for the token
59
- */
60
- setMetaData(metaData: Record<string, any>): this;
61
- /**
62
- * Verifies the value of a token against the pre-defined hash
63
- */
64
- verify(value: string): boolean;
65
- /**
66
- * Define the token expiresAt timestamp from a duration. The value
67
- * value must be a number in seconds or a string expression.
68
- */
69
- setExpiry(duration: string | number): void;
70
- /**
71
- * Creates token value, series, and hash
72
- */
73
- static seed(size?: number): {
74
- series: string;
75
- value: string;
76
- hash: string;
77
- };
78
- /**
79
- * Decodes a publicly shared token and return the series
80
- * and the token value from it.
81
- *
82
- * Returns null when unable to decode the token because of
83
- * invalid format or encoding.
84
- */
85
- static decode(value: string): null | {
86
- series: string;
87
- value: string;
88
- };
89
- }
@@ -1,114 +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 { createHash } from 'node:crypto';
10
- import string from '@adonisjs/core/helpers/string';
11
- import { base64, safeEqual } from '@adonisjs/core/helpers';
12
- /**
13
- * A token represents an opaque token issued to a client
14
- * to perform a specific task.
15
- *
16
- * The raw value of a token is only visible at the time of
17
- * issuing it and one must persist hash to the database.
18
- */
19
- export class Token {
20
- series;
21
- value;
22
- hash;
23
- /**
24
- * Arbitary meta-data associated with the token
25
- */
26
- metaData;
27
- /**
28
- * Timestamp when the token will expire
29
- */
30
- expiresAt;
31
- /**
32
- * Date/time when the token instance was created
33
- */
34
- createdAt = new Date();
35
- /**
36
- * Date/time when the token was updated
37
- */
38
- updatedAt = new Date();
39
- constructor(
40
- /**
41
- * Series is a random number stored inside the database as it is
42
- */
43
- series,
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,
49
- /**
50
- * Hash reference to the token hash
51
- */
52
- hash) {
53
- this.series = series;
54
- this.value = value;
55
- this.hash = hash;
56
- }
57
- /**
58
- * Define metadata for the token
59
- */
60
- setMetaData(metaData) {
61
- this.metaData = metaData;
62
- return this;
63
- }
64
- /**
65
- * Verifies the value of a token against the pre-defined hash
66
- */
67
- verify(value) {
68
- const newHash = createHash('sha256').update(value).digest('hex');
69
- return safeEqual(this.hash, newHash);
70
- }
71
- /**
72
- * Define the token expiresAt timestamp from a duration. The value
73
- * value must be a number in seconds or a string expression.
74
- */
75
- setExpiry(duration) {
76
- /**
77
- * Defining a date object and adding seconds since the
78
- * creation of the token
79
- */
80
- this.expiresAt = new Date();
81
- this.expiresAt.setSeconds(this.createdAt.getSeconds() + string.seconds.parse(duration));
82
- }
83
- /**
84
- * Creates token value, series, and hash
85
- */
86
- static seed(size = 30) {
87
- const series = string.random(15);
88
- const value = string.random(size);
89
- const hash = createHash('sha256').update(value).digest('hex');
90
- return { series, value: `${base64.urlEncode(series)}.${base64.urlEncode(value)}`, hash };
91
- }
92
- /**
93
- * Decodes a publicly shared token and return the series
94
- * and the token value from it.
95
- *
96
- * Returns null when unable to decode the token because of
97
- * invalid format or encoding.
98
- */
99
- static decode(value) {
100
- const [series, ...tokenValue] = value.split('.');
101
- if (!series || tokenValue.length === 0) {
102
- return null;
103
- }
104
- const decodedSeries = base64.urlDecode(series);
105
- const decodedValue = base64.urlDecode(tokenValue.join('.'));
106
- if (!decodedSeries || !decodedValue) {
107
- return null;
108
- }
109
- return {
110
- series: decodedSeries,
111
- value: decodedValue,
112
- };
113
- }
114
- }