78 lines
2.9 KiB
JavaScript
78 lines
2.9 KiB
JavaScript
const router = require('express').Router();
|
|
const auth = require('../core/auth.core');
|
|
const userAuth = require('../middlewares/user.security');
|
|
const internalAuth = require('../middlewares/internal.security');
|
|
|
|
const USERNAME_REGEX = /^[a-zA-Z0-9_.\-]{3,50}$/;
|
|
const TELEGRAM_REGEX = /^[0-9]{5,15}$/;
|
|
|
|
// ─── SERVICE-TO-SERVICE (x-internal-api-key) ────────────────────────
|
|
|
|
router.get('/', internalAuth, async (req, res) => {
|
|
try {
|
|
const users = await auth.getAllUsers();
|
|
res.json(users);
|
|
} catch (err) {
|
|
console.error('[USERS] list:', err.message);
|
|
res.status(500).json({ error: 'internal' });
|
|
}
|
|
});
|
|
|
|
router.get('/tonotify', internalAuth, async (req, res) => {
|
|
try {
|
|
const users = await auth.getUsersToNotify();
|
|
res.json(users);
|
|
} catch (err) {
|
|
console.error('[USERS] tonotify:', err.message);
|
|
res.status(500).json({ error: 'internal' });
|
|
}
|
|
});
|
|
|
|
// ─── USER AUTH (cookie/JWT) ─────────────────────────────────────────
|
|
|
|
router.use(userAuth);
|
|
|
|
router.get('/me', async (req, res) => {
|
|
try {
|
|
const user = await auth.getUserById(req.user.user_id);
|
|
if (!user) return res.status(404).json({ error: 'user_not_found' });
|
|
res.json(user);
|
|
} catch (err) {
|
|
console.error('[USERS] me:', err.message);
|
|
res.status(500).json({ error: 'internal' });
|
|
}
|
|
});
|
|
|
|
router.put('/me/username', async (req, res) => {
|
|
const newUsername = req.body?.newUsername || req.query.newUsername;
|
|
if (!newUsername || typeof newUsername !== 'string' || !USERNAME_REGEX.test(newUsername)) {
|
|
return res.status(400).json({ error: 'invalid_username' });
|
|
}
|
|
try {
|
|
const updated = await auth.updateUsername(req.user.user_id, newUsername);
|
|
if (!updated) return res.status(404).json({ error: 'user_not_found' });
|
|
res.json({ success: true, username: updated.username });
|
|
} catch (err) {
|
|
if (err.code === '23505') return res.status(409).json({ error: 'username_taken' });
|
|
console.error('[USERS] update username:', err.message);
|
|
res.status(500).json({ error: 'internal' });
|
|
}
|
|
});
|
|
|
|
router.put('/me/telegram', async (req, res) => {
|
|
const telegramId = req.body?.telegramId || req.query.telegramId;
|
|
if (!telegramId || typeof telegramId !== 'string' || !TELEGRAM_REGEX.test(telegramId)) {
|
|
return res.status(400).json({ error: 'invalid_telegram_id' });
|
|
}
|
|
try {
|
|
await auth.updateTelegram(req.user.user_id, telegramId);
|
|
res.json({ success: true });
|
|
} catch (err) {
|
|
if (err.code === '23505') return res.status(409).json({ error: 'telegram_taken' });
|
|
console.error('[USERS] update telegram:', err.message);
|
|
res.status(500).json({ error: 'internal' });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|