67 lines
2.0 KiB
JavaScript
67 lines
2.0 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;
|
|
}
|
|
}
|
|
|
|
async function checkUserExistsAD(req, res, next) {
|
|
let userData = await getUserData();
|
|
|
|
if (Array.isArray(req.user)) {
|
|
req.user = req.user.find(u => u._json && u._json.sAMAccountName);
|
|
}
|
|
|
|
if (req.user && req.user._json && req.user._json.sAMAccountName) {
|
|
req.user.name = req.user._json.sAMAccountName;
|
|
}
|
|
|
|
try {
|
|
let users = Array.isArray(userData) ? userData : [];
|
|
|
|
let existingUser;
|
|
if (req.user.name) {
|
|
existingUser = users.find(u => u.name === req.user.name);
|
|
} else if (req.user.id) {
|
|
existingUser = users.find(u => u.id === req.user.id);
|
|
}
|
|
|
|
if (!existingUser) {
|
|
const id = Math.floor(Math.random() * 1e19);
|
|
const newUser = {
|
|
id: id.toString(),
|
|
name: req.user.name || req.user.id,
|
|
role: "user"
|
|
};
|
|
users.push(newUser);
|
|
|
|
try {
|
|
await fs.writeFile(filePath, JSON.stringify(users, null, 2), 'utf8');
|
|
} catch (error) {
|
|
console.error(`Failed to write to ${filePath}: ${error}`);
|
|
return next(error);
|
|
}
|
|
|
|
req.user = newUser;
|
|
req.session.userId = newUser.id;
|
|
} else {
|
|
req.user = existingUser;
|
|
req.session.userId = existingUser.id;
|
|
res.status(200).render('AuthLogin', { isAuthenticated: true, setupData: {}, currentUrl: req.originalUrl, errorMessage: '' });
|
|
}
|
|
|
|
return next();
|
|
} catch (error) {
|
|
return next(error);
|
|
}
|
|
}
|
|
|
|
module.exports = { checkUserExistsAD }; |