-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
137 lines (120 loc) Β· 4.35 KB
/
app.ts
File metadata and controls
137 lines (120 loc) Β· 4.35 KB
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
import express, { NextFunction, Request, Response } from 'express';
import path from 'path';
import cors from 'cors';
import morganMiddleware from './middleware/morgan.middleware.js';
import router from './routes/router.js';
import routeGuard, { createAccessRules } from './auth/guard.js';
import authConfig from './routes/authConfig.js';
import { type User } from '../prisma/generated/client.js';
import BaseError from './utils/errors/BaseError.js';
import { fromNodeHeaders, toNodeHandler } from 'better-auth/node';
import { auth } from './auth.js';
import Logger from './utils/logger.js';
import { CORS_ORIGIN } from './utils/originConfig.js';
import { notify } from './socketIoServer.js';
const AccessRules = createAccessRules(authConfig.accessMatrix);
/**
* Architecture samples
* @link https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/blob/main/5-AccessControl/1-call-api-roles/API/app.js
*
*/
const app = express();
export const API_VERSION = 'v1';
export const API_URL = `/api/${API_VERSION}`;
/**
* this is not needed when running behind a reverse proxy
* as is the case with dokku (nginx)
*/
// app.use(compression(), express.json({ limit: "5mb" }));
// ensure the server can call other domains: enable cross origin resource sharing (cors)
app.use(
cors({
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD'],
origin: CORS_ORIGIN,
credentials: true
})
);
/** make sure to have 1 (reverse) proxy in front of the application
* as is the case with dokku (nginx)
*/
app.set('trust proxy', 1);
app.use(morganMiddleware);
// make sure to configure *before* the json middleware
app.all('/api/auth/{*any}', toNodeHandler(auth));
// received packages should be presented in the JSON format
app.use(express.json({ limit: '5mb' }));
// passport.deserializeUser(deserializeUser);
// Serve the static files to be accessed by the docs app
app.use(express.static(path.join(__dirname, '..', 'docs')));
const welcomeApi = (req: Request, res: Response) => {
return res.status(200).send('Welcome to the TEACHING-WEBSITE-API V1.0');
};
// Public Endpoints
app.get(`${API_URL}`, welcomeApi);
const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
if ((err as BaseError).isHttpError) {
const httpErr = err as BaseError;
res.status(httpErr.statusCode).send({
errors: [
{
name: httpErr.name,
message: httpErr.message,
status: httpErr.statusCode,
isOperational: httpErr.isOperational
}
]
});
} else {
res.status(500).send({ errors: [{ name: err.name, message: err.message }] });
}
Logger.error(err);
};
export const configure = (_app: typeof app) => {
/**
* Notification Middleware
* when the response `res` contains a `notifications` property, the middleware will
* send the notification over SocketIO to the specififed rooms.
*/
_app.use((req: Request, res, next) => {
res.on('finish', async () => {
if (res.statusCode >= 400) {
return;
}
if (res.notifications) {
res.notifications.forEach((notification) => {
notify(notification, req.headers['x-metadata-sid'] as string);
});
}
});
next();
});
/**
* API Route Guard
* This middleware will check if the user is authenticated and has the required
* permissions to access the requested route.
*/
_app.use(
API_URL,
(req, res, next) => {
return auth.api
.getSession({ headers: fromNodeHeaders(req.headers) })
.then((session) => {
if (!session?.user) {
return res.status(401).json({ error: 'Unauthorized' });
}
req.user = session.user as User;
return next();
})
.catch((err) => {
return res.status(401).json({ error: err.message });
});
},
routeGuard(AccessRules), // route guard middleware
router // the router with all the routes
);
_app.use(errorHandler);
};
if (process.env.NODE_ENV === 'test') {
configure(app);
}
export default app;