Last active
July 20, 2021 13:16
-
-
Save merlinsbeard/e7a787e7e2aca643f204d8aadb83daf5 to your computer and use it in GitHub Desktop.
middleware-sample
This file contains hidden or 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
| import { Request, NextFunction } from 'express' | |
| import grabUser from '../helpers/grabUser' | |
| export const userRequired = async (req: Request, res, next: NextFunction) => { | |
| const authorization = req.headers.authorization | |
| if (authorization == null || authorization === '') { | |
| return res.status(401).send({ msg: 'Authorization header required' }) | |
| } | |
| try { | |
| const u = await grabUser(authorization) | |
| if (u.error) { | |
| return res.status(u.status).json({ error: u.error.data }) | |
| } | |
| req.body.user = u.data | |
| } catch (error) { | |
| return res.status(500).json({ msg: error }) | |
| } | |
| next() | |
| } | |
| export const permissionRequired = (permission: string) => { | |
| return (req, res, next: NextFunction) => { | |
| if (req.body?.user == null) { | |
| return res.status(401).send({ error: 'Authentication Required' }) | |
| } | |
| if (req.body.user.is_superuser) { | |
| return next() | |
| } else { | |
| const user = req.body.user | |
| if (user.permissions.includes(permission) === false) { | |
| return res.status(401).send({ error: 'permission denied' }) | |
| } | |
| next() | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment