Skip to content

Commit

Permalink
fix: should get undecoded flash message when it is not been base64 en…
Browse files Browse the repository at this point in the history
…code in session
  • Loading branch information
EastSun5566 committed Sep 25, 2024
1 parent d65b423 commit cf7710f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
12 changes: 10 additions & 2 deletions lib/flash.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ function base64Encode(str) {
}

function base64Decode(str) {
return Buffer.from(str, 'base64').toString();
return Buffer.from(str, 'base64').toString('utf-8');
}

function isBase64(str) {
return Buffer.from(str, 'base64').toString('base64') === str;
}

/**
Expand Down Expand Up @@ -87,7 +91,11 @@ function _flash(type, msg) {
delete msgs[type];
// decode msg from base64
if (Array.isArray(arr)) {
return arr.map(base64Decode);
return arr.map((val) => {
// if it is not base64, return it as is
if (!isBase64(val)) return val;
return base64Decode(val);
});
}
return [];
} else {
Expand Down
23 changes: 18 additions & 5 deletions test/flash-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,27 @@ vows.describe('flash').addBatch({
assert.equal(msgs[0], 'Something went wrong');
assert.lengthOf(Object.keys(req.session.flash), 0);
},
'should set/get flash unicode message' : function(err, req, res) {
const count = req.flash('error', 'a Ā 𐀀 文 🦄');
assert.equal(count, 1);
'should be encoded to base64 in session' : function(err, req, res) {
req.flash('error', 'Something went wrong');
assert.equal(req.session.flash.error[0], 'U29tZXRoaW5nIHdlbnQgd3Jvbmc=');
const msgs = req.flash('error');
assert.equal(msgs[0], 'Something went wrong');
},
'should set/get unicode flash message' : function(err, req, res) {
req.flash('error', 'a Ā 𐀀 文 🦄');
assert.equal(req.session.flash.error[0], 'YSDEgCDwkICAIOaWhyDwn6aE');
const msgs = req.flash('error');
assert.lengthOf(msgs, 1);
assert.equal(msgs[0], 'a Ā 𐀀 文 🦄');
assert.lengthOf(Object.keys(req.session.flash), 0);
},
'should get undecoded flash message when it is not been base64 encode in session' : function(err, req, res) {
req.flash('error', 'Something went wrong');
req.session.flash.error.push('Something went wrong');
assert.equal(req.session.flash.error[0], 'U29tZXRoaW5nIHdlbnQgd3Jvbmc=');
assert.equal(req.session.flash.error[1], 'Something went wrong');
console.log(req.session.flash.error);
const msgs = req.flash('error');
assert.equal(msgs[0], 'Something went wrong');
assert.equal(msgs[1], 'Something went wrong');
},
'should set multiple flash messages' : function(err, req, res) {
req.flash('info', 'Welcome');
Expand Down

0 comments on commit cf7710f

Please sign in to comment.