Spaces:
Running
Running
Vyacheslav commited on
Commit ·
9df4ff3
1
Parent(s): 404de5b
optimization
Browse filesFiles changed (5)
1234568 unmodified lines15161718192021222324const jwt = require('jsonwebtoken');const User = require('../models/User');const { JWT_SECRET } = require('../config/env');const authenticateToken = (req, res, next) => {const authHeader = req.headers['authorization'];8 unmodified linesif (!user || user.role === 'banned') return res.status(403).json({ error: 'Banned' });const isValid = Array.isArray(user.sessions) && user.sessions.some(s => s && s.token === token);if (!isValid) return res.status(401).json({ error: 'Session expired' });await User.updateOne({ username, "sessions.token": token },{ $set: { "sessions.$.lastActive": new Date() } });req.user = { ...decoded, username, role: user.role };req.token = token;next();12345678 unmodified lines161718192021222324252627const jwt = require('jsonwebtoken');const User = require('../models/User');const { JWT_SECRET } = require('../config/env');const { shouldUpdateLastActive } = require('../utils/lastActive');const authenticateToken = (req, res, next) => {const authHeader = req.headers['authorization'];8 unmodified linesif (!user || user.role === 'banned') return res.status(403).json({ error: 'Banned' });const isValid = Array.isArray(user.sessions) && user.sessions.some(s => s && s.token === token);if (!isValid) return res.status(401).json({ error: 'Session expired' });if (shouldUpdateLastActive(username, token)) {await User.updateOne({ username, "sessions.token": token },{ $set: { "sessions.$.lastActive": new Date() } });}req.user = { ...decoded, username, role: user.role };req.token = token;next();
8 unmodified lines91011121314151 unmodified line17181920212223248 unmodified linesif (token !== null && token !== '' && (typeof token !== 'string' || token.length > 500 || token.length < 10)) {return res.status(400).json({ error: 'Invalid token' });}const user = await User.findOne({ username: req.user.username });if (!user) return res.status(404).json({ error: 'Not found' });if (user.pushToken && user.pushToken !== token) {const { sendPushNotification } = require('../services/push');1 unmodified linenotification: { title: 'Push Token Changed', body: 'Your notification device was changed. If this was not you, check your account security.' }});}user.pushToken = token || null;await user.save();res.json({ success: true });} catch { res.status(500).send(''); }});8 unmodified lines91011121314151 unmodified line171819202122238 unmodified linesif (token !== null && token !== '' && (typeof token !== 'string' || token.length > 500 || token.length < 10)) {return res.status(400).json({ error: 'Invalid token' });}const user = await User.findOne({ username: req.user.username }).lean();if (!user) return res.status(404).json({ error: 'Not found' });if (user.pushToken && user.pushToken !== token) {const { sendPushNotification } = require('../services/push');1 unmodified linenotification: { title: 'Push Token Changed', body: 'Your notification device was changed. If this was not you, check your account security.' }});}await User.updateOne({ username: req.user.username }, { $set: { pushToken: token || null } });res.json({ success: true });} catch { res.status(500).send(''); }});
10 unmodified lines11121314151617181920212223242510 unmodified lines3637383940414243444546472 unmodified lines50515253545556575859606162636410 unmodified linesif (!password || !panicPassword) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (panicPassword.length < 8 || panicPassword.length > 30) return res.status(400).json({ error: st('Тревожный пароль должен быть от 8 до 30 символов', detectLangReq(req)) });try {const user = await User.findOne({ username: req.user.username });if (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный основной пароль', detectLangReq(req)) });}if (await bcrypt.compare(panicPassword, user.password)) {return res.status(400).json({ error: st('Тревожный пароль не должен совпадать с основным', detectLangReq(req)) });}user.panicPassword = await bcrypt.hash(panicPassword, 10);await user.save();res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});10 unmodified linesif (!password || !twoFactorPassword) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (twoFactorPassword.length < 4 || twoFactorPassword.length > 30) return res.status(400).json({ error: st('2FA пароль должен быть от 4 до 30 символов', detectLangReq(req)) });try {const user = await User.findOne({ username: req.user.username });if (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный основной пароль', detectLangReq(req)) });}user.twoFactorPassword = await bcrypt.hash(twoFactorPassword, 10);await user.save();res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});2 unmodified linesconst { password, twoFactorPassword } = req.body;if (!password || !twoFactorPassword) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });try {const user = await User.findOne({ username: req.user.username });if (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный основной пароль', detectLangReq(req)) });}if (!(await bcrypt.compare(twoFactorPassword, user.twoFactorPassword))) {return res.status(400).json({ error: st('Неверный 2FA пароль', detectLangReq(req)) });}user.twoFactorPassword = null;await user.save();res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});10 unmodified lines11121314151617181920212223242510 unmodified lines3637383940414243444546472 unmodified lines505152535455565758596061626310 unmodified linesif (!password || !panicPassword) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (panicPassword.length < 8 || panicPassword.length > 30) return res.status(400).json({ error: st('Тревожный пароль должен быть от 8 до 30 символов', detectLangReq(req)) });try {const user = await User.findOne({ username: req.user.username }).lean();if (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный основной пароль', detectLangReq(req)) });}if (await bcrypt.compare(panicPassword, user.password)) {return res.status(400).json({ error: st('Тревожный пароль не должен совпадать с основным', detectLangReq(req)) });}const hashed = await bcrypt.hash(panicPassword, 10);await User.updateOne({ username: req.user.username }, { $set: { panicPassword: hashed } });res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});10 unmodified linesif (!password || !twoFactorPassword) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (twoFactorPassword.length < 4 || twoFactorPassword.length > 30) return res.status(400).json({ error: st('2FA пароль должен быть от 4 до 30 символов', detectLangReq(req)) });try {const user = await User.findOne({ username: req.user.username }).lean();if (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный основной пароль', detectLangReq(req)) });}const hashed = await bcrypt.hash(twoFactorPassword, 10);await User.updateOne({ username: req.user.username }, { $set: { twoFactorPassword: hashed } });res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});2 unmodified linesconst { password, twoFactorPassword } = req.body;if (!password || !twoFactorPassword) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });try {const user = await User.findOne({ username: req.user.username }).lean();if (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный основной пароль', detectLangReq(req)) });}if (!(await bcrypt.compare(twoFactorPassword, user.twoFactorPassword))) {return res.status(400).json({ error: st('Неверный 2FA пароль', detectLangReq(req)) });}await User.updateOne({ username: req.user.username }, { $set: { twoFactorPassword: null } });res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});
2 unmodified lines34567810 unmodified lines192021222324252627282 unmodified linesconst { JWT_SECRET } = require('../config/env');const { checkServerPrivacy } = require('../middleware/privacyWrapper');const { st, detectLang } = require('../constants/translations');const socketAuthMiddleware = (socket, next) => {const token = socket.handshake.auth?.token;10 unmodified linessocket.username = username;socket.userTokenData = { ...decoded, username, role: user.role };socket.authToken = token;await User.updateOne({ username, "sessions.token": token },{ $set: { "sessions.$.lastActive": new Date() } });next();} catch {next(new Error('Server error'));2 unmodified lines345678910 unmodified lines2021222324252627282930312 unmodified linesconst { JWT_SECRET } = require('../config/env');const { checkServerPrivacy } = require('../middleware/privacyWrapper');const { st, detectLang } = require('../constants/translations');const { shouldUpdateLastActive } = require('../utils/lastActive');const socketAuthMiddleware = (socket, next) => {const token = socket.handshake.auth?.token;10 unmodified linessocket.username = username;socket.userTokenData = { ...decoded, username, role: user.role };socket.authToken = token;if (shouldUpdateLastActive(username, token)) {await User.updateOne({ username, "sessions.token": token },{ $set: { "sessions.$.lastActive": new Date() } });}next();} catch {next(new Error('Server error'));
12345678910111213const lastActiveCache = new Map();const THROTTLE_MS = 5 * 60 * 1000;
const shouldUpdateLastActive = (username, token) => { const key = `${username}:${token}`; const now = Date.now(); const last = lastActiveCache.get(key); if (last && now - last < THROTTLE_MS) return false; lastActiveCache.set(key, now); return true;};
module.exports = { shouldUpdateLastActive };middleware/authenticateToken.js+7-4
routes/push.js+2-3
routes/security.js+8-9
socket/middleware.js+7-4
utils/lastActive.jsAdded+13