Skip to content

Instantly share code, notes, and snippets.

@diasjuniorr
Last active June 10, 2021 02:43
Show Gist options
  • Select an option

  • Save diasjuniorr/160fe2318bb939eebed0835cd0aa14d0 to your computer and use it in GitHub Desktop.

Select an option

Save diasjuniorr/160fe2318bb939eebed0835cd0aa14d0 to your computer and use it in GitHub Desktop.
Next.js high-order function middlewware
// 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