Hashing keys before storing them

This commit is contained in:
Vertmo 2018-11-06 13:36:19 +01:00 committed by Cassie Tarakajian
parent 78695d3983
commit 3b55ff81d2
3 changed files with 28 additions and 5 deletions

View file

@ -226,8 +226,8 @@ export function addApiKey(label) {
return ((dispatch) => {
crypto.randomBytes(20, (err, buf) => {
const key = buf.toString('hex');
const hashedKey = Buffer.from(key).toString('base64');
axios.put(`${ROOT_URL}/account/api-keys`, { label, hashedKey }, { withCredentials: true })
const encodedKey = Buffer.from(key).toString('base64');
axios.put(`${ROOT_URL}/account/api-keys`, { label, encodedKey }, { withCredentials: true })
.then((response) => {
// window.alert(`Here is your key :\n${key}\nNote it somewhere, you won't be able to see it later !`);
const elt = React.createElement(

View file

@ -363,11 +363,11 @@ export function addApiKey(req, res) {
res.status(404).json({ error: 'User not found' });
return;
}
if (!req.body.label || !req.body.hashedKey) {
res.status(400).json({ error: 'Expected field \'label\' or \'hashedKey\' was not present in request body' });
if (!req.body.label || !req.body.encodedKey) {
res.status(400).json({ error: 'Expected field \'label\' or \'encodedKey\' was not present in request body' });
return;
}
user.apiKeys.push(req.body);
user.apiKeys.push({ label: req.body.label, hashedKey: req.body.encodedKey });
saveUser(res, user);
});
}

View file

@ -68,6 +68,29 @@ userSchema.pre('save', function checkPassword(next) { // eslint-disable-line con
});
});
/**
* API keys hash middleware
*/
userSchema.pre('save', function checkApiKey(next) {
const user = this;
if (!user.isModified('apiKeys')) { return next(); }
let hasNew = false;
user.apiKeys.forEach((k) => {
if (k.isNew) {
hasNew = true;
bcrypt.genSalt(10, (err, salt) => {
if (err) { return next(err); }
bcrypt.hash(k.hashedKey, salt, null, (innerErr, hash) => {
if (innerErr) { return next(innerErr); }
k.hashedKey = hash;
return next();
});
});
}
});
if (!hasNew) return next();
});
userSchema.virtual('id').get(function idToString() {
return this._id.toHexString();
});