Files
OLD-server-architecture/realtime/src/routes/connect.js

36 lines
1.1 KiB
JavaScript

const router = require('express').Router();
const db = require('../store/db');
const crypto = require('crypto');
router.post('/connect/new', async (req, res) => {
const { name, code } = req.body;
if (!name || !code) {
return res.status(400).json({ error: 'name and code are required' });
}
if (code.length < 6) {
return res.status(400).json({ error: 'code must be at least 6 characters' });
}
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.scryptSync(code, salt, 64).toString('hex');
const codeHash = `${salt}:${hash}`;
try {
await db.query('sensors',
'INSERT INTO sensors (name, code_hash) VALUES ($1, $2)',
[name, codeHash]
);
res.status(201).json({ status: 'ok' });
} catch (err) {
if (err.code === '23505') {
return res.status(409).json({ error: 'name already exists' });
}
console.error('Error creating sensor', err);
res.status(500).json({ error: 'internal server error' });
}
});
module.exports = router;