-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
100 lines (93 loc) · 4.32 KB
/
index.ts
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
import * as cookieParser from 'cookie-parser';
import { config } from 'dotenv';
import { HttpRequest, initialize } from 'express-hibernate-wrapper';
import { load, save, updateDatabase } from 'hibernatets';
import { v4 as uuid } from 'uuid';
import { MessageCommunciation } from './resources/mapserver/message-communication';
import { User } from './resources/mapserver/user/user';
import "./util/fetch";
config({
path: __dirname + '/.env'
});
updateDatabase(__dirname + '/resources')
.then(() => {
initialize(__dirname + '/resources', {
allowCors: true,
prereesources: app => {
app.use(cookieParser());
app.use(async (req: HttpRequest<User>, res, next) => {
if (req.path == "/rest/users") {
next();
return;
}
const deepSettings = {
first: true as const,
deep: {
friends: 'TRUE=TRUE',
friendedUser: {
depths: 4,
filter: 'TRUE=TRUE'
},
attributes: 'TRUE=TRUE',
inventory: 'TRUE=TRUE'
}
};
if (req.attributes?.needsUser !== false) {
if (!req.user && req.cookies.user) {
try {
req.user = await load(User, `cookie = ?`, [req.cookies.user], deepSettings);
} catch (e) {
console.error(e);
}
}
if (!req.user && !req.cookies.user && req.query.pusheruuid) {
try {
req.user = await load(User, `pusherUuid = ?`, [`${req.query.pusheruuid}`], deepSettings);
if (req.user) {
res.cookie('user', req.user.cookie, {
expires: new Date(Date.now() + (1000 * 60 * 60 * 24 * 400)),
httpOnly: true,
secure: true,
sameSite: 'none'
});
}
} catch (e) {
console.error(e);
}
}
if (!req.user && !req.cookies.user) {
if (req.method !== 'GET' && req.method !== 'HEAD' || req.path.endsWith('/message.html') || req.attributes?.needsUser == true) {
console.log(`createing new user at ${req.path} with ${req.method}`);
req.user = new User(uuid());
await save(req.user);
res.cookie('user', req.user.cookie, {
expires: new Date(Date.now() + (1000 * 60 * 60 * 24 * 400)),
httpOnly: true,
secure: true,
sameSite: 'none'
});
} else {
if (!req.path.endsWith('.png')) {
console.log(`didnt set cookies for ${req.path}`);
}
}
} else {
if (req.user && !req.user.referenceUuid) {
req.user.referenceUuid = uuid();
}
if (MessageCommunciation.websockets[req.user.id]) {
MessageCommunciation.websockets[req.user.id].user = req.user;
}
}
} else {
console.log("doesnt need user");
}
next();
});
},
public: __dirname + '/public'
})
.then(() => {
console.log('started');
});
});