66 lines
2.4 KiB
JavaScript
66 lines
2.4 KiB
JavaScript
const crypto = require('crypto');
|
|
const database = require("../db");
|
|
const authentication = require("../authentication");
|
|
|
|
const accountController = {
|
|
getCookie: (req, res) => {
|
|
console.log("site loaded")
|
|
console.log(req.cookies)
|
|
let cookie = req.cookies.user;
|
|
if (!cookie) {
|
|
//crypto.randomBytes() instead of Math.random() for cryptographically secure random numbers
|
|
let randomBuffer = crypto.randomBytes(16); // 128bits of entropy
|
|
let randomNumber = randomBuffer.toString('hex');
|
|
let options = {
|
|
maxAge: 86400000, // 1 day
|
|
httpOnly: true
|
|
}
|
|
// Set cookie
|
|
res.cookie("user", randomNumber, options);
|
|
console.log("cookie set");
|
|
}
|
|
res.redirect('/');
|
|
},
|
|
register: async (req, res) => {
|
|
try {
|
|
const { sharedSecret, publicKey } = req.body;
|
|
if (!sharedSecret || !publicKey) {
|
|
return res.status(400).json({ error: "Missing sharedSecret or publicKey" });
|
|
}
|
|
console.log('Received data:', { sharedSecret, publicKey });
|
|
if (authentication.checkSharedSecret(sharedSecret)) {
|
|
database.addUser(publicKey);
|
|
} else {
|
|
return res.status(400).json({ error: "Wrong sharedSecret" });
|
|
}
|
|
return res.status(201).json({ message: "Registration successful" });
|
|
} catch (error) {
|
|
console.error("Error during registration:", error);
|
|
return res.status(500).json({ error: "Server error during registration" });
|
|
}
|
|
},
|
|
loginGetChallenge: async (req, res) => {
|
|
let randomBuffer = crypto.randomBytes(16);
|
|
let randomNumber = randomBuffer.toString('hex');
|
|
req.session.randomNumber = randomNumber;
|
|
return res.status(200).json({
|
|
message: "Challenge generated successfully",
|
|
challenge: randomNumber
|
|
});
|
|
},
|
|
loginVerifyChallenge: async (req, res) => {
|
|
const { signature } = req.body;
|
|
const publicKeys = await database.getPublicKeys();
|
|
const msg = new TextEncoder().encode(req.session.randomNumber);
|
|
const sig = new TextEncoder().encode(signature);
|
|
let validKey = authentication.verifySignature(msg, sig, publicKeys);
|
|
if (validKey !== null) {
|
|
return res.status(200).json({ message: "Challenge solved successfully" });
|
|
} else {
|
|
return res.status(400).json({ error: "Challenge failed" });
|
|
}
|
|
}
|
|
};
|
|
|
|
module.exports = accountController;
|