@adonisjs/auth 9.0.0-0 → 9.0.0-10

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 (39) hide show
  1. package/build/configure.js +5 -26
  2. package/build/factories/basic_auth_guard_factory.d.ts +12 -0
  3. package/build/factories/basic_auth_guard_factory.js +22 -0
  4. package/build/index.d.ts +1 -2
  5. package/build/index.js +1 -2
  6. package/build/src/auth/auth_manager.d.ts +9 -0
  7. package/build/src/auth/auth_manager.js +13 -0
  8. package/build/src/auth/authenticator.d.ts +45 -0
  9. package/build/src/auth/authenticator.js +74 -0
  10. package/build/src/auth/authenticator_client.d.ts +23 -0
  11. package/build/src/auth/authenticator_client.js +59 -0
  12. package/build/src/auth/errors.d.ts +86 -4
  13. package/build/src/auth/errors.js +189 -5
  14. package/build/src/auth/middleware/initialize_auth_middleware.d.ts +18 -0
  15. package/build/src/auth/middleware/initialize_auth_middleware.js +25 -0
  16. package/build/src/auth/plugins/japa/api_client.d.ts +32 -0
  17. package/build/src/auth/plugins/japa/api_client.js +63 -0
  18. package/build/src/auth/plugins/japa/browser_client.d.ts +25 -0
  19. package/build/src/auth/plugins/japa/browser_client.js +64 -0
  20. package/build/src/auth/types.d.ts +60 -8
  21. package/build/src/core/token.d.ts +4 -1
  22. package/build/src/core/token.js +5 -3
  23. package/build/src/core/token_providers/database.d.ts +1 -1
  24. package/build/src/guards/basic_auth/define_config.d.ts +16 -0
  25. package/build/src/guards/basic_auth/define_config.js +38 -0
  26. package/build/src/guards/basic_auth/guard.d.ts +70 -0
  27. package/build/src/guards/basic_auth/guard.js +193 -0
  28. package/build/src/guards/basic_auth/main.d.ts +2 -0
  29. package/build/{stubs → src/guards/basic_auth}/main.js +2 -2
  30. package/build/src/guards/basic_auth/types.d.ts +40 -0
  31. package/build/src/guards/basic_auth/types.js +9 -0
  32. package/build/src/guards/session/define_config.js +1 -1
  33. package/build/src/guards/session/guard.d.ts +33 -2
  34. package/build/src/guards/session/guard.js +153 -11
  35. package/build/src/guards/session/types.d.ts +19 -3
  36. package/package.json +54 -30
  37. package/build/stubs/config/auth_middleware.stub +0 -12
  38. package/build/stubs/config.stub +0 -35
  39. package/build/stubs/main.d.ts +0 -1
@@ -6,36 +6,15 @@
6
6
  * For the full copyright and license information, please view the LICENSE
7
7
  * file that was distributed with this source code.
8
8
  */
9
- /**
10
- * Configures the user provider to use for finding
11
- * users
12
- */
13
- async function configureProvider(command) {
14
- const provider = await command.prompt.choice('Select the user provider you want to use', [
15
- {
16
- name: 'lucid',
17
- message: 'Lucid models',
18
- },
19
- {
20
- name: 'db',
21
- message: 'Database query builder',
22
- },
23
- ]);
24
- /**
25
- * Publish config file
26
- */
27
- await command.publishStub('config.stub', { provider });
28
- }
9
+ import { presetAuth } from '@adonisjs/presets/auth';
29
10
  /**
30
11
  * Configures the auth package
31
12
  */
32
13
  export async function configure(command) {
33
- await configureProvider(command);
34
14
  const codemods = await command.createCodemods();
35
- /**
36
- * Register provider
37
- */
38
- await codemods.updateRcFile((rcFile) => {
39
- rcFile.addProvider('@adonisjs/auth/auth_provider');
15
+ // let guard: string | undefined = command.parsedFlags.guard
16
+ await presetAuth(codemods, command.app, {
17
+ guard: 'session',
18
+ userProvider: 'lucid',
40
19
  });
41
20
  }
@@ -0,0 +1,12 @@
1
+ import type { HttpContext } from '@adonisjs/core/http';
2
+ import { FactoryUser, TestLucidUserProvider } from './lucid_user_provider.js';
3
+ import { BasicAuthGuard } from '../src/guards/basic_auth/guard.js';
4
+ import type { UserProviderContract } from '../src/core/types.js';
5
+ /**
6
+ * Exposes the API to create a basic auth guard for testing. Under
7
+ * the hood configures Lucid models for looking up users
8
+ */
9
+ export declare class BasicAuthGuardFactory {
10
+ merge(): this;
11
+ create<UserProvider extends UserProviderContract<unknown> = TestLucidUserProvider<typeof FactoryUser>>(ctx: HttpContext, provider?: UserProvider): BasicAuthGuard<TestLucidUserProvider<typeof FactoryUser> | UserProvider>;
12
+ }
@@ -0,0 +1,22 @@
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 { LucidUserProviderFactory, } from './lucid_user_provider.js';
10
+ import { BasicAuthGuard } from '../src/guards/basic_auth/guard.js';
11
+ /**
12
+ * Exposes the API to create a basic auth guard for testing. Under
13
+ * the hood configures Lucid models for looking up users
14
+ */
15
+ export class BasicAuthGuardFactory {
16
+ merge() {
17
+ return this;
18
+ }
19
+ create(ctx, provider) {
20
+ return new BasicAuthGuard('basic', ctx, provider || new LucidUserProviderFactory().create());
21
+ }
22
+ }
package/build/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  export { configure } from './configure.js';
2
- export { stubsRoot } from './stubs/main.js';
3
- export * as errors from './src/auth/errors.js';
4
2
  export * as symbols from './src/auth/symbols.js';
5
3
  export { AuthManager } from './src/auth/auth_manager.js';
6
4
  export { Authenticator } from './src/auth/authenticator.js';
7
5
  export { defineConfig, providers } from './src/auth/define_config.js';
6
+ export { AuthenticationException, InvalidCredentialsException } from './src/auth/errors.js';
package/build/index.js CHANGED
@@ -7,9 +7,8 @@
7
7
  * file that was distributed with this source code.
8
8
  */
9
9
  export { configure } from './configure.js';
10
- export { stubsRoot } from './stubs/main.js';
11
- export * as errors from './src/auth/errors.js';
12
10
  export * as symbols from './src/auth/symbols.js';
13
11
  export { AuthManager } from './src/auth/auth_manager.js';
14
12
  export { Authenticator } from './src/auth/authenticator.js';
15
13
  export { defineConfig, providers } from './src/auth/define_config.js';
14
+ export { AuthenticationException, InvalidCredentialsException } from './src/auth/errors.js';
@@ -1,12 +1,17 @@
1
1
  import type { HttpContext } from '@adonisjs/core/http';
2
2
  import type { GuardFactory } from './types.js';
3
3
  import { Authenticator } from './authenticator.js';
4
+ import { AuthenticatorClient } from './authenticator_client.js';
4
5
  /**
5
6
  * Auth manager exposes the API to register and manage authentication
6
7
  * guards from the config
7
8
  */
8
9
  export declare class AuthManager<KnownGuards extends Record<string, GuardFactory>> {
9
10
  #private;
11
+ /**
12
+ * Name of the default guard
13
+ */
14
+ get defaultGuard(): keyof KnownGuards;
10
15
  constructor(config: {
11
16
  default: keyof KnownGuards;
12
17
  guards: KnownGuards;
@@ -15,4 +20,8 @@ export declare class AuthManager<KnownGuards extends Record<string, GuardFactory
15
20
  * Create an authenticator for a given HTTP request
16
21
  */
17
22
  createAuthenticator(ctx: HttpContext): Authenticator<KnownGuards>;
23
+ /**
24
+ * Creates an instance of the authenticator client
25
+ */
26
+ createAuthenticatorClient(): AuthenticatorClient<KnownGuards>;
18
27
  }
@@ -7,6 +7,7 @@
7
7
  * file that was distributed with this source code.
8
8
  */
9
9
  import { Authenticator } from './authenticator.js';
10
+ import { AuthenticatorClient } from './authenticator_client.js';
10
11
  /**
11
12
  * Auth manager exposes the API to register and manage authentication
12
13
  * guards from the config
@@ -16,6 +17,12 @@ export class AuthManager {
16
17
  * Registered guards
17
18
  */
18
19
  #config;
20
+ /**
21
+ * Name of the default guard
22
+ */
23
+ get defaultGuard() {
24
+ return this.#config.default;
25
+ }
19
26
  constructor(config) {
20
27
  this.#config = config;
21
28
  }
@@ -25,4 +32,10 @@ export class AuthManager {
25
32
  createAuthenticator(ctx) {
26
33
  return new Authenticator(ctx, this.#config);
27
34
  }
35
+ /**
36
+ * Creates an instance of the authenticator client
37
+ */
38
+ createAuthenticatorClient() {
39
+ return new AuthenticatorClient(this.#config);
40
+ }
28
41
  }
@@ -6,13 +6,58 @@ import type { GuardFactory } from './types.js';
6
6
  */
7
7
  export declare class Authenticator<KnownGuards extends Record<string, GuardFactory>> {
8
8
  #private;
9
+ /**
10
+ * Name of the default guard
11
+ */
12
+ get defaultGuard(): keyof KnownGuards;
13
+ /**
14
+ * Reference to the guard using which the current
15
+ * request has been authenticated.
16
+ */
17
+ get authenticatedViaGuard(): keyof KnownGuards | undefined;
18
+ /**
19
+ * A boolean to know if the current request has
20
+ * been authenticated
21
+ */
22
+ get isAuthenticated(): boolean;
23
+ /**
24
+ * Reference to the currently authenticated user
25
+ */
26
+ get user(): {
27
+ [K in keyof KnownGuards]: ReturnType<KnownGuards[K]>['user'];
28
+ }[keyof KnownGuards];
29
+ /**
30
+ * Whether or not the authentication has been attempted
31
+ * during the current request
32
+ */
33
+ get authenticationAttempted(): boolean;
9
34
  constructor(ctx: HttpContext, config: {
10
35
  default: keyof KnownGuards;
11
36
  guards: KnownGuards;
12
37
  });
38
+ /**
39
+ * Returns an instance of the logged-in user or throws an
40
+ * exception
41
+ */
42
+ getUserOrFail(): {
43
+ [K in keyof KnownGuards]: ReturnType<ReturnType<KnownGuards[K]>['getUserOrFail']>;
44
+ }[keyof KnownGuards];
13
45
  /**
14
46
  * Returns an instance of a known guard. Guards instances are
15
47
  * cached during the lifecycle of an HTTP request.
16
48
  */
17
49
  use<Guard extends keyof KnownGuards>(guard?: Guard): ReturnType<KnownGuards[Guard]>;
50
+ /**
51
+ * Authenticate the request using all of the mentioned
52
+ * guards or the default guard.
53
+ *
54
+ * The authentication process will stop after any of the
55
+ * mentioned guards is able to authenticate the request
56
+ * successfully.
57
+ *
58
+ * Otherwise, "AuthenticationException" will be raised.
59
+ */
60
+ authenticateUsing(guards?: (keyof KnownGuards)[], options?: {
61
+ loginRoute?: string;
62
+ }): Promise<boolean>;
18
63
  }
@@ -7,11 +7,17 @@
7
7
  * file that was distributed with this source code.
8
8
  */
9
9
  import debug from './debug.js';
10
+ import { AuthenticationException } from './errors.js';
10
11
  /**
11
12
  * Authenticator is an HTTP request specific implementation for using
12
13
  * guards to login users and authenticate requests.
13
14
  */
14
15
  export class Authenticator {
16
+ /**
17
+ * Name of the guard using which the request has
18
+ * been authenticated
19
+ */
20
+ #authenticatedViaGuard;
15
21
  /**
16
22
  * Reference to HTTP context
17
23
  */
@@ -24,11 +30,51 @@ export class Authenticator {
24
30
  * Cache of guards created during the HTTP request
25
31
  */
26
32
  #guardsCache = {};
33
+ /**
34
+ * Name of the default guard
35
+ */
36
+ get defaultGuard() {
37
+ return this.#config.default;
38
+ }
39
+ /**
40
+ * Reference to the guard using which the current
41
+ * request has been authenticated.
42
+ */
43
+ get authenticatedViaGuard() {
44
+ return this.#authenticatedViaGuard;
45
+ }
46
+ /**
47
+ * A boolean to know if the current request has
48
+ * been authenticated
49
+ */
50
+ get isAuthenticated() {
51
+ return this.use(this.#authenticatedViaGuard || this.defaultGuard).isAuthenticated;
52
+ }
53
+ /**
54
+ * Reference to the currently authenticated user
55
+ */
56
+ get user() {
57
+ return this.use(this.#authenticatedViaGuard || this.defaultGuard).user;
58
+ }
59
+ /**
60
+ * Whether or not the authentication has been attempted
61
+ * during the current request
62
+ */
63
+ get authenticationAttempted() {
64
+ return this.use(this.#authenticatedViaGuard || this.defaultGuard).authenticationAttempted;
65
+ }
27
66
  constructor(ctx, config) {
28
67
  this.#ctx = ctx;
29
68
  this.#config = config;
30
69
  debug('creating authenticator. config %O', this.#config);
31
70
  }
71
+ /**
72
+ * Returns an instance of the logged-in user or throws an
73
+ * exception
74
+ */
75
+ getUserOrFail() {
76
+ return this.use(this.#authenticatedViaGuard || this.defaultGuard).getUserOrFail();
77
+ }
32
78
  /**
33
79
  * Returns an instance of a known guard. Guards instances are
34
80
  * cached during the lifecycle of an HTTP request.
@@ -52,4 +98,32 @@ export class Authenticator {
52
98
  this.#guardsCache[guardToUse] = guardInstance;
53
99
  return guardInstance;
54
100
  }
101
+ /**
102
+ * Authenticate the request using all of the mentioned
103
+ * guards or the default guard.
104
+ *
105
+ * The authentication process will stop after any of the
106
+ * mentioned guards is able to authenticate the request
107
+ * successfully.
108
+ *
109
+ * Otherwise, "AuthenticationException" will be raised.
110
+ */
111
+ async authenticateUsing(guards, options) {
112
+ const guardsToUse = guards || [this.defaultGuard];
113
+ let lastUsedGuardDriver;
114
+ for (let guardName of guardsToUse) {
115
+ debug('attempting to authenticate using guard "%s"', guardName);
116
+ const guard = this.use(guardName);
117
+ lastUsedGuardDriver = guard.driverName;
118
+ if (await guard.check()) {
119
+ this.#authenticatedViaGuard = guardName;
120
+ return true;
121
+ }
122
+ }
123
+ throw new AuthenticationException('Unauthorized access', {
124
+ code: 'E_UNAUTHORIZED_ACCESS',
125
+ guardDriverName: lastUsedGuardDriver,
126
+ redirectTo: options?.loginRoute,
127
+ });
128
+ }
55
129
  }
@@ -0,0 +1,23 @@
1
+ import type { GuardFactory } from './types.js';
2
+ /**
3
+ * Authenticator client is used to create guard instances for
4
+ * testing. It passes a fake HTTPContext to the guards, so
5
+ * make sure to not call server side APIs that might be
6
+ * relying on a real HTTPContext instance
7
+ */
8
+ export declare class AuthenticatorClient<KnownGuards extends Record<string, GuardFactory>> {
9
+ #private;
10
+ /**
11
+ * Name of the default guard
12
+ */
13
+ get defaultGuard(): keyof KnownGuards;
14
+ constructor(config: {
15
+ default: keyof KnownGuards;
16
+ guards: KnownGuards;
17
+ });
18
+ /**
19
+ * Returns an instance of a known guard. Guards instances are
20
+ * cached during the lifecycle of an HTTP request.
21
+ */
22
+ use<Guard extends keyof KnownGuards>(guard?: Guard): ReturnType<KnownGuards[Guard]>;
23
+ }
@@ -0,0 +1,59 @@
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 debug from './debug.js';
10
+ import { HttpContextFactory } from '@adonisjs/core/factories/http';
11
+ /**
12
+ * Authenticator client is used to create guard instances for
13
+ * testing. It passes a fake HTTPContext to the guards, so
14
+ * make sure to not call server side APIs that might be
15
+ * relying on a real HTTPContext instance
16
+ */
17
+ export class AuthenticatorClient {
18
+ /**
19
+ * Registered guards
20
+ */
21
+ #config;
22
+ /**
23
+ * Cache of guards
24
+ */
25
+ #guardsCache = {};
26
+ /**
27
+ * Name of the default guard
28
+ */
29
+ get defaultGuard() {
30
+ return this.#config.default;
31
+ }
32
+ constructor(config) {
33
+ this.#config = config;
34
+ debug('creating authenticator client. config %O', this.#config);
35
+ }
36
+ /**
37
+ * Returns an instance of a known guard. Guards instances are
38
+ * cached during the lifecycle of an HTTP request.
39
+ */
40
+ use(guard) {
41
+ const guardToUse = guard || this.#config.default;
42
+ /**
43
+ * Use cached copy if exists
44
+ */
45
+ const cachedGuard = this.#guardsCache[guardToUse];
46
+ if (cachedGuard) {
47
+ debug('using guard from cache. name: "%s"', guardToUse);
48
+ return cachedGuard;
49
+ }
50
+ const guardFactory = this.#config.guards[guardToUse];
51
+ /**
52
+ * Construct guard and cache it
53
+ */
54
+ debug('creating guard. name: "%s"', guardToUse);
55
+ const guardInstance = guardFactory(new HttpContextFactory().create());
56
+ this.#guardsCache[guardToUse] = guardInstance;
57
+ return guardInstance;
58
+ }
59
+ }
@@ -1,8 +1,90 @@
1
+ import { Exception } from '@poppinss/utils';
2
+ import { HttpContext } from '@adonisjs/core/http';
1
3
  /**
2
- * Invalid token provided
4
+ * Authentication exception is raised when an attempt is
5
+ * made to authenticate an HTTP request
3
6
  */
4
- export declare const E_INVALID_AUTH_TOKEN: new (args?: any, options?: ErrorOptions | undefined) => import("@poppinss/utils").Exception;
7
+ export declare class AuthenticationException extends Exception {
8
+ static status?: number | undefined;
9
+ static code?: string | undefined;
10
+ /**
11
+ * Raises authentication exception when session guard
12
+ * is unable to authenticate the request
13
+ */
14
+ static E_INVALID_AUTH_SESSION(): AuthenticationException;
15
+ /**
16
+ * Raises authentication exception when session guard
17
+ * is unable to authenticate the request
18
+ */
19
+ static E_INVALID_BASIC_AUTH_CREDENTIALS(): AuthenticationException;
20
+ guardDriverName: string;
21
+ redirectTo?: string;
22
+ identifier: string;
23
+ constructor(message: string, options: ErrorOptions & {
24
+ guardDriverName: string;
25
+ redirectTo?: string;
26
+ code?: string;
27
+ status?: number;
28
+ });
29
+ /**
30
+ * Returns the message to be sent in the HTTP response.
31
+ * Feel free to override this method and return a custom
32
+ * response.
33
+ */
34
+ getResponseMessage(error: AuthenticationException, ctx: HttpContext): string;
35
+ /**
36
+ * A collection of authentication exception
37
+ * renderers to render the exception to a
38
+ * response.
39
+ *
40
+ * The collection is a key-value pair, where the
41
+ * key is the guard driver name and value is
42
+ * a factory function to respond to the
43
+ * request.
44
+ */
45
+ renderers: Record<string, (message: string, error: AuthenticationException, ctx: HttpContext) => Promise<void> | void>;
46
+ /**
47
+ * Self handles the auth exception and converts it to an
48
+ * HTTP response
49
+ */
50
+ handle(error: AuthenticationException, ctx: HttpContext): Promise<void>;
51
+ }
5
52
  /**
6
- * The user session is invalid
53
+ * Invalid credentials exception is raised when unable
54
+ * to verify user credentials during login
7
55
  */
8
- export declare const E_INVALID_AUTH_SESSION: new (args?: any, options?: ErrorOptions | undefined) => import("@poppinss/utils").Exception;
56
+ export declare class InvalidCredentialsException extends Exception {
57
+ static message: string;
58
+ static code: string;
59
+ static status?: number | undefined;
60
+ static E_INVALID_CREDENTIALS(guardDriverName: string): InvalidCredentialsException;
61
+ guardDriverName: string;
62
+ identifier: string;
63
+ constructor(message: string, options: ErrorOptions & {
64
+ guardDriverName: string;
65
+ code?: string;
66
+ status?: number;
67
+ });
68
+ /**
69
+ * Returns the message to be sent in the HTTP response.
70
+ * Feel free to override this method and return a custom
71
+ * response.
72
+ */
73
+ getResponseMessage(error: InvalidCredentialsException, ctx: HttpContext): string;
74
+ /**
75
+ * A collection of authentication exception
76
+ * renderers to render the exception to a
77
+ * response.
78
+ *
79
+ * The collection is a key-value pair, where the
80
+ * key is the guard driver name and value is
81
+ * a factory function to respond to the
82
+ * request.
83
+ */
84
+ renderers: Record<string, (message: string, error: InvalidCredentialsException, ctx: HttpContext) => Promise<void> | void>;
85
+ /**
86
+ * Self handles the auth exception and converts it to an
87
+ * HTTP response
88
+ */
89
+ handle(error: InvalidCredentialsException, ctx: HttpContext): Promise<void>;
90
+ }