From cf7710faa17bfce8cdd03d4bb92febc1f196cf33 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Wed, 25 Sep 2024 17:30:01 +0800 Subject: [PATCH] fix: should get undecoded flash message when it is not been base64 encode in session --- lib/flash.js | 12 ++++++++++-- test/flash-test.js | 23 ++++++++++++++++++----- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/lib/flash.js b/lib/flash.js index 254b4d9..0bd2fcb 100644 --- a/lib/flash.js +++ b/lib/flash.js @@ -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; } /** @@ -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 { diff --git a/test/flash-test.js b/test/flash-test.js index 2807a1f..1e8ecf5 100644 --- a/test/flash-test.js +++ b/test/flash-test.js @@ -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');