@maximemrf/adonisjs-jwt 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.
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ # The MIT License
2
+
3
+ Copyright (c) 2023
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # AdonisJS package starter kit
2
+
3
+ > A boilerplate for creating AdonisJS packages
4
+
5
+ This repo provides you with a starting point for creating AdonisJS packages. Of course, you can create a package from scratch with your folder structure and workflow. However, using this starter kit can speed up the process, as you have fewer decisions to make.
6
+
7
+ ## Setup
8
+
9
+ - Clone the repo on your computer, or use `giget` to download this repo without the Git history.
10
+ ```sh
11
+ npx giget@latest gh:adonisjs/pkg-starter-kit
12
+ ```
13
+ - Install dependencies.
14
+ - Update the `package.json` file and define the `name`, `description`, `keywords`, and `author` properties.
15
+ - The repo is configured with an MIT license. Feel free to change that if you are not publishing under the MIT license.
16
+
17
+ ## Folder structure
18
+
19
+ The starter kit mimics the folder structure of the official packages. Feel free to rename files and folders as per your requirements.
20
+
21
+ ```
22
+ ├── providers
23
+ ├── src
24
+ ├── bin
25
+ ├── stubs
26
+ ├── configure.ts
27
+ ├── index.ts
28
+ ├── LICENSE.md
29
+ ├── package.json
30
+ ├── README.md
31
+ ├── tsconfig.json
32
+ ├── tsnode.esm.js
33
+ ```
34
+
35
+ - The `configure.ts` file exports the `configure` hook to configure the package using the `node ace configure` command.
36
+ - The `index.ts` file is the main entry point of the package.
37
+ - The `tsnode.esm.js` file runs TypeScript code using TS-Node + SWC. Please read the code comment in this file to learn more.
38
+ - The `bin` directory contains the entry point file to run Japa tests.
39
+ - Learn more about [the `providers` directory](./providers/README.md).
40
+ - Learn more about [the `src` directory](./src/README.md).
41
+ - Learn more about [the `stubs` directory](./stubs/README.md).
42
+
43
+ ### File system naming convention
44
+
45
+ We use `snake_case` naming conventions for the file system. The rule is enforced using ESLint. However, turn off the rule and use your preferred naming conventions.
46
+
47
+ ## Peer dependencies
48
+
49
+ The starter kit has a peer dependency on `@adonisjs/core@6`. Since you are creating a package for AdonisJS, you must make it against a specific version of the framework core.
50
+
51
+ If your package needs Lucid to be functional, you may install `@adonisjs/lucid` as a development dependency and add it to the list of `peerDependencies`.
52
+
53
+ As a rule of thumb, packages installed in the user application should be part of the `peerDependencies` of your package and not the main dependency.
54
+
55
+ For example, if you install `@adonisjs/core` as a main dependency, then essentially, you are importing a separate copy of `@adonisjs/core` and not sharing the one from the user application. Here is a great article explaining [peer dependencies](https://blog.bitsrc.io/understanding-peer-dependencies-in-javascript-dbdb4ab5a7be).
56
+
57
+ ## Published files
58
+
59
+ Instead of publishing your repo's source code to npm, you must cherry-pick files and folders to publish only the required files.
60
+
61
+ The cherry-picking uses the `files` property inside the `package.json` file. By default, we publish the following files and folders.
62
+
63
+ ```json
64
+ {
65
+ "files": ["build/src", "build/providers", "build/stubs", "build/index.d.ts", "build/index.js"]
66
+ }
67
+ ```
68
+
69
+ If you create additional folders or files, mention them inside the `files` array.
70
+
71
+ ## Exports
72
+
73
+ [Node.js Subpath exports](https://nodejs.org/api/packages.html#subpath-exports) allows you to define the exports of your package regardless of the folder structure. This starter kit defines the following exports.
74
+
75
+ ```json
76
+ {
77
+ "exports": {
78
+ ".": "./build/index.js",
79
+ "./types": "./build/src/types.js"
80
+ }
81
+ }
82
+ ```
83
+
84
+ - The dot `.` export is the main export.
85
+ - The `./types` exports all the types defined inside the `./build/src/types.js` file (the compiled output).
86
+
87
+ Feel free to change the exports as per your requirements.
88
+
89
+ ## Testing
90
+
91
+ We configure the [Japa test runner](https://japa.dev/) with this starter kit. Japa is used in AdonisJS applications as well. Just run one of the following commands to execute tests.
92
+
93
+ - `npm run test`: This command will first lint the code using ESlint and then run tests and report the test coverage using [c8](https://github.com/bcoe/c8).
94
+ - `npm run quick:test`: Runs only the tests without linting or coverage reporting.
95
+
96
+ The starter kit also has a Github workflow file to run tests using Github Actions. The tests are executed against `Node.js 20.x` and `Node.js 21.x` versions on both Linux and Windows. Feel free to edit the workflow file in the `.github/workflows` directory.
97
+
98
+ ## TypeScript workflow
99
+
100
+ - The starter kit uses [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) for compiling the TypeScript to JavaScript when publishing the package.
101
+ - [TS-Node](https://typestrong.org/ts-node/) and [SWC](https://swc.rs/) are used to run tests without compiling the source code.
102
+ - The `tsconfig.json` file is extended from [`@adonisjs/tsconfig`](https://github.com/adonisjs/tooling-config/tree/main/packages/typescript-config) and uses the `NodeNext` module system. Meaning the packages are written using ES modules.
103
+ - You can perform type checking without compiling the source code using the `npm run type check` script.
104
+
105
+ Feel free to explore the `tsconfig.json` file for all the configured options.
106
+
107
+ ## ESLint and Prettier setup
108
+
109
+ The starter kit configures ESLint and Prettier. Both configurations are stored within the `package.json` file and use our [shared config](https://github.com/adonisjs/tooling-config/tree/main/packages). Feel free to change the configuration, use custom plugins, or remove both tools altogether.
110
+
111
+ ## Using Stale bot
112
+
113
+ The [Stale bot](https://github.com/apps/stale) is a Github application that automatically marks issues and PRs as stale and closes after a specific duration of inactivity.
114
+
115
+ Feel free to delete the `.github/stale.yml` and `.github/lock.yml` files if you decide not to use the Stale bot.
@@ -0,0 +1 @@
1
+ export { configure } from './configure.js';
package/build/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /*
2
+ |--------------------------------------------------------------------------
3
+ | Package entrypoint
4
+ |--------------------------------------------------------------------------
5
+ |
6
+ | Export values from the package entrypoint as you see fit.
7
+ |
8
+ */
9
+ export { configure } from './configure.js';
@@ -0,0 +1,12 @@
1
+ import type { ApplicationService } from '@adonisjs/core/types';
2
+ import { jwtGuard } from '../src/define_config.js';
3
+ export default class JwtProvider {
4
+ protected app: ApplicationService;
5
+ constructor(app: ApplicationService);
6
+ register(): void;
7
+ }
8
+ declare module '@adonisjs/core/types' {
9
+ interface ContainerBindings {
10
+ 'max/jwt': typeof jwtGuard;
11
+ }
12
+ }
@@ -0,0 +1,12 @@
1
+ import { jwtGuard } from '../src/define_config.js';
2
+ export default class JwtProvider {
3
+ app;
4
+ constructor(app) {
5
+ this.app = app;
6
+ }
7
+ register() {
8
+ this.app.container.singleton('max/jwt', async () => {
9
+ return jwtGuard;
10
+ });
11
+ }
12
+ }
@@ -0,0 +1,7 @@
1
+ import { GuardConfigProvider } from '@adonisjs/auth/types';
2
+ import type { HttpContext } from '@adonisjs/core/http';
3
+ import { JwtGuard, JwtUserProviderContract } from './jwt.js';
4
+ export declare function jwtGuard<UserProvider extends JwtUserProviderContract<unknown>>(config: {
5
+ provider: UserProvider;
6
+ tokenExpiresIn: number | string;
7
+ }): GuardConfigProvider<(ctx: HttpContext) => JwtGuard<UserProvider>>;
@@ -0,0 +1,10 @@
1
+ import { JwtGuard } from './jwt.js';
2
+ export function jwtGuard(config) {
3
+ return {
4
+ async resolver(_, app) {
5
+ const appKey = app.config.get('app.appKey').release();
6
+ const options = { secret: appKey, expiresIn: config.tokenExpiresIn };
7
+ return (ctx) => new JwtGuard(ctx, config.provider, options);
8
+ },
9
+ };
10
+ }
@@ -0,0 +1,95 @@
1
+ import { symbols } from '@adonisjs/auth';
2
+ import { AuthClientResponse, GuardContract } from '@adonisjs/auth/types';
3
+ import type { HttpContext } from '@adonisjs/core/http';
4
+ /**
5
+ * The bridge between the User provider and the
6
+ * Guard
7
+ */
8
+ export type JwtGuardUser<RealUser> = {
9
+ /**
10
+ * Returns the unique ID of the user
11
+ */
12
+ getId(): string | number | BigInt;
13
+ /**
14
+ * Returns the original user object
15
+ */
16
+ getOriginal(): RealUser;
17
+ };
18
+ /**
19
+ * The interface for the UserProvider accepted by the
20
+ * JWT guard.
21
+ */
22
+ export interface JwtUserProviderContract<RealUser> {
23
+ /**
24
+ * A property the guard implementation can use to infer
25
+ * the data type of the actual user (aka RealUser)
26
+ */
27
+ [symbols.PROVIDER_REAL_USER]: RealUser;
28
+ /**
29
+ * Create a user object that acts as an adapter between
30
+ * the guard and real user value.
31
+ */
32
+ createUserForGuard(user: RealUser): Promise<JwtGuardUser<RealUser>>;
33
+ /**
34
+ * Find a user by their id.
35
+ */
36
+ findById(identifier: string | number | BigInt): Promise<JwtGuardUser<RealUser> | null>;
37
+ }
38
+ export type JwtGuardOptions = {
39
+ secret: string;
40
+ expiresIn?: number | string;
41
+ };
42
+ export declare class JwtGuard<UserProvider extends JwtUserProviderContract<unknown>> implements GuardContract<UserProvider[typeof symbols.PROVIDER_REAL_USER]> {
43
+ #private;
44
+ constructor(ctx: HttpContext, userProvider: UserProvider, option: JwtGuardOptions);
45
+ /**
46
+ * A list of events and their types emitted by
47
+ * the guard.
48
+ */
49
+ [symbols.GUARD_KNOWN_EVENTS]: {};
50
+ /**
51
+ * A unique name for the guard driver
52
+ */
53
+ driverName: 'jwt';
54
+ /**
55
+ * A flag to know if the authentication was an attempt
56
+ * during the current HTTP request
57
+ */
58
+ authenticationAttempted: boolean;
59
+ /**
60
+ * A boolean to know if the current request has
61
+ * been authenticated
62
+ */
63
+ isAuthenticated: boolean;
64
+ /**
65
+ * Reference to the currently authenticated user
66
+ */
67
+ user?: UserProvider[typeof symbols.PROVIDER_REAL_USER];
68
+ /**
69
+ * Generate a JWT token for a given user.
70
+ */
71
+ generate(user: UserProvider[typeof symbols.PROVIDER_REAL_USER]): Promise<{
72
+ type: string;
73
+ token: string;
74
+ expiresIn: string | number | undefined;
75
+ }>;
76
+ /**
77
+ * Authenticate the current HTTP request and return
78
+ * the user instance if there is a valid JWT token
79
+ * or throw an exception
80
+ */
81
+ authenticate(): Promise<UserProvider[typeof symbols.PROVIDER_REAL_USER]>;
82
+ /**
83
+ * Same as authenticate, but does not throw an exception
84
+ */
85
+ check(): Promise<boolean>;
86
+ /**
87
+ * Returns the authenticated user or throws an error
88
+ */
89
+ getUserOrFail(): UserProvider[typeof symbols.PROVIDER_REAL_USER];
90
+ /**
91
+ * This method is called by Japa during testing when "loginAs"
92
+ * method is used to login the user.
93
+ */
94
+ authenticateAsClient(user: UserProvider[typeof symbols.PROVIDER_REAL_USER]): Promise<AuthClientResponse>;
95
+ }
@@ -0,0 +1,132 @@
1
+ import { symbols, errors } from '@adonisjs/auth';
2
+ import jwt from 'jsonwebtoken';
3
+ export class JwtGuard {
4
+ #ctx;
5
+ #userProvider;
6
+ #options;
7
+ constructor(ctx, userProvider, option) {
8
+ this.#ctx = ctx;
9
+ this.#userProvider = userProvider;
10
+ this.#options = option;
11
+ }
12
+ /**
13
+ * A unique name for the guard driver
14
+ */
15
+ driverName = 'jwt';
16
+ /**
17
+ * A flag to know if the authentication was an attempt
18
+ * during the current HTTP request
19
+ */
20
+ authenticationAttempted = false;
21
+ /**
22
+ * A boolean to know if the current request has
23
+ * been authenticated
24
+ */
25
+ isAuthenticated = false;
26
+ /**
27
+ * Reference to the currently authenticated user
28
+ */
29
+ user;
30
+ /**
31
+ * Generate a JWT token for a given user.
32
+ */
33
+ async generate(user) {
34
+ const providerUser = await this.#userProvider.createUserForGuard(user);
35
+ const token = jwt.sign({ userId: providerUser.getId() }, this.#options.secret, {
36
+ expiresIn: this.#options.expiresIn,
37
+ });
38
+ return {
39
+ type: 'bearer',
40
+ token: token,
41
+ expiresIn: this.#options.expiresIn,
42
+ };
43
+ }
44
+ /**
45
+ * Authenticate the current HTTP request and return
46
+ * the user instance if there is a valid JWT token
47
+ * or throw an exception
48
+ */
49
+ async authenticate() {
50
+ /**
51
+ * Avoid re-authentication when it has been done already
52
+ * for the given request
53
+ */
54
+ if (this.authenticationAttempted) {
55
+ return this.getUserOrFail();
56
+ }
57
+ this.authenticationAttempted = true;
58
+ /**
59
+ * Ensure the auth header exists
60
+ */
61
+ const authHeader = this.#ctx.request.header('authorization');
62
+ if (!authHeader) {
63
+ throw new errors.E_UNAUTHORIZED_ACCESS('Unauthorized access', {
64
+ guardDriverName: this.driverName,
65
+ });
66
+ }
67
+ /**
68
+ * Split the header value and read the token from it
69
+ */
70
+ const [, token] = authHeader.split('Bearer ');
71
+ if (!token) {
72
+ throw new errors.E_UNAUTHORIZED_ACCESS('Unauthorized access', {
73
+ guardDriverName: this.driverName,
74
+ });
75
+ }
76
+ /**
77
+ * Verify token
78
+ */
79
+ const payload = jwt.verify(token, this.#options.secret);
80
+ if (typeof payload !== 'object' || !('userId' in payload)) {
81
+ throw new errors.E_UNAUTHORIZED_ACCESS('Unauthorized access', {
82
+ guardDriverName: this.driverName,
83
+ });
84
+ }
85
+ /**
86
+ * Fetch the user by user ID and save a reference to it
87
+ */
88
+ const providerUser = await this.#userProvider.findById(payload.userId);
89
+ if (!providerUser) {
90
+ throw new errors.E_UNAUTHORIZED_ACCESS('Unauthorized access', {
91
+ guardDriverName: this.driverName,
92
+ });
93
+ }
94
+ this.user = providerUser.getOriginal();
95
+ return this.getUserOrFail();
96
+ }
97
+ /**
98
+ * Same as authenticate, but does not throw an exception
99
+ */
100
+ async check() {
101
+ try {
102
+ await this.authenticate();
103
+ return true;
104
+ }
105
+ catch {
106
+ return false;
107
+ }
108
+ }
109
+ /**
110
+ * Returns the authenticated user or throws an error
111
+ */
112
+ getUserOrFail() {
113
+ if (!this.user) {
114
+ throw new errors.E_UNAUTHORIZED_ACCESS('Unauthorized access', {
115
+ guardDriverName: this.driverName,
116
+ });
117
+ }
118
+ return this.user;
119
+ }
120
+ /**
121
+ * This method is called by Japa during testing when "loginAs"
122
+ * method is used to login the user.
123
+ */
124
+ async authenticateAsClient(user) {
125
+ const token = await this.generate(user);
126
+ return {
127
+ headers: {
128
+ authorization: `Bearer ${token.token}`,
129
+ },
130
+ };
131
+ }
132
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Path to the root directory where the stubs are stored. We use
3
+ * this path within commands and the configure hook
4
+ */
5
+ export declare const stubsRoot: string;
@@ -0,0 +1,7 @@
1
+ import { dirname } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ /**
4
+ * Path to the root directory where the stubs are stored. We use
5
+ * this path within commands and the configure hook
6
+ */
7
+ export const stubsRoot = dirname(fileURLToPath(import.meta.url));
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "@maximemrf/adonisjs-jwt",
3
+ "description": "",
4
+ "version": "0.0.1",
5
+ "engines": {
6
+ "node": ">=20.6.0"
7
+ },
8
+ "type": "module",
9
+ "files": [
10
+ "build/src",
11
+ "build/providers",
12
+ "build/stubs",
13
+ "build/index.d.ts",
14
+ "build/index.js"
15
+ ],
16
+ "exports": {
17
+ ".": "./build/index.js",
18
+ "./types": "./build/src/types.js"
19
+ },
20
+ "scripts": {
21
+ "clean": "del-cli build",
22
+ "copy:templates": "copyfiles \"stubs/**/*.stub\" build",
23
+ "typecheck": "tsc --noEmit",
24
+ "lint": "eslint . --ext=.ts",
25
+ "format": "prettier --write .",
26
+ "quick:test": "node --import=./tsnode.esm.js --enable-source-maps bin/test.ts",
27
+ "pretest": "npm run lint",
28
+ "test": "c8 npm run quick:test",
29
+ "prebuild": "npm run lint && npm run clean",
30
+ "build": "tsc",
31
+ "postbuild": "npm run copy:templates",
32
+ "release": "np",
33
+ "version": "npm run build",
34
+ "prepublishOnly": "npm run build"
35
+ },
36
+ "keywords": [],
37
+ "author": "",
38
+ "license": "MIT",
39
+ "devDependencies": {
40
+ "@adonisjs/assembler": "^7.2.3",
41
+ "@adonisjs/auth": "^9.1.1",
42
+ "@adonisjs/core": "^6.3.1",
43
+ "@adonisjs/eslint-config": "^1.3.0",
44
+ "@adonisjs/lucid": "^20.4.0",
45
+ "@adonisjs/prettier-config": "^1.3.0",
46
+ "@adonisjs/tsconfig": "^1.3.0",
47
+ "@japa/assert": "^2.1.0",
48
+ "@japa/runner": "^3.1.1",
49
+ "@swc/core": "^1.4.6",
50
+ "@types/node": "^20.11.25",
51
+ "c8": "^9.1.0",
52
+ "copyfiles": "^2.4.1",
53
+ "del-cli": "^5.1.0",
54
+ "eslint": "^8.57.0",
55
+ "np": "^10.0.0",
56
+ "prettier": "^3.2.5",
57
+ "ts-node": "^10.9.2",
58
+ "typescript": "^5.4.2"
59
+ },
60
+ "peerDependencies": {
61
+ "@adonisjs/core": "^6.2.0"
62
+ },
63
+ "publishConfig": {
64
+ "access": "public",
65
+ "tag": "latest"
66
+ },
67
+ "np": {
68
+ "message": "chore(release): %s",
69
+ "tag": "latest",
70
+ "branch": "main",
71
+ "anyBranch": false
72
+ },
73
+ "c8": {
74
+ "reporter": [
75
+ "text",
76
+ "html"
77
+ ],
78
+ "exclude": [
79
+ "tests/**"
80
+ ]
81
+ },
82
+ "eslintConfig": {
83
+ "extends": "@adonisjs/eslint-config/package"
84
+ },
85
+ "prettier": "@adonisjs/prettier-config",
86
+ "dependencies": {
87
+ "@types/jsonwebtoken": "^9.0.6",
88
+ "jsonwebtoken": "^9.0.2"
89
+ }
90
+ }