-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathdatabase.js
274 lines (225 loc) · 6.49 KB
/
database.js
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const joi = require('joi');
const util = require('./util');
const { PNID } = require('./models/pnid');
const { Server } = require('./models/server');
const logger = require('../logger');
const { config } = require('./config-manager');
const { connection_string, options } = config.mongoose;
// TODO: Extend this later with more settings
const discordConnectionSchema = joi.object({
id: joi.string()
});
let connection;
async function connect() {
await mongoose.connect(connection_string, options);
connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
module.exports.connection = connection;
}
function verifyConnected() {
if (!connection) {
throw new Error('Cannot make database requets without being connected');
}
}
async function getUserByUsername(username) {
verifyConnected();
if (typeof username !== 'string') {
return null;
}
const user = await PNID.findOne({
usernameLower: username.toLowerCase()
});
return user;
}
async function getUserByPID(pid) {
verifyConnected();
const user = await PNID.findOne({
pid
});
return user;
}
async function getUserByEmailAddress(email) {
verifyConnected();
const user = await PNID.findOne({
'email.address': new RegExp(email, 'i') // * Ignore case
});
return user;
}
async function doesUserExist(username) {
verifyConnected();
return !!await getUserByUsername(username);
}
async function getUserBasic(token) {
verifyConnected();
// Wii U sends Basic auth as `username password`, where the password may not have spaces
// This is not to spec, but that is the consoles fault not ours
const [username, password] = Buffer.from(token, 'base64').toString().split(' ');
const user = await getUserByUsername(username);
if (!user) {
return null;
}
const hashedPassword = util.nintendoPasswordHash(password, user.pid);
if (!bcrypt.compareSync(hashedPassword, user.password)) {
return null;
}
return user;
}
async function getUserBearer(token) {
verifyConnected();
try {
const decryptedToken = await util.decryptToken(Buffer.from(token, 'base64'));
const unpackedToken = util.unpackToken(decryptedToken);
const user = await getUserByPID(unpackedToken.pid);
if (user) {
const expireTime = Math.floor((Number(unpackedToken.expire_time) / 1000));
if (Math.floor(Date.now() / 1000) > expireTime) {
return null;
}
}
return user;
} catch (error) {
// TODO: Handle error
logger.error(error);
return null;
}
}
async function getUserProfileJSONByPID(pid) {
verifyConnected();
const user = await getUserByPID(pid);
const device = user.get('devices')[0]; // Just grab the first device
let device_attributes;
if (device) {
device_attributes = device.get('device_attributes').map(({name, value, created_date}) => {
const deviceAttributeDocument = {
name,
value
};
if (created_date) {
deviceAttributeDocument.created_date = created_date;
}
return {
device_attribute: deviceAttributeDocument
};
});
}
const userObject = {
//accounts: {}, We need to figure this out, no idea what these values mean or what they do
active_flag: user.get('flags.active') ? 'Y' : 'N',
birth_date: user.get('birthdate'),
country: user.get('country'),
create_date: user.get('creation_date'),
device_attributes: device_attributes,
gender: user.get('gender'),
language: user.get('language'),
updated: user.get('updated'),
marketing_flag: user.get('flags.marketing') ? 'Y' : 'N',
off_device_flag: user.get('flags.off_device') ? 'Y' : 'N',
pid: user.get('pid'),
email: {
address: user.get('email.address'),
id: user.get('email.id'),
parent: user.get('email.parent') ? 'Y' : 'N',
primary: user.get('email.primary') ? 'Y' : 'N',
reachable: user.get('email.reachable') ? 'Y' : 'N',
type: 'DEFAULT',
updated_by: 'USER', // Can also be INTERNAL WS, don't know the difference
validated: user.get('email.validated') ? 'Y' : 'N'
},
mii: {
status: 'COMPLETED',
data: user.get('mii.data').replace(/(\r\n|\n|\r)/gm, ''),
id: user.get('mii.id'),
mii_hash: user.get('mii.hash'),
mii_images: {
mii_image: {
// Images MUST be loaded over HTTPS or console ignores them
// Bunny CDN is the only CDN which seems to support TLS 1.0/1.1 (required)
cached_url: `${config.cdn.base_url}/mii/${user.pid}/standard.tga`,
id: user.get('mii.image_id'),
url: `${config.cdn.base_url}/mii/${user.pid}/standard.tga`,
type: 'standard'
}
},
name: user.get('mii.name'),
primary: user.get('mii.primary') ? 'Y' : 'N',
},
region: user.get('region'),
tz_name: user.get('timezone.name'),
user_id: user.get('username'),
utc_offset: user.get('timezone.offset')
};
if (user.get('email.validated')) {
userObject.email.validated_date = user.get('email.validated_date');
}
return userObject;
}
function getServer(gameServerId, accessMode) {
return Server.findOne({
game_server_id: gameServerId,
access_mode: accessMode,
});
}
function getServerByTitleId(titleId, accessMode) {
return Server.findOne({
title_ids: titleId,
access_mode: accessMode,
});
}
async function addUserConnection(pnid, data, type) {
if (type === 'discord') {
return await addUserConnectionDiscord(pnid, data);
}
}
async function addUserConnectionDiscord(pnid, data) {
const valid = discordConnectionSchema.validate(data);
if (valid.error) {
return {
app: 'api',
status: 400,
error: 'Invalid or missing connection data'
};
}
await PNID.updateOne({ pid: pnid.get('pid') }, {
$set: {
'connections.discord.id': data.id
}
});
return {
app: 'api',
status: 200
};
}
async function removeUserConnection(pnid, type) {
// Add more connections later?
if (type === 'discord') {
return await removeUserConnectionDiscord(pnid);
}
}
async function removeUserConnectionDiscord(pnid) {
await PNID.updateOne({ pid: pnid.get('pid') }, {
$set: {
'connections.discord.id': ''
}
});
return {
app: 'api',
status: 200
};
}
module.exports = {
connect,
connection,
getUserByUsername,
getUserByPID,
getUserByEmailAddress,
doesUserExist,
getUserBasic,
getUserBearer,
getUserProfileJSONByPID,
getServer,
getServerByTitleId,
addUserConnection,
removeUserConnection,
};