Skip to content
This repository has been archived by the owner on Nov 21, 2020. It is now read-only.

Commit

Permalink
fix: add user middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
munkhorgil authored Apr 5, 2020
1 parent b5548ba commit 71d7a4d
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { initRedis } from './redisClient';
import initSmooch from './smooch/controller';
import { init } from './startup';
import initTwitter from './twitter/controller';
import userMiddleware from './userMiddleware';
import initDaily from './videoCall/controller';
import initWhatsapp from './whatsapp/controller';

Expand All @@ -33,6 +34,8 @@ const rawBodySaver = (req, _res, buf, encoding) => {
app.use(bodyParser.urlencoded({ limit: '10mb', verify: rawBodySaver, extended: true }));
app.use(bodyParser.json({ limit: '10mb', verify: rawBodySaver }));

app.use(userMiddleware);

// Intentionally placing this route above raw bodyParser
// File upload in nylas controller is not working with rawParser
initNylas(app);
Expand Down
27 changes: 27 additions & 0 deletions src/redisClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,33 @@ export const getArray = async (key: string): Promise<any> => {
return JSON.parse(value);
};

/*
* Check if value exists in set
*/
export const inArray = async (setKey: string, setMember: string): Promise<any> => {
try {
const response = await new Promise((resolve, reject) => {
client.sismember(setKey, setMember, (error, reply) => {
if (error) {
return reject(error);
}

return resolve(reply);
});
});

return response;

// handle already stored invalid type error
} catch (e) {
if (e.message.includes('WRONGTYPE')) {
client.del(setKey);
}

return false;
}
};

/*
* Set array
*/
Expand Down
29 changes: 29 additions & 0 deletions src/userMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { inArray } from './redisClient';

const EXCLUDE_PATH = ['/nylas/webhook', '/nylas/auth/callback', '/nylas/oauth2/callback', '/gmaillogin'];

const userMiddleware = async (req, _res, next) => {
const { path, headers, query } = req;

if (EXCLUDE_PATH.includes(path)) {
return next();
}

if (path.startsWith('/gmail') || path.startsWith('/accounts') || path.startsWith('/nylas')) {
try {
const userId = headers.userid || query.userId;

if (await inArray('userIds', userId)) {
return next();
}

next(new Error('User not authorized'));
} catch (e) {
next(e);
}
}

next();
};

export default userMiddleware;

0 comments on commit 71d7a4d

Please sign in to comment.