vybe/src/event/authenticate.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-04-21 23:31:37 -07:00
const db = require('../db');
const openpgp = require('openpgp');
2023-05-07 18:43:57 -07:00
2023-05-28 14:56:08 -07:00
const authenticate = async (msg, respond, socket, io) => {
2024-03-18 23:07:48 -07:00
if (!msg.name || !msg.message) {
return respond({
success: false,
2024-04-21 23:31:37 -07:00
message: 'invalid message'
2024-03-18 23:07:48 -07:00
});
}
2024-04-21 23:31:37 -07:00
const result = await db.query('select * from user where name = ?', [
msg.name
2024-03-18 23:07:48 -07:00
]);
if (result.rows.length === 0) {
return respond({
success: false,
2024-04-21 23:31:37 -07:00
message: 'user not found'
2024-03-18 23:07:48 -07:00
});
}
try {
const key = await openpgp.readKey({ armoredKey: result.rows[0].pubkey });
const verification = await openpgp.verify({
message: await openpgp.readCleartextMessage({
cleartextMessage: msg.message,
}),
verificationKeys: key,
2024-04-21 23:31:37 -07:00
expectSigned: true
2024-03-18 23:07:48 -07:00
});
2024-04-21 23:31:37 -07:00
const data = verification.data.split(' ');
if (data[0] !== 'vybe_auth') {
2024-03-18 23:07:48 -07:00
return respond({
success: false,
2024-04-21 23:31:37 -07:00
message: 'bad auth message'
2024-03-18 23:07:48 -07:00
});
}
const auths = await db.query(
2024-04-21 23:31:37 -07:00
'select * from authentication where user = ? and salt = ?',
2024-03-18 23:07:48 -07:00
[result.rows[0].id, data[1]]
);
if (auths.rows.length === 0) {
2024-04-21 23:31:37 -07:00
await db.query('insert into authentication (user, salt) values (?, ?)', [
2024-03-18 23:07:48 -07:00
result.rows[0].id,
2024-04-21 23:31:37 -07:00
data[1]
2024-03-18 23:07:48 -07:00
]);
socket.username = msg.name;
if (io.cache[msg.name]) {
io.cache[msg.name].push(socket.id);
} else {
io.cache[msg.name] = [socket.id];
}
return respond({
success: true,
});
} else {
return respond({
success: false,
2024-04-21 23:31:37 -07:00
message: 'already authenticated with this message'
2024-03-18 23:07:48 -07:00
});
}
} catch (err) {
2024-04-21 23:31:37 -07:00
console.error('error in authentication: ' + err);
2024-03-18 23:07:48 -07:00
return respond({
success: false,
2024-04-21 23:31:37 -07:00
message: 'message signature verification failed'
2024-03-18 23:07:48 -07:00
});
}
2023-05-07 18:43:57 -07:00
};
module.exports = authenticate;