Last active
June 10, 2021 02:43
-
-
Save diasjuniorr/160fe2318bb939eebed0835cd0aa14d0 to your computer and use it in GitHub Desktop.
Next.js high-order function middlewware
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
| // util/middleware/auth.ts | |
| import { NextApiRequest, NextApiResponse } from 'next' | |
| import { User } from './models/user' | |
| // so we can add the user info to the req object | |
| type NextApiRequestWithUser = NextApiRequest & { | |
| user: string | |
| } | |
| export const auth = (handler: (req: NextApiRequestWithUser, res: NextApiResponse) => void) => { | |
| return async (req: NextApiRequest, res: NextApiResponse): Promise<void> => { | |
| const { email, password } = req.body | |
| if (!email || !password) { | |
| return res.status(401).json({message: "missing email or password"}) | |
| } | |
| const user = await User.findOne({ email }) | |
| if (!user) { | |
| return res.status(401).json({ message: "unauthorized" }) | |
| } | |
| const isAllowed = user.authenticate({ user, password }) | |
| if (!isAllowed) { | |
| return res.status(401).json({ message: "unauthorized" }) | |
| } | |
| // if it's successful add the user info to the request object | |
| // let the request get through | |
| req.user = user | |
| return handler(req, res) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment