diff --git a/client/modules/User/actions.js b/client/modules/User/actions.js index 90545b4c..0ba02f0d 100644 --- a/client/modules/User/actions.js +++ b/client/modules/User/actions.js @@ -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( diff --git a/server/controllers/user.controller.js b/server/controllers/user.controller.js index d22b19ae..8243fc8c 100644 --- a/server/controllers/user.controller.js +++ b/server/controllers/user.controller.js @@ -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); }); } diff --git a/server/models/user.js b/server/models/user.js index d15a8930..29e9934f 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -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(); });