Improved passing of req, res, and tokens
This commit is contained in:
parent
a8e5b57363
commit
39ddf8fde9
17 changed files with 134 additions and 170 deletions
|
@ -1,34 +1,29 @@
|
|||
import { TokenType } from "@prisma/client"
|
||||
import jwt from "jsonwebtoken"
|
||||
import errors from "../errors"
|
||||
import jwtVerifyCatch from "../jwtVerifyCatch"
|
||||
import { NextApiRequest, NextApiResponse } from "next"
|
||||
import sendError from "./sendError"
|
||||
import sendError, { API } from "./sendError"
|
||||
import { IdToken, RawToken } from "./createTokenDB"
|
||||
|
||||
async function checkTokenIsValid(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
rawToken: [string, TokenType],
|
||||
next: (tokenBody: jwt.JwtPayload) => void
|
||||
context: API,
|
||||
rawToken: RawToken,
|
||||
next: (token: IdToken) => void
|
||||
) {
|
||||
const [tokenValue, tokenType] = rawToken
|
||||
const { value, type } = rawToken
|
||||
|
||||
// Verify the token and get the payload
|
||||
let tokenData: string | jwt.JwtPayload
|
||||
let data: string | jwt.JwtPayload
|
||||
try {
|
||||
tokenData = jwt.verify(
|
||||
tokenValue,
|
||||
process.env.ACCESS_TOKEN_SECRET as string
|
||||
)
|
||||
data = jwt.verify(value, process.env.ACCESS_TOKEN_SECRET as string)
|
||||
} catch (err: any) {
|
||||
// Deal with the problem in more detail
|
||||
return sendError(req, res, jwtVerifyCatch(tokenType, err))
|
||||
return sendError(context, jwtVerifyCatch(type, err))
|
||||
}
|
||||
// Making sure the token data is not a string (because it should be an object)
|
||||
if (typeof tokenData === "string")
|
||||
return sendError(req, res, errors.tokenWasString(tokenType, tokenValue))
|
||||
if (typeof data === "string")
|
||||
return sendError(context, errors.tokenWasString(type, value))
|
||||
|
||||
return next(tokenData)
|
||||
return next({ id: data.id, type })
|
||||
}
|
||||
|
||||
export default checkTokenIsValid
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue