Ghost/core/server/models/single-use-token.js
Rishabh Garg 7182efdb88
🐛 Fixed special chars in single use token (#12290)
no refs

- The token generation logic for single use token was replacing only the first instance of + or / to make the token URL safe, instead of replacing all instances which caused a bug where token was not validated properly in case it included multiple + or / in it.

- The fix ensures replacing all the + or / in the token with URL safe _ or - so it can be properly validated via magic link
2020-10-20 11:49:20 +05:30

46 lines
1.3 KiB
JavaScript

const ghostBookshelf = require('./base');
const crypto = require('crypto');
const SingleUseToken = ghostBookshelf.Model.extend({
tableName: 'tokens',
defaults() {
return {
token: crypto
.randomBytes(192 / 8)
.toString('base64')
// base64url encoding means the tokens are URL safe
.replace(/\+/g, '-')
.replace(/\//g, '_')
};
}
}, {
async findOne(data, unfilteredOptions = {}) {
if (!unfilteredOptions.transacting) {
return ghostBookshelf.transaction((transacting) => {
return this.findOne(data, Object.assign({transacting}, unfilteredOptions));
});
}
const model = await ghostBookshelf.Model.findOne.call(this, data, unfilteredOptions);
if (model) {
await this.destroy(Object.assign({
destroyBy: {
id: model.id
}
}, unfilteredOptions));
}
return model;
}
});
const SingleUseTokens = ghostBookshelf.Collection.extend({
model: SingleUseToken
});
module.exports = {
SingleUseToken: ghostBookshelf.model('SingleUseToken', SingleUseToken),
SingleUseTokens: ghostBookshelf.collection('SingleUseTokens', SingleUseTokens)
};