Skip to content

Instantly share code, notes, and snippets.

@mpaccione
Created August 18, 2021 03:21
Show Gist options
  • Save mpaccione/02ea5f1502540ca9a46a75966817e307 to your computer and use it in GitHub Desktop.
Save mpaccione/02ea5f1502540ca9a46a75966817e307 to your computer and use it in GitHub Desktop.
cookie.js
router.post('/cookie', (req, res) => {
const localhost = req.headers.referer.includes('localhost');
const decodedJWT = jwt_decode(req.body.token);
let expiration = decodedJWT.expiration;
expiration = Number(expiration);
expiration =
typeof expiration === 'number' && expiration > Date.now()
? expiration
: new Date(Date.now() + TEN_HOURS);
res.cookie('c', req.body.token, {
httpOnly: localhost ? false : true,
secure: true,
expires: expiration,
sameSite: 'none',
hostOnly: true,
path: '/'
});
res.json({ token: req.body.token });
});
router.get('/cookie', (req, res) => {
const cookie = req.cookies && req.cookies['c'] ? req.cookies['c'] : undefined;
res.json({ token: cookie });
});
router.get('/cookie/delete', (req, res) => {
console.log('==============');
console.log(req.get('host'));
let host = req.get('host');
const portIndex = host.indexOf(':');
const cookieDomain =
host.includes('localhost') || host.includes('127.0.0.1') ? host.substring(0, portIndex) : host;
console.log(cookieDomain);
res.clearCookie('c', {
httpOnly: host.includes('localhost') ? false : true,
secure: true,
domain: cookieDomain,
sameSite: 'none',
hostOnly: true,
path: '/'
});
res.send(200).end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment