aboutsummaryrefslogtreecommitdiff
path: root/src/server/RouteManager.ts
blob: c5d70da3d0fb98ea0e85b2186a0174d17a05519d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { cyan, green, red } from 'colors';
import { Express, Request, Response } from 'express';
import { Utils } from '../Utils';
import RouteSubscriber from './RouteSubscriber';
import { AdminPrivileges } from './SocketData';
import { DashUserModel } from './authentication/DashUserModel';

export enum Method {
    GET,
    POST,
    PATCH,
    DELETE,
}

export interface CoreArguments {
    req: Request;
    res: Response;
    isRelease: boolean;
}

export type AuthorizedCore = CoreArguments & { user: DashUserModel };
export type SecureHandler = (core: AuthorizedCore) => any | Promise<any>;
export type PublicHandler = (core: CoreArguments) => any | Promise<any>;
export type ErrorHandler = (core: CoreArguments & { error: any }) => any | Promise<any>;

export const STATUS = {
    OK: 200,
    BAD_REQUEST: 400,
    EXECUTION_ERROR: 500,
    PERMISSION_DENIED: 403,
};

export function _error(res: Response, message: string, error?: any) {
    console.error(message, error);
    res.statusMessage = message;
    res.status(STATUS.EXECUTION_ERROR).send(error);
}

export function _success(res: Response, body: any) {
    res.status(STATUS.OK).send(body);
}

export function _invalid(res: Response, message: string) {
    res.status(STATUS.BAD_REQUEST).send(message);
}

export function _permissionDenied(res: Response, message?: string) {
    if (message) {
        res.statusMessage = message;
    }
    res.status(STATUS.PERMISSION_DENIED).send(`Permission Denied! ${message}`);
}
export interface RouteInitializer {
    method: Method;
    subscription: string | RouteSubscriber | (string | RouteSubscriber)[];
    secureHandler: SecureHandler;
    publicHandler?: PublicHandler;
    errorHandler?: ErrorHandler;
    requireAdminInRelease?: true;
}

const registered = new Map<string, Set<Method>>();

enum RegistrationError {
    Malformed,
    Duplicate,
}

export default class RouteManager {
    private server: Express;
    private _isRelease: boolean;
    private failedRegistrations: { route: string; reason: RegistrationError }[] = [];

    public get isRelease() {
        return this._isRelease;
    }

    constructor(server: Express, isRelease: boolean) {
        this.server = server;
        this._isRelease = isRelease;
    }

    logRegistrationOutcome = () => {
        if (this.failedRegistrations.length) {
            let duplicateCount = 0;
            let malformedCount = 0;
            this.failedRegistrations.forEach(({ reason, route }) => {
                let error: string;
                if (reason === RegistrationError.Duplicate) {
                    error = `duplicate registration error: ${route} is already registered `;
                    duplicateCount++;
                } else {
                    error = `malformed route error: ${route} is invalid`;
                    malformedCount++;
                }
                console.log(red(error));
            });
            console.log();
            if (duplicateCount) {
                console.log('please remove all duplicate routes before continuing');
            }
            if (malformedCount) {
                console.log(`please ensure all routes adhere to ^/$|^/[A-Za-z]+(/:[A-Za-z?_]+)*$`);
            }
            process.exit(1);
        } else {
            console.log(green('all server routes have been successfully registered:'));
            Array.from(registered.keys())
                .sort()
                .forEach(route => console.log(cyan(route)));
            console.log();
        }
    };

    static routes: string[] = [];
    /**
     *
     * @param initializer
     */
    addSupervisedRoute = (initializer: RouteInitializer): void => {
        const { method, subscription, secureHandler, publicHandler, errorHandler, requireAdminInRelease: requireAdmin } = initializer;

        typeof initializer.subscription === 'string' && RouteManager.routes.push(initializer.subscription);
        initializer.subscription instanceof RouteSubscriber && RouteManager.routes.push(initializer.subscription.root);
        initializer.subscription instanceof Array &&
            initializer.subscription.forEach(sub => {
                typeof sub === 'string' && RouteManager.routes.push(sub);
                sub instanceof RouteSubscriber && RouteManager.routes.push(sub.root);
            });
        const isRelease = this._isRelease;
        const supervised = async (req: Request, res: Response) => {
            let user = req.user as Partial<DashUserModel> | undefined;
            const { originalUrl: target } = req;
            if (process.env.DB === 'MEM' && !user) {
                user = { id: 'guest', email: 'guest', userDocumentId: Utils.GuestID() };
            }
            const core = { req, res, isRelease };
            const tryExecute = async (toExecute: (args: any) => any | Promise<any>, args: any) => {
                try {
                    await toExecute(args);
                } catch (e) {
                    console.log(red(target), user && 'email' in user ? '<user logged out>' : undefined);
                    if (errorHandler) {
                        errorHandler({ ...core, error: e });
                    } else {
                        _error(res, `The server encountered an internal error when serving ${target}.`, e);
                    }
                }
            };
            if (user) {
                if (requireAdmin && isRelease && process.env.PASSWORD) {
                    if (AdminPrivileges.get(user.id)) {
                        AdminPrivileges.delete(user.id);
                    } else {
                        res.redirect(`/admin/${req.originalUrl.substring(1).replace('/', ':')}`);
                        return;
                    }
                }
                await tryExecute(secureHandler, { ...core, user });
            }
            // req.session!.target = target;
            else if (publicHandler) {
                await tryExecute(publicHandler, core);
                if (!res.headersSent) {
                    // res.redirect("/login");
                }
            } else {
                res.redirect('/login');
            }
            setTimeout(() => {
                if (!res.headersSent) {
                    console.log(red(`Initiating fallback for ${target}. Please remove dangling promise from route handler`));
                    const warning = `request to ${target} fell through - this is a fallback response`;
                    res.send({ warning });
                }
            }, 1000);
        };
        const subscribe = (subscriber: RouteSubscriber | string) => {
            let route: string;
            if (typeof subscriber === 'string') {
                route = subscriber;
            } else {
                route = subscriber.build;
            }
            if (!/^\/$|^\/[A-Za-z*]+(\/:[A-Za-z?_*]+)*$/g.test(route)) {
                this.failedRegistrations.push({
                    reason: RegistrationError.Malformed,
                    route,
                });
            } else {
                const existing = registered.get(route);
                if (existing) {
                    if (existing.has(method)) {
                        this.failedRegistrations.push({
                            reason: RegistrationError.Duplicate,
                            route,
                        });
                        return;
                    }
                } else {
                    const specific = new Set<Method>();
                    specific.add(method);
                    registered.set(route, specific);
                }
                switch (method) {
                    case Method.GET:
                        this.server.get(route, supervised);
                        break;
                    case Method.POST:
                        this.server.post(route, supervised);
                        break;
                    case Method.PATCH:
                        this.server.patch(route, supervised);
                        break;
                    case Method.DELETE:
                        this.server.delete(route, supervised);
                        break;
                    default:
                }
            }
        };
        if (Array.isArray(subscription)) {
            subscription.forEach(subscribe);
        } else {
            subscribe(subscription);
        }
    };
}