@mingjue8888/express-plus 1.2.1 → 1.2.3

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.
@@ -1,15 +1,10 @@
1
- import _ from "lodash";
1
+ import hasPermissionsByRBAC0 from "@mingjue8888/base-dependencies/rbac0/has-permissions";
2
2
  import asyncMiddleware, {Middleware} from "./async-middleware";
3
3
  import PermissionDeniedResponseError from "./permission-denied-response-error";
4
4
 
5
-
6
5
  export default function hasPermissions(permissions: string[]): Middleware {
7
6
  return asyncMiddleware(async function (req, _res) {
8
- const userPermissions = req.user?.roles
9
- .map(r => r.permissions)
10
- .flat();
11
-
12
- const noPermission = _.intersection(permissions, userPermissions).length === 0;
13
- if (noPermission) throw new PermissionDeniedResponseError("PermissionDeniedError", "You do not have permission");
7
+ if (!hasPermissionsByRBAC0(req.user, permissions))
8
+ throw new PermissionDeniedResponseError("PermissionDeniedError", "You do not have permission");
14
9
  });
15
10
  }
package/has-roles.ts CHANGED
@@ -1,12 +1,10 @@
1
- import _ from "lodash";
1
+ import hasRolesByRBAC0 from "@mingjue8888/base-dependencies/rbac0/has-roles";
2
2
  import asyncMiddleware, {Middleware} from "./async-middleware";
3
3
  import PermissionDeniedResponseError from "./permission-denied-response-error";
4
4
 
5
-
6
5
  export default function hasRoles(roles: string[]): Middleware {
7
6
  return asyncMiddleware(async function (req, _res) {
8
- const userRoles = req.user?.roles.map(r => r.name);
9
- const noRole = _.intersection(roles, userRoles).length === 0;
10
- if (noRole) throw new PermissionDeniedResponseError("NotQualifiedError", "You do not meet the qualifications");
7
+ if (!hasRolesByRBAC0(req.user, roles))
8
+ throw new PermissionDeniedResponseError("NotQualifiedError", "You do not meet the qualifications");
11
9
  });
12
10
  }
package/index.ts CHANGED
@@ -1,19 +1,17 @@
1
1
  import "dotenv/config";
2
2
  import logger from "@mingjue8888/base-dependencies/logger";
3
- import {oneDay, oneSecond} from "@mingjue8888/base-dependencies/ubiquitous-language";
3
+ import {AbstractAccount, oneDay, oneSecond} from "@mingjue8888/base-dependencies/ubiquitous-language";
4
4
  import compression from "compression";
5
5
  import cors from "cors";
6
6
  import express from "express";
7
7
  import rateLimit from "express-rate-limit";
8
8
  import Joi from "joi";
9
- import jwt from "jsonwebtoken";
9
+ import jwt, {JwtPayload} from "jsonwebtoken";
10
10
  import _ from "lodash";
11
11
  import morgan from "morgan";
12
12
  import passport from "passport";
13
13
  import {ExtractJwt, Strategy, StrategyOptions} from "passport-jwt";
14
14
  import {Middleware} from "./async-middleware";
15
- import LoginAccount from "./login-account";
16
- import LoginToken from "./login-token";
17
15
  import PermissionDeniedResponseError from "./permission-denied-response-error";
18
16
  import ResponseError from "./response-error";
19
17
  import Router from "./router";
@@ -25,6 +23,9 @@ type DeepArray<T> =
25
23
  | T[]
26
24
  | DeepArray<T>[];
27
25
 
26
+ type JWTPayload =
27
+ Required<Pick<JwtPayload, "exp" | "sub" | "iat">>;
28
+
28
29
  type ResponseErrorConverter =
29
30
  (err: Error) => ResponseError | void;
30
31
 
@@ -68,7 +69,7 @@ function errorHandler(
68
69
 
69
70
  declare global {
70
71
  namespace Express {
71
- interface User extends LoginAccount {}
72
+ interface User extends AbstractAccount {}
72
73
  interface Response {
73
74
  signToken: (sub: string) => void;
74
75
  body?: any;
@@ -86,7 +87,7 @@ interface EnvOptions {
86
87
  }
87
88
 
88
89
  interface StartupOptions extends EnvOptions {
89
- authenticate?: <T extends LoginAccount>(token: LoginToken) => Promise<T>;
90
+ authenticate?: <T extends AbstractAccount>(token: JWTPayload) => Promise<T>;
90
91
  middlewares?: Middleware[];
91
92
  onError?: ResponseErrorConverter;
92
93
  }
@@ -139,7 +140,7 @@ export default function app(routers: DeepArray<Router>, opt?: StartupOptions) {
139
140
  ignoreExpiration: true,
140
141
  }
141
142
 
142
- const strategy = new Strategy(jwtStrategy, function (payload: LoginToken, next) {
143
+ const strategy = new Strategy(jwtStrategy, function (payload: JWTPayload, next) {
143
144
  if (!opt?.authenticate) {
144
145
  next(new ServerErrorResponseError("AuthenticationError", "Missing authentication logic"), false);
145
146
  return;
package/package.json CHANGED
@@ -1,10 +1,18 @@
1
1
  {
2
2
  "name": "@mingjue8888/express-plus",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
4
4
  "repository": "github:mingjue8888/express-plus",
5
+ "keywords": [
6
+ "web",
7
+ "app",
8
+ "api",
9
+ "rest",
10
+ "restful",
11
+ "express",
12
+ "router"
13
+ ],
5
14
  "dependencies": {
6
- "@mingjue8888/base-dependencies": "^1.2.0",
7
- "bcrypt": "^6.0.0",
15
+ "@mingjue8888/base-dependencies": "^1.5.2",
8
16
  "compression": "^1.8.2",
9
17
  "cors": "^2.8.6",
10
18
  "express-rate-limit": "^8.7.4",
@@ -14,7 +22,6 @@
14
22
  "passport-jwt": "^4.0.1"
15
23
  },
16
24
  "devDependencies": {
17
- "@types/bcrypt": "^6.0.0",
18
25
  "@types/compression": "^1.8.1",
19
26
  "@types/cors": "^2.8.19",
20
27
  "@types/express": "^5.0.6",
package/README.md DELETED
@@ -1,150 +0,0 @@
1
- # Usage
2
-
3
- ## Define User
4
-
5
- ```typescript
6
- import LoginAccount from "@mingjue8888/express-plus/login-account";
7
-
8
- export interface UserAccount extends LoginAccount {}
9
-
10
- declare global {
11
- namespace Express {
12
- interface User extends UserAccount {}
13
- }
14
- }
15
- ```
16
-
17
- ## Define Error
18
-
19
- ```typescript
20
- export class NotFoundUserError extends Error {}
21
- ```
22
-
23
- ## Write Router
24
-
25
- ```typescript
26
- import Joi from "joi";
27
- import asyncMiddleware from "@mingjue8888/express-plus/async-middleware";
28
- import hasLogin from "@mingjue8888/express-plus/has-login";
29
- import Router from "@mingjue8888/express-plus/router";
30
- import validBody from "@mingjue8888/express-plus/valid-body";
31
- import validParam from "@mingjue8888/express-plus/valid-param";
32
- import validSend from "@mingjue8888/express-plus/valid-send";
33
-
34
- // File ./routers/routerA.ts
35
- const login: Router = {
36
- method: "POST",
37
- path: "/login",
38
- middlewares: [
39
- validBody({
40
- username: Joi.string()
41
- .required(),
42
-
43
- password: Joi.string()
44
- .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,}$/)
45
- .required()
46
- }),
47
- asyncMiddleware(async function (req, res) {
48
- const username = req.valid.body.username as string;
49
- const password = req.valid.body.password as string;
50
- const id = "UUID";
51
- res.signToken(id);
52
- }),
53
- validSend({
54
- accessToken: Joi.string()
55
- .required(),
56
- }),
57
- ],
58
- }
59
-
60
- export default [
61
- login,
62
- ];
63
-
64
- // File ./routers/routerB.ts
65
- const findUser: Router = {
66
- method: "GET",
67
- path: "/users/:userId",
68
- middlewares: [
69
- hasLogin,
70
- validParam({
71
- userId: Joi.string()
72
- .required(),
73
- }),
74
- asyncMiddleware(async function (req, res) {
75
- throw new NotFoundUserError();
76
- }),
77
- validSend({
78
- id: Joi.string()
79
- .required(),
80
-
81
- name: Joi.string()
82
- .required(),
83
- }),
84
- ],
85
- }
86
-
87
- const findUserPosts: Router = {
88
- method: "GET",
89
- path: "/users/:userId/posts",
90
- middlewares: [
91
- hasLogin,
92
- validParam({
93
- userId: Joi.string()
94
- .required(),
95
- }),
96
- asyncMiddleware(async function (req, res) {
97
- res.body = {
98
- posts: []
99
- }
100
- }),
101
- validSend({
102
- posts: Joi.array().items(Joi.object().keys({
103
- id: Joi.string().required(),
104
- content: Joi.string().required().default(""),
105
- }))
106
- })
107
- ],
108
- }
109
-
110
- export default [
111
- findUser,
112
- findUserPosts,
113
- ];
114
- ```
115
-
116
- ## Start app
117
-
118
- ```typescript
119
- import app from "@mingjue8888/express-plus";
120
- import routerA from "./routers/routerA";
121
- import routerB from "./routers/routerB";
122
- import {NotFoundUserError} from "./errors";
123
- import NotFoundResponseError from "@mingjue8888/express-plus/not-found-response-error";
124
-
125
- const routers = [
126
- routerA,
127
- routerB,
128
- ];
129
-
130
- app(routers, {
131
- APP_PORT: 3000,
132
-
133
- async authenticate<UserAccount>(token: LoginToken) {
134
- return {
135
- id: token.sub,
136
- isLocked: false,
137
- isSuspended: false,
138
- isBanned: false,
139
- roles: [],
140
- } as UserAccount;
141
- },
142
-
143
- // Covert Error to ResponseError
144
- onError(err: Error) {
145
- if (err instanceof NotFoundUserError) {
146
- return new NotFoundResponseError(err.constructor.name, "Not found user");
147
- }
148
- }
149
- });
150
- ```
package/id-generator.ts DELETED
@@ -1,5 +0,0 @@
1
- import * as crypto from "node:crypto";
2
-
3
- export default function idgen(): string {
4
- return crypto.randomUUID().toString().replaceAll("-", "");
5
- }
package/login-account.ts DELETED
@@ -1,11 +0,0 @@
1
- import RBAC0 from "./rbac0";
2
-
3
- export default interface LoginAccount extends RBAC0 {
4
- id: string;
5
- isLocked: boolean;
6
- isSuspended: boolean;
7
- isBanned: boolean;
8
- lockedReason?: string;
9
- suspendedReason?: string;
10
- bannedReason?: string;
11
- }
package/login-token.ts DELETED
@@ -1,7 +0,0 @@
1
- import {JwtPayload} from "jsonwebtoken";
2
-
3
- export default interface LoginToken extends JwtPayload {
4
- sub: string;
5
- iat: number;
6
- exp: number;
7
- }
@@ -1,9 +0,0 @@
1
- import bcrypt from "bcrypt";
2
-
3
- export function encode(password: string): string {
4
- return bcrypt.hashSync(password, bcrypt.genSaltSync());
5
- }
6
-
7
- export function check(password: string, encoded: string): boolean {
8
- return bcrypt.compareSync(password, encoded);
9
- }
package/rbac0.ts DELETED
@@ -1,9 +0,0 @@
1
-
2
- interface Role {
3
- name: string;
4
- permissions: string[];
5
- }
6
-
7
- export default interface RBAC0 {
8
- roles: Role[];
9
- }