forked from huggingface/Mongoku
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.ts
More file actions
174 lines (153 loc) · 4.99 KB
/
server.ts
File metadata and controls
174 lines (153 loc) · 4.99 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
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
import * as path from 'path';
import * as fs from 'fs';
import http from 'http';
import express from 'express';
import session from 'express-session';
import cookieParser from 'cookie-parser';
import MemoryStore from 'memorystore';
import {json as jsonBodyParser} from 'body-parser';
import factory from './lib/Factory';
import { api } from './routes/api';
declare module 'express-session' {
interface SessionData {
signedUser: string;
}
}
const app = express();
const DISABLE_AUTH = process.env.MONGOKU_DISABLE_AUTH == 'true';
const setupServer = () => {
const SERVER_PORT = process.env.MONGOKU_SERVER_PORT || 3100;
const AUTH_ENDPOINT = process.env.MONGOKU_AUTH_ENDPOINT || 'http://localhost/auth';
const EXT_SESSION_COOKIE = process.env.MONGOKU_EXT_SESSION_COOKIE;
const EXT_SESSION_ENDPOINT = process.env.MONGOKU_EXT_SESSION_ENDPOINT;
app.use(cookieParser());
app.use(session({
name: 'mongoku.sid',
cookie: { maxAge: 2*60*60*1000 },
store: new (MemoryStore(session as any))({
checkPeriod: 2*60*60*1000 // prune expired entries every 2h
}),
resave: false,
secret: process.env.MONGOKU_SESSION_SECRET || 'keyboard cat',
saveUninitialized: false
}));
app.get('/', (req, res, next) => {
res.sendFile("app/index.html", { root: __dirname }, (err) => {
if (err) {
return next(err);
}
});
});
app.post('/signin', jsonBodyParser(), (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return void res.status(400).send('username and password expected');
}
const data = JSON.stringify({ login: username, passwd: password });
const headers = {
accept: 'application/json',
'accept-language': 'en-US,en;q=0.9,ru;q=0.8',
'content-type': 'application/json',
'content-length': data.length,
};
const httpReq = http.request(AUTH_ENDPOINT, { headers, method: 'POST' }, (httpRes) => {
if (httpRes.statusCode === 200) {
res.set('set-cookie', httpRes.headers['set-cookie']);
req.session.signedUser = username;
res.json({ ok: true, message: 'signed in as ' + username });
} else {
let message = '';
httpRes.on('data', (chunk) => message += chunk);
httpRes.on('end', () => res.status(httpRes.statusCode || 401)
.json({ ok: false, message }));
}
});
httpReq.on('error', (error) => res.status(500).send(error));
httpReq.write(data);
httpReq.end();
});
app.post('/signout', (req, res) => {
res.set('Vary', 'Origin');
res.set('Access-Control-Allow-Origin', req.headers.origin);
res.set('Access-Control-Allow-Credentials', 'true');
const { signedUser } = req.session;
if (signedUser)
req.session.signedUser = undefined;
res.json({
ok: true,
message: signedUser ? 'successfully signed out' : 'was not signed in',
});
});
if (EXT_SESSION_COOKIE && EXT_SESSION_ENDPOINT) {
app.use('/api', (req, res, next) => {
if (req.session.signedUser || DISABLE_AUTH)
return void next();
const externalSession = req.cookies[EXT_SESSION_COOKIE];
if (!externalSession)
return void next();
const withCookie = {
accept: 'application/json',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
cookie: `${EXT_SESSION_COOKIE}=${externalSession}`,
};
const httpReq = http.request(EXT_SESSION_ENDPOINT, {headers: withCookie}, (httpRes) => {
if (httpRes.statusCode != 200)
return void next();
let bodyString = '';
httpRes.on('data', (chunk) => bodyString += chunk);
httpRes.on('end', () => {
try {
const body = JSON.parse(bodyString);
if (body.login)
req.session.signedUser = body.login;
} catch(e){}
next();
});
});
httpReq.on('error', error => { next() });
httpReq.end();
});
}
app.use('/api', (req, res, next) => {
if (req.session.signedUser || DISABLE_AUTH)
return next();
res.status(401).send('401 Unauthorized');
}, api);
app.get('/*', (req, res, next) => {
const ext = path.extname(req.url);
fs.stat(path.join(__dirname, "app", req.url), (err, stats) => {
let file = "index.html";
if (stats && stats.isFile()) {
file = req.url;
}
res.sendFile(file, { root: path.join(__dirname, "app") }, (err) => {
if (err) {
return next(err);
}
});
});
});
app.use((err: Error, req: express.Request, res: express.Response, next) => {
res.status(500);
return res.json({
ok: false,
message: err.message
});
});
app.listen(SERVER_PORT, () => console.log(`[Mongoku] listening on port ${SERVER_PORT}`));
}
export const start = async () => {
console.log(`[Mongoku] Starting...`);
try {
await factory.load();
setupServer();
} catch (err) {
console.error(err);
process.exit(1);
}
};
if (require.main === module) {
(async () => {
await start();
})();
}