Skip to content

Instantly share code, notes, and snippets.

@triblondon
Created June 30, 2017 21:02
Show Gist options
  • Save triblondon/f15908a41c8889bf9625ba9d0ee5d445 to your computer and use it in GitHub Desktop.
Save triblondon/f15908a41c8889bf9625ba9d0ee5d445 to your computer and use it in GitHub Desktop.
Vary middleware
'use strict';
const USER_ID_HEADER = 'Fastly-Auth-UserID';
const RANK_HEADER = 'Fastly-Auth-Rank';
const TOKEN_HEADER = 'Fastly-Auth-Token';
module.exports = () => {
return (req, res, next) => {
const uid = req.get(USER_ID_HEADER);
const rank = req.get(RANK_HEADER);
const token = req.get(TOKEN_HEADER);
req.auth = {
isLoggedIn() {
res.set('vary', RANK_HEADER);
return rank !== undefined && rank !== 'anonymous';
},
getRank() {
res.set('vary', RANK_HEADER);
return rank;
},
getUserId() {
res.set('vary', USER_ID_HEADER);
return uid;
},
getToken() {
res.set('vary', TOKEN_HEADER);
return token;
}
};
next();
};
};
module.exports = () => {
return (req, res, next) => {
const resSet = res.set;
const headers = {
'vary': new Set()
};
const modifyHeader = (name, val, mode) => {
name = name.toLowerCase();
if (name in headers) {
val = Array.isArray(val) ? val : val.split(',');
val.forEach(item => {
headers[name][mode](item.trim().toLowerCase());
});
val = Array.from(headers[name]).join(', ');
}
return val ? resSet.call(res, name, val) : res.removeHeader(name);
};
// Caution: These exported functions use the res scope so
// cannot be implemented as arrow functions
res.set = function (name, val) {
if (arguments.length === 2 && typeof name === 'string') {
return modifyHeader(name, val, 'add');
} else if (arguments.length === 1 && typeof name === 'object') {
Object.keys(name).forEach(key => modifyHeader(key, name[key], 'add'));
} else {
return resSet.call(res, name, val);
}
};
res.unset = function (name, val) {
if (arguments.length === 2 && typeof arguments[0] === 'string') {
return modifyHeader(name, val, 'delete');
} else if (arguments.length === 1 && typeof arguments[0] === 'string') {
return res.removeHeader(name);
}
throw new Error('Invalid call to res.unset');
};
next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment