67 lines
1.6 KiB
JavaScript
67 lines
1.6 KiB
JavaScript
const fs = require('fs').promises;
|
|
const path = require('path');
|
|
|
|
const filePath = path.join(__dirname, '../data/user.json');
|
|
|
|
async function getUserData() {
|
|
try {
|
|
const fileContent = await fs.readFile(filePath, 'utf8');
|
|
return JSON.parse(fileContent);
|
|
} catch (err) {
|
|
console.error(`Failed to read from ${filePath}: ${err}`);
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
let userData;
|
|
|
|
(async () => {
|
|
try {
|
|
userData = await getUserData();
|
|
} catch (err) {
|
|
console.error(`Failed to initialize userData: ${err}`);
|
|
process.exit(1);
|
|
}
|
|
})();
|
|
|
|
async function checkUserExistsDiscord(req, res, next) {
|
|
if (!req.user || (!req.user.username && !req.user.id)) {
|
|
return res.status(500).send('Internal Server Error');
|
|
}
|
|
|
|
try {
|
|
let userData = await getUserData();
|
|
|
|
let existingUser;
|
|
if (req.user.username) {
|
|
existingUser = userData.find(u => u.name === req.user.username);
|
|
} else if (req.user.id) {
|
|
existingUser = userData.find(u => u.id === req.user.id);
|
|
}
|
|
|
|
if (existingUser) {
|
|
req.user.id = existingUser.id;
|
|
return res.redirect('/dpanel/dashboard');
|
|
}
|
|
|
|
const newUser = {
|
|
id: req.user.id,
|
|
name: req.user.username,
|
|
role: "user"
|
|
};
|
|
|
|
userData.push(newUser);
|
|
|
|
await fs.writeFile(filePath, JSON.stringify(userData, null, 2), 'utf8');
|
|
|
|
req.user.id = newUser.id;
|
|
|
|
return next();
|
|
} catch (error) {
|
|
return next(error);
|
|
}
|
|
}
|
|
|
|
|
|
module.exports = { checkUserExistsDiscord };
|