Last active
October 9, 2021 00:33
-
-
Save jeremybradbury/8f754c9d54d97fb4960737c26a72fee7 to your computer and use it in GitHub Desktop.
This header can be spoofed, but it can at least block browser calls to your endpoints that are used for for apps only. Don't use this alone, ensure you also have authorization.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// blacklist Mozilla/Opera (all browsers) prefix, with optional overrides | |
export const noBrowsersMiddleware = async (req, res, next) => { | |
const client = req.headers["user-agent"]; | |
switch (true) { // yeah it's still faster than if/else | |
// optional overrrides by platform | |
// mobile / tablet | |
//case client.includes('Android') && !client.includes('Windows'): | |
//case client.includes('iPhone'): | |
//case client.includes('Windows Phone'): | |
// desktop / laptop | |
//case client.includes('CrOS'): | |
//case client.includes('Linux') && !client.includes('Android'): | |
//case client.includes('Macintosh'): | |
//case client.includes('Windows 10'): | |
// next(); // uncomment these lines if you use overrides above | |
// break; // uncomment these lines if you use overrides above | |
// see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent | |
// and: https://webaim.org/blog/user-agent-string-history/ | |
// for how/why this works | |
case client.startsWith('Mozilla'): | |
case client.startsWith('Opera'): | |
res.sendStatus(418); // no coffee for you | |
break; | |
default: next(); | |
} | |
}; | |
// whitelist custom User-Agent headers | |
export const onlyAppsMiddleware = async (req, res, next) => { | |
const client = req.headers["user-agent"]; | |
switch (true) { // my favorite coding trick: just move the conditions to cases | |
case client.startsWith('MyAndroidAppName'): | |
case client.startsWith('MyIOSAppName'): | |
case client.startsWith('MyMacAppName'): | |
case client.startsWith('MyWindowsAppName'): | |
case client.startsWith('MyLinuxAppName'): | |
next(); | |
break; | |
default: res.sendStatus(418); // no coffee for you | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment