@miqro/core 4.0.1 → 5.0.2

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 (220) hide show
  1. package/build/app.d.ts +15 -11
  2. package/build/app.js +22 -20
  3. package/build/app.js.map +1 -1
  4. package/build/common.d.ts +106 -0
  5. package/build/common.js +477 -0
  6. package/build/common.js.map +1 -0
  7. package/build/lib.d.ts +7 -38
  8. package/build/lib.js +6 -33
  9. package/build/lib.js.map +1 -1
  10. package/build/middleware/body-parser.d.ts +78 -0
  11. package/build/middleware/body-parser.js +552 -0
  12. package/build/middleware/body-parser.js.map +1 -0
  13. package/build/middleware/router.d.ts +114 -0
  14. package/build/middleware/router.js +704 -0
  15. package/build/middleware/router.js.map +1 -0
  16. package/build/middleware/session.d.ts +27 -3
  17. package/build/middleware/session.js +238 -18
  18. package/build/middleware/session.js.map +1 -1
  19. package/build/types.d.ts +309 -0
  20. package/build/types.js +455 -0
  21. package/build/types.js.map +1 -0
  22. package/build/{websocket/cluster.d.ts → websocket.d.ts} +13 -2
  23. package/build/websocket.js +316 -0
  24. package/build/websocket.js.map +1 -0
  25. package/package.json +7 -7
  26. package/src/app.ts +36 -32
  27. package/src/common.ts +528 -0
  28. package/src/lib.ts +63 -101
  29. package/src/middleware/body-parser.ts +597 -0
  30. package/src/middleware/router.ts +840 -0
  31. package/src/middleware/session.ts +249 -19
  32. package/src/types.ts +785 -0
  33. package/src/websocket.ts +356 -0
  34. package/build/api-router.d.ts +0 -34
  35. package/build/api-router.js +0 -48
  36. package/build/api-router.js.map +0 -1
  37. package/build/app-utils.d.ts +0 -13
  38. package/build/app-utils.js +0 -78
  39. package/build/app-utils.js.map +0 -1
  40. package/build/common/api-router-types.d.ts +0 -28
  41. package/build/common/api-router-types.js +0 -24
  42. package/build/common/api-router-types.js.map +0 -1
  43. package/build/common/api-router-utils.d.ts +0 -3
  44. package/build/common/api-router-utils.js +0 -118
  45. package/build/common/api-router-utils.js.map +0 -1
  46. package/build/common/config/config.d.ts +0 -15
  47. package/build/common/config/config.js +0 -38
  48. package/build/common/config/config.js.map +0 -1
  49. package/build/common/config/featuretoggle.d.ts +0 -1
  50. package/build/common/config/featuretoggle.js +0 -6
  51. package/build/common/config/featuretoggle.js.map +0 -1
  52. package/build/common/config/loader.d.ts +0 -13
  53. package/build/common/config/loader.js +0 -64
  54. package/build/common/config/loader.js.map +0 -1
  55. package/build/common/context.d.ts +0 -57
  56. package/build/common/context.js +0 -137
  57. package/build/common/context.js.map +0 -1
  58. package/build/common/error/badrequesterror.d.ts +0 -3
  59. package/build/common/error/badrequesterror.js +0 -7
  60. package/build/common/error/badrequesterror.js.map +0 -1
  61. package/build/common/error/configfilenotfound.d.ts +0 -3
  62. package/build/common/error/configfilenotfound.js +0 -7
  63. package/build/common/error/configfilenotfound.js.map +0 -1
  64. package/build/common/error/forbiddenerror.d.ts +0 -3
  65. package/build/common/error/forbiddenerror.js +0 -7
  66. package/build/common/error/forbiddenerror.js.map +0 -1
  67. package/build/common/error/notfound.d.ts +0 -3
  68. package/build/common/error/notfound.js +0 -7
  69. package/build/common/error/notfound.js.map +0 -1
  70. package/build/common/error/notimplemented.d.ts +0 -3
  71. package/build/common/error/notimplemented.js +0 -7
  72. package/build/common/error/notimplemented.js.map +0 -1
  73. package/build/common/error/unauthorizederror.d.ts +0 -3
  74. package/build/common/error/unauthorizederror.js +0 -7
  75. package/build/common/error/unauthorizederror.js.map +0 -1
  76. package/build/common/logger/constants.d.ts +0 -14
  77. package/build/common/logger/constants.js +0 -22
  78. package/build/common/logger/constants.js.map +0 -1
  79. package/build/common/logger/factory.d.ts +0 -16
  80. package/build/common/logger/factory.js +0 -47
  81. package/build/common/logger/factory.js.map +0 -1
  82. package/build/common/logger/interfaces.d.ts +0 -18
  83. package/build/common/logger/interfaces.js +0 -2
  84. package/build/common/logger/interfaces.js.map +0 -1
  85. package/build/common/logger/logger.d.ts +0 -35
  86. package/build/common/logger/logger.js +0 -95
  87. package/build/common/logger/logger.js.map +0 -1
  88. package/build/common/logger/transport/console.d.ts +0 -5
  89. package/build/common/logger/transport/console.js +0 -37
  90. package/build/common/logger/transport/console.js.map +0 -1
  91. package/build/common/logger/transport/file.d.ts +0 -2
  92. package/build/common/logger/transport/file.js +0 -25
  93. package/build/common/logger/transport/file.js.map +0 -1
  94. package/build/common/parser.d.ts +0 -7
  95. package/build/common/parser.js +0 -44
  96. package/build/common/parser.js.map +0 -1
  97. package/build/common/router-default-logger-factory.d.ts +0 -4
  98. package/build/common/router-default-logger-factory.js +0 -38
  99. package/build/common/router-default-logger-factory.js.map +0 -1
  100. package/build/common/router-handler.d.ts +0 -20
  101. package/build/common/router-handler.js +0 -154
  102. package/build/common/router-handler.js.map +0 -1
  103. package/build/common/router-types.d.ts +0 -63
  104. package/build/common/router-types.js +0 -86
  105. package/build/common/router-types.js.map +0 -1
  106. package/build/common/router-utils.d.ts +0 -3
  107. package/build/common/router-utils.js +0 -46
  108. package/build/common/router-utils.js.map +0 -1
  109. package/build/common/session/common.d.ts +0 -37
  110. package/build/common/session/common.js +0 -2
  111. package/build/common/session/common.js.map +0 -1
  112. package/build/common/session/service.d.ts +0 -26
  113. package/build/common/session/service.js +0 -154
  114. package/build/common/session/service.js.map +0 -1
  115. package/build/common/tokenize-match.d.ts +0 -19
  116. package/build/common/tokenize-match.js +0 -73
  117. package/build/common/tokenize-match.js.map +0 -1
  118. package/build/common/url-utils.d.ts +0 -6
  119. package/build/common/url-utils.js +0 -48
  120. package/build/common/url-utils.js.map +0 -1
  121. package/build/middleware/buffer.d.ts +0 -6
  122. package/build/middleware/buffer.js +0 -78
  123. package/build/middleware/buffer.js.map +0 -1
  124. package/build/middleware/cookie.d.ts +0 -4
  125. package/build/middleware/cookie.js +0 -15
  126. package/build/middleware/cookie.js.map +0 -1
  127. package/build/middleware/cors.d.ts +0 -8
  128. package/build/middleware/cors.js +0 -89
  129. package/build/middleware/cors.js.map +0 -1
  130. package/build/middleware/form.d.ts +0 -6
  131. package/build/middleware/form.js +0 -58
  132. package/build/middleware/form.js.map +0 -1
  133. package/build/middleware/group.d.ts +0 -3
  134. package/build/middleware/group.js +0 -77
  135. package/build/middleware/group.js.map +0 -1
  136. package/build/middleware/json.d.ts +0 -6
  137. package/build/middleware/json.js +0 -55
  138. package/build/middleware/json.js.map +0 -1
  139. package/build/middleware/logger.d.ts +0 -4
  140. package/build/middleware/logger.js +0 -16
  141. package/build/middleware/logger.js.map +0 -1
  142. package/build/middleware/parse.d.ts +0 -14
  143. package/build/middleware/parse.js +0 -88
  144. package/build/middleware/parse.js.map +0 -1
  145. package/build/middleware/result.d.ts +0 -9
  146. package/build/middleware/result.js +0 -62
  147. package/build/middleware/result.js.map +0 -1
  148. package/build/middleware/tag.d.ts +0 -4
  149. package/build/middleware/tag.js +0 -10
  150. package/build/middleware/tag.js.map +0 -1
  151. package/build/middleware/text.d.ts +0 -5
  152. package/build/middleware/text.js +0 -46
  153. package/build/middleware/text.js.map +0 -1
  154. package/build/proxy.d.ts +0 -19
  155. package/build/proxy.js +0 -74
  156. package/build/proxy.js.map +0 -1
  157. package/build/router.d.ts +0 -26
  158. package/build/router.js +0 -116
  159. package/build/router.js.map +0 -1
  160. package/build/static.d.ts +0 -14
  161. package/build/static.js +0 -211
  162. package/build/static.js.map +0 -1
  163. package/build/websocket/cluster.js +0 -114
  164. package/build/websocket/cluster.js.map +0 -1
  165. package/build/websocket/server.d.ts +0 -15
  166. package/build/websocket/server.js +0 -127
  167. package/build/websocket/server.js.map +0 -1
  168. package/build/websocket/types.d.ts +0 -39
  169. package/build/websocket/types.js +0 -2
  170. package/build/websocket/types.js.map +0 -1
  171. package/build/websocket/utils.d.ts +0 -8
  172. package/build/websocket/utils.js +0 -77
  173. package/build/websocket/utils.js.map +0 -1
  174. package/src/api-router.ts +0 -50
  175. package/src/app-utils.ts +0 -82
  176. package/src/common/api-router-types.ts +0 -52
  177. package/src/common/api-router-utils.ts +0 -126
  178. package/src/common/config/config.ts +0 -49
  179. package/src/common/config/featuretoggle.ts +0 -6
  180. package/src/common/config/loader.ts +0 -81
  181. package/src/common/context.ts +0 -192
  182. package/src/common/error/badrequesterror.ts +0 -6
  183. package/src/common/error/configfilenotfound.ts +0 -6
  184. package/src/common/error/forbiddenerror.ts +0 -6
  185. package/src/common/error/notfound.ts +0 -6
  186. package/src/common/error/notimplemented.ts +0 -6
  187. package/src/common/error/unauthorizederror.ts +0 -6
  188. package/src/common/logger/constants.ts +0 -28
  189. package/src/common/logger/factory.ts +0 -53
  190. package/src/common/logger/interfaces.ts +0 -19
  191. package/src/common/logger/logger.ts +0 -136
  192. package/src/common/logger/transport/console.ts +0 -36
  193. package/src/common/logger/transport/file.ts +0 -26
  194. package/src/common/parser.ts +0 -50
  195. package/src/common/router-default-logger-factory.ts +0 -44
  196. package/src/common/router-handler.ts +0 -186
  197. package/src/common/router-types.ts +0 -153
  198. package/src/common/router-utils.ts +0 -47
  199. package/src/common/session/common.ts +0 -40
  200. package/src/common/session/service.ts +0 -175
  201. package/src/common/tokenize-match.ts +0 -98
  202. package/src/common/url-utils.ts +0 -46
  203. package/src/middleware/buffer.ts +0 -82
  204. package/src/middleware/cookie.ts +0 -20
  205. package/src/middleware/cors.ts +0 -98
  206. package/src/middleware/form.ts +0 -61
  207. package/src/middleware/group.ts +0 -74
  208. package/src/middleware/json.ts +0 -57
  209. package/src/middleware/logger.ts +0 -18
  210. package/src/middleware/parse.ts +0 -105
  211. package/src/middleware/result.ts +0 -73
  212. package/src/middleware/tag.ts +0 -15
  213. package/src/middleware/text.ts +0 -47
  214. package/src/proxy.ts +0 -99
  215. package/src/router.ts +0 -140
  216. package/src/static.ts +0 -242
  217. package/src/websocket/cluster.ts +0 -128
  218. package/src/websocket/server.ts +0 -135
  219. package/src/websocket/types.ts +0 -41
  220. package/src/websocket/utils.ts +0 -95
@@ -1,9 +1,9 @@
1
- import { checkEnvVariables } from "../common/config/config.js";
2
- import { Context, Handler } from "../common/context.js";
3
- import { ForbiddenError } from "../common/error/forbiddenerror.js";
4
- import { UnAuthorizedError } from "../common/error/unauthorizederror.js";
5
- import { assertNotUndefined, DEFAULT_PARSER } from "../common/parser.js";
6
- import { SessionHandlerOptions } from "../common/session/common.js";
1
+ import { assertNotUndefined, DEFAULT_PARSER } from "./body-parser.js";
2
+ import { RequestOptions, RequestResponse, request } from "@miqro/request";
3
+ import { Schema } from "@miqro/parser";
4
+ import { parse as cookieParse } from "cookie";
5
+ import { BadRequestError, checkEnvVariables, ForbiddenError, UnAuthorizedError } from "../common.js";
6
+ import { GroupPolicy, GroupPolicySchema, Handler, NoTokenSession, Request, Response, Session, SessionHandlerOptions } from "../types.js";
7
7
 
8
8
  const DEFAULT_TOKEN_LOCATION = "header";
9
9
  const DEFAULT_TOKEN_HEADER = "Authorization";
@@ -14,7 +14,170 @@ const DEFAULT_TOKEN_SET_COOKIE_SECURE = "true";
14
14
  const DEFAULT_TOKEN_SET_COOKIE_PATH = "/";
15
15
  const DEFAULT_TOKEN_SET_COOKIE_SAME_SITE = "strict";
16
16
 
17
- export const SessionHandler = (config: SessionHandlerOptions): Handler<void> => {
17
+ export interface VerifyTokenService {
18
+ verify(args: { token: string; req: Request }): Promise<Session | null>;
19
+ }
20
+
21
+ export interface VerifyEndpointServiceOptions {
22
+ url: string;
23
+ method: string;
24
+ tokenLocation: "header" | "query" | "cookie";
25
+ tokenLocationName: string | ((req: Request) => Promise<string>);
26
+ }
27
+
28
+ const NoTokenSessionSchema: Schema<NoTokenSession> = {
29
+ type: "object",
30
+ properties: {
31
+ username: "string",
32
+ account: "string",
33
+ groups: "string[]"
34
+ },
35
+ mode: "add_extra"
36
+ }
37
+
38
+ const VerifyEndpointServiceSchema: Schema<VerifyEndpointServiceOptions> = {
39
+ type: "object",
40
+ properties: {
41
+ url: "string1",
42
+ method: "string1",
43
+ tokenLocation: {
44
+ type: "enum",
45
+ enumValues: ["header", "query", "cookie"]
46
+ },
47
+ tokenLocationName: "string1"
48
+ }
49
+ };
50
+
51
+ export class VerifyEndpointService implements VerifyTokenService {
52
+
53
+ protected options: VerifyEndpointServiceOptions;
54
+
55
+ constructor(options?: VerifyEndpointServiceOptions) {
56
+ if (!options) {
57
+ const [url, method] = checkEnvVariables(["TOKEN_VERIFY_ENDPOINT", "TOKEN_VERIFY_ENDPOINT_METHOD"]);
58
+ const [tokenVerifyLocation] = checkEnvVariables(["TOKEN_VERIFY_LOCATION"], [DEFAULT_TOKEN_LOCATION]);
59
+ let tokenLocationName;
60
+ switch (tokenVerifyLocation) {
61
+ case "header":
62
+ tokenLocationName = checkEnvVariables(["TOKEN_HEADER"], [DEFAULT_TOKEN_HEADER])[0];
63
+ break;
64
+ case "query":
65
+ tokenLocationName = checkEnvVariables(["TOKEN_QUERY"], [DEFAULT_TOKEN_QUERY])[0];
66
+ break;
67
+ case "cookie":
68
+ tokenLocationName = checkEnvVariables(["TOKEN_COOKIE"], [DEFAULT_TOKEN_COOKIE])[0];
69
+ break;
70
+ default:
71
+ throw new Error(`TOKEN_VERIFY_LOCATION=${tokenVerifyLocation} not supported use (header or query)`);
72
+ }
73
+ this.options = {
74
+ url, method,
75
+ tokenLocation: tokenVerifyLocation,
76
+ tokenLocationName
77
+ }
78
+ } else {
79
+ this.options = assertNotUndefined(DEFAULT_PARSER.parse(options, VerifyEndpointServiceSchema, "options"), "bad options");
80
+ }
81
+ if (this.options.tokenLocationName && (this.options.tokenLocationName === "__proto__" || this.options.tokenLocationName === "__prototype__")) {
82
+ throw new Error(`invalid tokenLocationName ${this.options.tokenLocationName}`);
83
+ }
84
+ }
85
+
86
+ public async verify({ token, req }: { token: string; req: Request; }): Promise<Session | null> {
87
+ try {
88
+ let response = null;
89
+ const tokenVerifyLocation = this.options.tokenLocation;
90
+ const url = this.options.url;
91
+ const method = this.options.method;
92
+ switch (tokenVerifyLocation) {
93
+ case "header":
94
+ const tokenHeaderLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(req);
95
+ req.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_HEADER=[${tokenHeaderLocation}]`);
96
+ response = await this.getResponse({
97
+ url,
98
+ headers: {
99
+ [tokenHeaderLocation]: token
100
+ },
101
+ method
102
+ }, req);
103
+ break;
104
+ case "query":
105
+ const tokenQueryLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(req);
106
+ req.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_QUERY=[${tokenQueryLocation}]`);
107
+ response = await this.getResponse({
108
+ url,
109
+ query: {
110
+ [tokenQueryLocation]: token
111
+ },
112
+ method
113
+ }, req);
114
+ break;
115
+ case "cookie":
116
+ const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(req);
117
+ req.logger.trace(`verifying [${token}] on TOKEN_VERIFY_ENDPOINT=[${process.env.TOKEN_VERIFY_ENDPOINT}] TOKEN_COOKIE=[${tokenCookieLocation}]`);
118
+ response = await this.getResponse({
119
+ url,
120
+ method,
121
+ headers: {
122
+ Cookie: `${tokenCookieLocation}=${token}; Path=/; HttpOnly;`
123
+ }
124
+ }, req);
125
+ break;
126
+ default:
127
+ throw new Error(`TOKEN_VERIFY_LOCATION=${tokenVerifyLocation} not supported use (header, query or cookie)`);
128
+ }
129
+ if (response) {
130
+ const session = await this.decodeSession(response, token, req);
131
+ if (!this.checkSession(session, req)) {
132
+ req.logger.warn(`unauthorized token not valid [${token}]`);
133
+ return null;
134
+ } else {
135
+ req.logger.trace("token [%s]authorized!", token);
136
+
137
+ if (tokenVerifyLocation === "cookie" && response.headers["set-cookie"]) {
138
+ const tokenCookieLocation = typeof this.options.tokenLocationName === "string" ? this.options.tokenLocationName : await this.options.tokenLocationName(req);
139
+ const cookies = response.headers["set-cookie"].map((c: any) => cookieParse(c)).filter((c: any) => c[tokenCookieLocation] !== undefined);
140
+ if (cookies.length === 1) {
141
+ const value = cookies[0][tokenCookieLocation];
142
+ if (value) {
143
+ session.token = value; // replace token because token update via set-cookie
144
+ }
145
+ }
146
+ }
147
+ return {
148
+ token,
149
+ ...session
150
+ } as Session;
151
+ }
152
+ } else {
153
+ req.logger.warn(`unauthorized token not valid [${token}]`);
154
+ return null;
155
+ }
156
+ } catch (e: any) {
157
+ throw new UnAuthorizedError(`Fail to authenticate token! error verifying [${token}] [${e.status}][${e.config ? e.config.url : ""}]`);
158
+ }
159
+ }
160
+
161
+ /* eslint-disable @typescript-eslint/no-unused-vars */
162
+ protected async getResponse(config: RequestOptions, req?: Request): Promise<RequestResponse> {
163
+ return request(config);
164
+ }
165
+
166
+ /* eslint-disable @typescript-eslint/no-unused-vars */
167
+ protected checkSession(session: NoTokenSession, req?: Request): boolean {
168
+ assertNotUndefined(DEFAULT_PARSER.parse(session, NoTokenSessionSchema, "session"), "bad session");
169
+ return true;
170
+ }
171
+
172
+ /* eslint-disable @typescript-eslint/no-unused-vars */
173
+ protected async decodeSession(response: RequestResponse, token: string, req?: Request): Promise<NoTokenSession> {
174
+ const session = response.data;
175
+ return session as NoTokenSession;
176
+ }
177
+ }
178
+
179
+
180
+ export function SessionHandler(config: SessionHandlerOptions): Handler<void> {
18
181
  if (!config.options) {
19
182
  const tokenLocation = checkEnvVariables(["TOKEN_LOCATION"], [DEFAULT_TOKEN_LOCATION])[0];
20
183
  config.options = {
@@ -93,36 +256,36 @@ export const SessionHandler = (config: SessionHandlerOptions): Handler<void> =>
93
256
  const tokenLocation = config.options.tokenLocation;
94
257
  const tokenLocationName = config.options.tokenLocationName;
95
258
  const setCookieOptions = config.options.setCookieOptions;
96
- return async function SessionHandler(ctx: Context): Promise<void> {
259
+ return async function SessionHandler(req, res): Promise<void> {
97
260
  try {
98
- const tlN = typeof tokenLocationName === "string" ? tokenLocationName : await tokenLocationName(ctx);
261
+ const tlN = typeof tokenLocationName === "string" ? tokenLocationName : await tokenLocationName(req);
99
262
  let token = null;
100
263
  switch (tokenLocation) {
101
264
  case "header":
102
- token = ctx.headers[(tlN).toLowerCase()] as string;
265
+ token = req.headers[(tlN).toLowerCase()] as string;
103
266
  break;
104
267
  case "query":
105
- token = ctx.query[tlN] as string;
268
+ token = req.query[tlN] as string;
106
269
  break;
107
270
  case "cookie":
108
- token = ctx.cookies[tlN] ? ctx.cookies[tlN] : undefined;
271
+ token = req.cookies[tlN] ? req.cookies[tlN] : undefined;
109
272
  break;
110
273
  default:
111
274
  throw new Error(`TOKEN_LOCATION=${tokenLocation} not supported use (header, query or cookie)`);
112
275
  }
113
276
  if (!token) {
114
- ctx.logger.warn("No token provided!");
277
+ req.logger.warn("No token provided!");
115
278
  throw new ForbiddenError("NO TOKEN");
116
279
  } else {
117
- const session = await config.authService.verify({ token, ctx });
280
+ const session = await config.authService.verify({ token, req });
118
281
  if (!session) {
119
- ctx.logger.warn("fail to authenticate token [%s]!", token);
282
+ req.logger.warn("fail to authenticate token [%s]!", token);
120
283
  throw new UnAuthorizedError();
121
284
  } else {
122
285
  if (tokenLocation === "cookie" && session.token !== token) {
123
286
  const newTokenCookie = String(session.token ? session.token : token);
124
- const cookiePath = typeof setCookieOptions.path === "string" ? setCookieOptions.path : await setCookieOptions.path(ctx);
125
- ctx.setCookie(tlN, newTokenCookie, session.expires instanceof Date ? {
287
+ const cookiePath = typeof setCookieOptions.path === "string" ? setCookieOptions.path : await setCookieOptions.path(req);
288
+ res.setCookie(tlN, newTokenCookie, session.expires instanceof Date ? {
126
289
  httpOnly: setCookieOptions.httpOnly,
127
290
  secure: setCookieOptions.secure,
128
291
  path: cookiePath,
@@ -135,8 +298,8 @@ export const SessionHandler = (config: SessionHandlerOptions): Handler<void> =>
135
298
  sameSite: setCookieOptions.sameSite
136
299
  })
137
300
  }
138
- ctx.session = session;
139
- ctx.logger.debug("authenticated!");
301
+ req.session = session;
302
+ req.logger.debug("authenticated!");
140
303
  }
141
304
  }
142
305
  } catch (e: any) {
@@ -150,3 +313,70 @@ export const SessionHandler = (config: SessionHandlerOptions): Handler<void> =>
150
313
  };
151
314
 
152
315
 
316
+ export function GroupPolicyHandler(options: GroupPolicy): Handler<void> {
317
+ options = assertNotUndefined(DEFAULT_PARSER.parse(options, GroupPolicySchema, "options"));
318
+ return function GroupPolicyHandler(req: Request, res: Response): void {
319
+ try {
320
+ if (!req.session) {
321
+ throw new UnAuthorizedError(`No Session!`);
322
+ } else {
323
+ const result = policyCheck(req.session, options);
324
+ if (result) {
325
+ req.logger.debug("groups validated!");
326
+ } else {
327
+ req.logger.error("%s groups fail to validate!", req && req.session && req.session.groups ? `[${req.session.groups.join(",")}] ` : "");
328
+ throw new ForbiddenError(`Invalid session. You are not permitted to do this!`);
329
+ }
330
+ }
331
+ } catch (e: any) {
332
+ //(logger as Logger).warn(`request[${req.uuid}] message[${e.message}] stack[${e.stack}]`);
333
+ if (e.name && e.name !== "Error") {
334
+ throw e;
335
+ } else {
336
+ throw new UnAuthorizedError(`Invalid session. You are not permitted to do this!`);
337
+ }
338
+ }
339
+ };
340
+ };
341
+
342
+ function policyCheck(session: Session, options: GroupPolicy): boolean {
343
+ switch (options.groupPolicy) {
344
+ case "at_least_one":
345
+ for (const group of options.groups) {
346
+ if (group instanceof Array) {
347
+ let ret = true;
348
+ for (const g of group) {
349
+ if (session.groups.indexOf(g) === -1) {
350
+ ret = false;
351
+ break;
352
+ }
353
+ }
354
+ if (ret) {
355
+ return true;
356
+ }
357
+ } else {
358
+ if (session.groups.indexOf(group) !== -1) {
359
+ return true;
360
+ }
361
+ }
362
+ }
363
+ return false;
364
+ case "all":
365
+ for (const group of options.groups) {
366
+ if (group instanceof Array) {
367
+ for (const g of group) {
368
+ if (session.groups.indexOf(g) === -1) {
369
+ return false;
370
+ }
371
+ }
372
+ } else {
373
+ if (session.groups.indexOf(group) === -1) {
374
+ return false;
375
+ }
376
+ }
377
+ }
378
+ return true;
379
+ default:
380
+ throw new BadRequestError(`policy [${options.groupPolicy}] not implemented!!`);
381
+ }
382
+ };