Skip to content

Commit

Permalink
route protect
Browse files Browse the repository at this point in the history
  • Loading branch information
Hendrixer committed Dec 14, 2021
1 parent 10100ed commit 58b14a7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import jwt from 'jsonwebtoken'
import { NextApiRequest, NextApiResponse } from 'next'
import prisma from './prisma'

export const validateRoute = (handler) => {
return async (req: NextApiRequest, res: NextApiResponse) => {
const token = req.cookies.TRAX_ACCESS_TOKEN

if (token) {
let user

try {
const { id } = jwt.verify(token, 'hello')
user = await prisma.user.findUnique({
where: { id },
})

if (!user) {
throw new Error('Not real user')
}
} catch (error) {
res.status(401)
res.json({ error: 'Not Authorizied' })
return
}

return handler(req, res, user)
}

res.status(401)
res.json({ error: 'Not Authorizied' })
}
}
5 changes: 5 additions & 0 deletions pages/api/me.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { validateRoute } from '../../lib/auth'

export default validateRoute((req, res, user) => {
res.json(user)
})

0 comments on commit 58b14a7

Please sign in to comment.