@adminforth/two-factors-auth 1.0.10 → 1.0.14

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,230 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import path from 'path';
11
- import fs from 'fs';
12
- import CodeInjector from '../modules/codeInjector.js';
13
- import fetch from 'node-fetch';
14
- function replaceAtStart(string, substring) {
15
- if (string.startsWith(substring)) {
16
- return string.slice(substring.length);
17
- }
18
- return string;
19
- }
20
- function proxyTo(url, res) {
21
- return __awaiter(this, void 0, void 0, function* () {
22
- const actual = yield fetch(url);
23
- actual.headers.forEach((v, n) => res.setHeader(n, v));
24
- actual.body.pipe(res);
25
- });
26
- }
27
- function parseExpressCookie(req) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- const cookies = req.headers.cookie;
30
- if (!cookies) {
31
- return [];
32
- }
33
- const parts = cookies.split('; ');
34
- const result = [];
35
- parts.forEach(part => {
36
- const [key, value] = part.split('=');
37
- result.push({ key, value });
38
- });
39
- return result;
40
- });
41
- }
42
- const respondNoServer = (title, explanation) => {
43
- return `
44
- <!DOCTYPE html>
45
- <html lang="en">
46
- <head>
47
- <meta charset="UTF-8">
48
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
49
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
50
- <title>AdminForth</title>
51
- </head>
52
- <body>
53
- <div class="center">
54
- <h1>Oops!</h1>
55
- <h2>${title}</h2>
56
- <p>${explanation}</p>
57
- </div>
58
- <style>
59
- body {
60
- font-family: Arial, sans-serif;
61
- background-color: #f0f0f0;
62
- margin: 0;
63
- padding: 0;
64
- }
65
- .center {
66
- display: flex;
67
- justify-content: center;
68
- align-items: center;
69
- height: 100vh;
70
- flex-direction: column;
71
- }
72
- </style>
73
- <script>
74
- setTimeout(() => {
75
- location.reload();
76
- }, 1500);
77
- </script>
78
- </body>
79
- `;
80
- };
81
- class ExpressServer {
82
- constructor(adminforth) {
83
- this.adminforth = adminforth;
84
- }
85
- setupSpaServer() {
86
- const prefix = this.adminforth.config.baseUrl;
87
- const slashedPrefix = prefix.endsWith('/') ? prefix : `${prefix}/`;
88
- if (this.adminforth.runningHotReload) {
89
- const handler = (req, res) => __awaiter(this, void 0, void 0, function* () {
90
- // proxy using fetch to webpack dev server
91
- try {
92
- yield proxyTo(`http://localhost:5173${req.url}`, res);
93
- }
94
- catch (e) {
95
- // console.log('Failed to proxy', e);
96
- res.status(500).send(respondNoServer('AdminForth SPA is not ready yet', 'Vite is still starting up. Please wait a moment...'));
97
- return;
98
- }
99
- });
100
- this.expressApp.get(`${slashedPrefix}assets/*`, handler);
101
- this.expressApp.get(`${prefix}*`, handler);
102
- }
103
- else {
104
- this.expressApp.get(`${slashedPrefix}assets/*`, (req, res) => {
105
- res.sendFile(path.join(CodeInjector.SPA_TMP_PATH, 'dist', replaceAtStart(req.url, prefix)), {
106
- cacheControl: false,
107
- // store for a year
108
- headers: {
109
- 'Cache-Control': 'public, max-age=31536000',
110
- 'Pragma': 'public',
111
- }
112
- });
113
- });
114
- this.expressApp.get(`${prefix}*`, (req, res) => __awaiter(this, void 0, void 0, function* () {
115
- const fullPath = path.join(CodeInjector.SPA_TMP_PATH, 'dist', 'index.html');
116
- let fileExists = true;
117
- try {
118
- yield fs.promises.access(fullPath, fs.constants.F_OK);
119
- }
120
- catch (e) {
121
- fileExists = false;
122
- }
123
- if (!fileExists) {
124
- res.status(500).send(respondNoServer(`${this.adminforth.config.customization.brandName} is still warming up`, 'Please wait a moment...'));
125
- return;
126
- }
127
- res.sendFile(fullPath, {
128
- cacheControl: false,
129
- headers: {
130
- 'Content-Type': 'text/html',
131
- 'Cache-Control': 'no-cache, no-store, must-revalidate',
132
- 'Pragma': 'no-cache',
133
- 'Expires': '0'
134
- }
135
- });
136
- }));
137
- }
138
- }
139
- serve(app) {
140
- this.expressApp = app;
141
- this.adminforth.setupEndpoints(this);
142
- this.setupSpaServer();
143
- }
144
- authorize(handler) {
145
- return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
146
- var _a;
147
- const cookies = yield parseExpressCookie(req);
148
- // check if multiple adminforth_jwt providerd and show warning
149
- const jwts = cookies.filter(({ key }) => key === 'adminforth_jwt');
150
- if (jwts.length > 1) {
151
- console.error('Multiple adminforth_jwt cookies provided');
152
- jwts.forEach(({ key }) => {
153
- res.setHeader('Set-Cookie', `${key}=; HttpOnly; SameSite=Strict; Expires=${new Date(0).toUTCString()}`);
154
- });
155
- res.status(401).send(`Unauthorized by AdminForth. Too many JWT cookies found (${jwts.length} instead of 1). Expected to get only one cookie with name 'adminforth_jwt'.`);
156
- }
157
- const jwt = (_a = jwts[0]) === null || _a === void 0 ? void 0 : _a.value;
158
- if (!jwt) {
159
- res.status(401).send('Unauthorized by AdminForth');
160
- return;
161
- }
162
- const adminforthUser = yield this.adminforth.auth.verify(jwt, 'auth');
163
- if (!adminforthUser) {
164
- res.status(401).send('Unauthorized by AdminForth');
165
- }
166
- else {
167
- req.adminUser = adminforthUser;
168
- handler(req, res, next);
169
- }
170
- });
171
- }
172
- endpoint({ method = 'GET', path, handler, noAuth = false }) {
173
- if (!path.startsWith('/')) {
174
- throw new Error(`Path must start with /, got: ${path}`);
175
- }
176
- const fullPath = `${this.adminforth.config.baseUrl}/adminapi/v1${path}`;
177
- const expressHandler = (req, res) => __awaiter(this, void 0, void 0, function* () {
178
- let body = req.body || {};
179
- if (typeof body === 'string') {
180
- try {
181
- body = JSON.parse(body);
182
- }
183
- catch (e) {
184
- console.error('Failed to parse body', e);
185
- res.status(400).send('Invalid JSON body');
186
- }
187
- }
188
- const query = req.query;
189
- const adminUser = req.adminUser;
190
- const headers = req.headers;
191
- const cookies = yield parseExpressCookie(req);
192
- const response = {
193
- headers: [],
194
- status: 200,
195
- message: undefined,
196
- setHeader(name, value) {
197
- this.headers.push([name, value]);
198
- },
199
- setStatus(code, message) {
200
- this.status = code;
201
- this.message = message;
202
- }
203
- };
204
- const input = { body, query, headers, cookies, adminUser, response, _raw_express_req: req, _raw_express_res: res };
205
- let output;
206
- try {
207
- output = yield handler(input);
208
- }
209
- catch (e) {
210
- console.error('Error in handler', e);
211
- // print full stack trace
212
- console.error(e.stack);
213
- res.status(500).send('Internal server error');
214
- return;
215
- }
216
- response.headers.forEach(([name, value]) => {
217
- res.setHeader(name, value);
218
- });
219
- const resp = res.status(response.status);
220
- if (response.message) {
221
- resp.send(response.message);
222
- return;
223
- }
224
- res.json(output);
225
- });
226
- console.log(`Adding endpoint ${method} ${fullPath}`);
227
- this.expressApp[method.toLowerCase()](fullPath, noAuth ? expressHandler : this.authorize(expressHandler));
228
- }
229
- }
230
- export default ExpressServer;
@@ -1,105 +0,0 @@
1
- export var AdminForthMenuTypes;
2
- (function (AdminForthMenuTypes) {
3
- /**
4
- * HEADING is just a label in the menu.
5
- * Respect `label` and `icon` property in {@link AdminForthConfigMenuItem}
6
- */
7
- AdminForthMenuTypes["heading"] = "heading";
8
- /**
9
- * GROUP is a group of menu items.
10
- * Respects `label`, `icon` and `children` properties in {@link AdminForthConfigMenuItem}
11
- * use @AdminForthMenuTypes.open to set if group is open by default
12
- */
13
- AdminForthMenuTypes["group"] = "group";
14
- /**
15
- * RESOURCE is a link to a resource.
16
- * Respects `label`, `icon`, `resourceId`, `homepage`, `isStaticRoute` properties in {@link AdminForthConfigMenuItem}
17
- */
18
- AdminForthMenuTypes["resource"] = "resource";
19
- /**
20
- * PAGE is a link to a custom page.
21
- * Respects `label`, `icon`, `path`, `component`, `homepage`, `isStaticRoute`, properties in {@link AdminForthConfigMenuItem}
22
- *
23
- * Example:
24
- *
25
- * ```ts
26
- * \{
27
- * type: AdminForthMenuTypes.PAGE,
28
- * label: 'Custom Page',
29
- * icon: 'home',
30
- * path: '/dash',
31
- * component: '@@/Dashboard.vue',
32
- * homepage: true,
33
- * \}
34
- * ```
35
- *
36
- */
37
- AdminForthMenuTypes["page"] = "page";
38
- /**
39
- * GAP ads some space between menu items.
40
- */
41
- AdminForthMenuTypes["gap"] = "gap";
42
- /**
43
- * DIVIDER is a divider between menu items.
44
- */
45
- AdminForthMenuTypes["divider"] = "divider";
46
- })(AdminForthMenuTypes || (AdminForthMenuTypes = {}));
47
- export var AdminForthResourcePages;
48
- (function (AdminForthResourcePages) {
49
- AdminForthResourcePages["list"] = "list";
50
- AdminForthResourcePages["show"] = "show";
51
- AdminForthResourcePages["edit"] = "edit";
52
- AdminForthResourcePages["create"] = "create";
53
- AdminForthResourcePages["filter"] = "filter";
54
- })(AdminForthResourcePages || (AdminForthResourcePages = {}));
55
- export var AllowedActionsEnum;
56
- (function (AllowedActionsEnum) {
57
- AllowedActionsEnum["show"] = "show";
58
- AllowedActionsEnum["list"] = "list";
59
- AllowedActionsEnum["edit"] = "edit";
60
- AllowedActionsEnum["create"] = "create";
61
- AllowedActionsEnum["delete"] = "delete";
62
- AllowedActionsEnum["filter"] = "filter";
63
- })(AllowedActionsEnum || (AllowedActionsEnum = {}));
64
- export var ActionCheckSource;
65
- (function (ActionCheckSource) {
66
- ActionCheckSource["DisplayButtons"] = "displayButtons";
67
- ActionCheckSource["ListRequest"] = "listRequest";
68
- ActionCheckSource["ShowRequest"] = "showRequest";
69
- ActionCheckSource["EditRequest"] = "editRequest";
70
- ActionCheckSource["CreateRequest"] = "createRequest";
71
- ActionCheckSource["DeleteRequest"] = "deleteRequest";
72
- })(ActionCheckSource || (ActionCheckSource = {}));
73
- export var AdminForthDataTypes;
74
- (function (AdminForthDataTypes) {
75
- AdminForthDataTypes["STRING"] = "string";
76
- AdminForthDataTypes["INTEGER"] = "integer";
77
- AdminForthDataTypes["FLOAT"] = "float";
78
- AdminForthDataTypes["DECIMAL"] = "decimal";
79
- AdminForthDataTypes["BOOLEAN"] = "boolean";
80
- AdminForthDataTypes["DATE"] = "date";
81
- AdminForthDataTypes["DATETIME"] = "datetime";
82
- AdminForthDataTypes["TIME"] = "time";
83
- AdminForthDataTypes["TEXT"] = "text";
84
- AdminForthDataTypes["JSON"] = "json";
85
- })(AdminForthDataTypes || (AdminForthDataTypes = {}));
86
- export var AdminForthFilterOperators;
87
- (function (AdminForthFilterOperators) {
88
- AdminForthFilterOperators["EQ"] = "eq";
89
- AdminForthFilterOperators["NE"] = "ne";
90
- AdminForthFilterOperators["GT"] = "gt";
91
- AdminForthFilterOperators["LT"] = "lt";
92
- AdminForthFilterOperators["GTE"] = "gte";
93
- AdminForthFilterOperators["LTE"] = "lte";
94
- AdminForthFilterOperators["LIKE"] = "like";
95
- AdminForthFilterOperators["ILIKE"] = "ilike";
96
- AdminForthFilterOperators["IN"] = "in";
97
- AdminForthFilterOperators["NIN"] = "nin";
98
- })(AdminForthFilterOperators || (AdminForthFilterOperators = {}));
99
- ;
100
- export var AdminForthSortDirections;
101
- (function (AdminForthSortDirections) {
102
- AdminForthSortDirections["asc"] = "asc";
103
- AdminForthSortDirections["desc"] = "desc";
104
- })(AdminForthSortDirections || (AdminForthSortDirections = {}));
105
- ;