@skillstew/common 1.0.0 → 1.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/package.json +8 -2
- package/src/errors/AppError.ts +20 -0
- package/src/errors/JwtErrors.ts +47 -0
- package/src/errors/UnauthenticatedError.ts +10 -0
- package/src/errors/codes/JwtErrorCodes.ts +8 -0
- package/src/jwt-utils/JwtHelper.ts +74 -0
- package/src/middlewares/authMiddleware.ts +39 -0
- package/src/types/UserRoles.ts +2 -0
- package/src/types/express/index.d.ts +16 -0
- package/tsconfig.json +9 -7
package/package.json
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skillstew/common",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"main": "index.js",
|
|
5
5
|
"scripts": {},
|
|
6
6
|
"keywords": [],
|
|
7
7
|
"author": "",
|
|
8
8
|
"license": "ISC",
|
|
9
|
-
"description": ""
|
|
9
|
+
"description": "",
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@types/express": "^5.0.3",
|
|
12
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
13
|
+
"express": "^5.1.0",
|
|
14
|
+
"jsonwebtoken": "^9.0.2"
|
|
15
|
+
}
|
|
10
16
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export abstract class AppError extends Error {
|
|
2
|
+
public readonly name: string;
|
|
3
|
+
constructor(
|
|
4
|
+
public readonly message: string,
|
|
5
|
+
public readonly code: string,
|
|
6
|
+
public readonly context?: Record<string, unknown>,
|
|
7
|
+
) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = this.constructor.name;
|
|
10
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
abstract toJSON(): object;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export abstract class DomainError extends AppError {}
|
|
17
|
+
|
|
18
|
+
export abstract class InfrastructureError extends AppError {}
|
|
19
|
+
|
|
20
|
+
export abstract class ApplicationError extends AppError {}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { InfrastructureError } from "./AppError";
|
|
2
|
+
import { JwtErrorCodes } from "./codes/JwtErrorCodes";
|
|
3
|
+
|
|
4
|
+
export class JwtError extends InfrastructureError {
|
|
5
|
+
constructor(code: keyof typeof JwtErrorCodes) {
|
|
6
|
+
super(JwtErrorCodes[code], code);
|
|
7
|
+
}
|
|
8
|
+
toJSON(): object {
|
|
9
|
+
return { error: this.name, message: this.message, code: this.code };
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class EmailVerificationJwtVerifyError extends JwtError {
|
|
14
|
+
constructor() {
|
|
15
|
+
super("EMAIL_VERIFICATION_JWT_VERIFY_ERROR");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class RefreshTokenVerifyError extends JwtError {
|
|
20
|
+
constructor() {
|
|
21
|
+
super("REFRESH_TOKEN_VERIFY_ERROR");
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class AccessTokenVerifyError extends JwtError {
|
|
26
|
+
constructor() {
|
|
27
|
+
super("ACCESS_TOKEN_VERIFY_ERROR");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class InvalidTokenError extends JwtError {
|
|
32
|
+
constructor() {
|
|
33
|
+
super("INVALID_TOKEN_ERROR");
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class InvalidTokenRoleError extends JwtError {
|
|
38
|
+
constructor() {
|
|
39
|
+
super("INVALID_TOKEN_ROLE_ERROR");
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class TokenRoleMismatchError extends JwtError {
|
|
44
|
+
constructor() {
|
|
45
|
+
super("TOKEN_ROLE_MISMATCH_ERROR");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { ApplicationError } from "./AppError";
|
|
2
|
+
|
|
3
|
+
export class UnauthenticatedError extends ApplicationError {
|
|
4
|
+
constructor() {
|
|
5
|
+
super("Unauthenticated", "USER_UNAUTHENTICATED");
|
|
6
|
+
}
|
|
7
|
+
toJSON(): object {
|
|
8
|
+
return { name: this.name, message: this.message };
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export enum JwtErrorCodes {
|
|
2
|
+
EMAIL_VERIFICATION_JWT_VERIFY_ERROR = "Invalid email verification jwt",
|
|
3
|
+
REFRESH_TOKEN_VERIFY_ERROR = "Invalid refresh token",
|
|
4
|
+
ACCESS_TOKEN_VERIFY_ERROR = "Invalid access token",
|
|
5
|
+
INVALID_TOKEN_ERROR = "Invalid token",
|
|
6
|
+
INVALID_TOKEN_ROLE_ERROR = "Invalid role identifier",
|
|
7
|
+
TOKEN_ROLE_MISMATCH_ERROR = "Role mismatch between payload and header",
|
|
8
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import jwt, { JwtHeader } from "jsonwebtoken";
|
|
2
|
+
import { UserRoles } from "../types/UserRoles";
|
|
3
|
+
import {
|
|
4
|
+
AccessTokenVerifyError,
|
|
5
|
+
InvalidTokenError,
|
|
6
|
+
InvalidTokenRoleError,
|
|
7
|
+
TokenRoleMismatchError,
|
|
8
|
+
} from "../errors/JwtErrors";
|
|
9
|
+
|
|
10
|
+
function isUserRole(role: string): role is UserRoles {
|
|
11
|
+
return ["ADMIN", "EXPERT", "USER"].includes(role);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type tokenBody =
|
|
15
|
+
| {
|
|
16
|
+
userId: string;
|
|
17
|
+
email: string;
|
|
18
|
+
role: Exclude<UserRoles, "ADMIN">;
|
|
19
|
+
}
|
|
20
|
+
| {
|
|
21
|
+
userId: string;
|
|
22
|
+
username: string;
|
|
23
|
+
role: "ADMIN";
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export type JWTPayload = tokenBody & {
|
|
27
|
+
iat: number;
|
|
28
|
+
exp: number;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export class JwtHelper {
|
|
32
|
+
private _AccessSecrets: Record<UserRoles, string>;
|
|
33
|
+
constructor({
|
|
34
|
+
userAccessTokenSecret,
|
|
35
|
+
expertAccessTokenSecret,
|
|
36
|
+
adminAccessTokenSecret,
|
|
37
|
+
}: {
|
|
38
|
+
userAccessTokenSecret: string;
|
|
39
|
+
expertAccessTokenSecret: string;
|
|
40
|
+
adminAccessTokenSecret: string;
|
|
41
|
+
}) {
|
|
42
|
+
this._AccessSecrets = {
|
|
43
|
+
USER: userAccessTokenSecret,
|
|
44
|
+
ADMIN: adminAccessTokenSecret,
|
|
45
|
+
EXPERT: expertAccessTokenSecret,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
verifyAccessToken = (jwtToken: string) => {
|
|
50
|
+
const decoded = jwt.decode(jwtToken, { complete: true }) as any;
|
|
51
|
+
if (!decoded || !decoded.header) {
|
|
52
|
+
throw new InvalidTokenError();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const header = decoded.header as JwtHeader & { kid?: string };
|
|
56
|
+
const role = header.kid as UserRoles | undefined;
|
|
57
|
+
|
|
58
|
+
if (!role || !isUserRole(role)) {
|
|
59
|
+
throw new InvalidTokenRoleError();
|
|
60
|
+
}
|
|
61
|
+
let payload: JWTPayload;
|
|
62
|
+
try {
|
|
63
|
+
payload = <JWTPayload>jwt.verify(jwtToken, this._AccessSecrets[role]);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
throw new AccessTokenVerifyError();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (!(role === payload.role)) {
|
|
69
|
+
throw new TokenRoleMismatchError();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return payload;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { RequestHandler } from "express";
|
|
2
|
+
import { UnauthenticatedError } from "../errors/UnauthenticatedError";
|
|
3
|
+
import { JwtHelper } from "../jwt-utils/JwtHelper";
|
|
4
|
+
|
|
5
|
+
export class AuthMiddleware {
|
|
6
|
+
private _jwtHelper: JwtHelper;
|
|
7
|
+
|
|
8
|
+
constructor(
|
|
9
|
+
userAccessTokenSecret: string,
|
|
10
|
+
expertAccessTokenSecret: string,
|
|
11
|
+
adminAccessTokenSecret: string,
|
|
12
|
+
) {
|
|
13
|
+
this._jwtHelper = new JwtHelper({
|
|
14
|
+
userAccessTokenSecret,
|
|
15
|
+
expertAccessTokenSecret,
|
|
16
|
+
adminAccessTokenSecret,
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
verify: RequestHandler = (req, _res, next) => {
|
|
21
|
+
try {
|
|
22
|
+
const token = req.headers["authorization"]?.split(" ")[1];
|
|
23
|
+
if (!token) {
|
|
24
|
+
throw new UnauthenticatedError();
|
|
25
|
+
}
|
|
26
|
+
const payload = this._jwtHelper.verifyAccessToken(token);
|
|
27
|
+
req.user = {
|
|
28
|
+
id: payload.userId,
|
|
29
|
+
...(payload.role === "ADMIN"
|
|
30
|
+
? { userame: payload.username }
|
|
31
|
+
: { email: payload.email }),
|
|
32
|
+
role: payload.role,
|
|
33
|
+
};
|
|
34
|
+
next();
|
|
35
|
+
} catch (err) {
|
|
36
|
+
next(err);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { RequestUser } from "../../3-presentation/types/RequestType";
|
|
2
|
+
import { UserRoles } from "../../0-domain/entities/UserRoles";
|
|
3
|
+
|
|
4
|
+
export interface RequestUser {
|
|
5
|
+
id: string | number;
|
|
6
|
+
email: string;
|
|
7
|
+
role: UserRoles;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
declare global {
|
|
11
|
+
namespace Express {
|
|
12
|
+
interface Request {
|
|
13
|
+
user: RequestUser;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
package/tsconfig.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
12
12
|
|
|
13
13
|
/* Language and Environment */
|
|
14
|
-
"target": "es2016"
|
|
14
|
+
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
|
15
15
|
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
16
16
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
|
17
17
|
// "libReplacement": true, /* Enable lib replacement. */
|
|
@@ -26,13 +26,15 @@
|
|
|
26
26
|
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
27
27
|
|
|
28
28
|
/* Modules */
|
|
29
|
-
"module": "commonjs"
|
|
29
|
+
"module": "commonjs" /* Specify what module code is generated. */,
|
|
30
30
|
// "rootDir": "./", /* Specify the root folder within your source files. */
|
|
31
31
|
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
|
32
32
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
33
33
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
34
34
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
35
|
-
|
|
35
|
+
"typeRoots": [
|
|
36
|
+
"./src/types"
|
|
37
|
+
] /* Specify multiple folders that act like './node_modules/@types'. */,
|
|
36
38
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
37
39
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
38
40
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
@@ -80,12 +82,12 @@
|
|
|
80
82
|
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
|
|
81
83
|
// "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
|
|
82
84
|
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
83
|
-
"esModuleInterop": true
|
|
85
|
+
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
|
|
84
86
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
85
|
-
"forceConsistentCasingInFileNames": true
|
|
87
|
+
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
|
|
86
88
|
|
|
87
89
|
/* Type Checking */
|
|
88
|
-
"strict": true
|
|
90
|
+
"strict": true /* Enable all strict type-checking options. */,
|
|
89
91
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
90
92
|
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
91
93
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
@@ -108,6 +110,6 @@
|
|
|
108
110
|
|
|
109
111
|
/* Completeness */
|
|
110
112
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
111
|
-
"skipLibCheck": true
|
|
113
|
+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
112
114
|
}
|
|
113
115
|
}
|