Complete backend rework
This commit is contained in:
parent
53d4ab527a
commit
eb09017dab
25 changed files with 958 additions and 866 deletions
|
@ -1,30 +1,34 @@
|
|||
import { Token } from "@prisma/client"
|
||||
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"
|
||||
|
||||
async function checkTokenIsValid<T>(
|
||||
payload: T & { token: string; tokenType: Token["type"] }
|
||||
async function checkTokenIsValid(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
rawToken: [string, TokenType],
|
||||
next: (tokenBody: jwt.JwtPayload) => void
|
||||
) {
|
||||
const { token, tokenType } = payload
|
||||
const [tokenValue, tokenType] = rawToken
|
||||
|
||||
// Verify the token and get the payload
|
||||
let tokenData: string | jwt.JwtPayload
|
||||
try {
|
||||
tokenData = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET as string)
|
||||
tokenData = jwt.verify(
|
||||
tokenValue,
|
||||
process.env.ACCESS_TOKEN_SECRET as string
|
||||
)
|
||||
} catch (err: any) {
|
||||
// Deal with the problem in more detail
|
||||
return Promise.reject(jwtVerifyCatch(tokenType, err))
|
||||
return sendError(req, res, jwtVerifyCatch(tokenType, err))
|
||||
}
|
||||
// Making sure the token data is not a string (because it should be an object)
|
||||
if (typeof tokenData === "string") {
|
||||
return Promise.reject({
|
||||
message: tokenType + "-Token data was a string. Token: " + token,
|
||||
statusCode: 401,
|
||||
solved: false,
|
||||
})
|
||||
}
|
||||
if (typeof tokenData === "string")
|
||||
return sendError(req, res, errors.tokenWasString(tokenType, tokenValue))
|
||||
|
||||
return { ...payload, tokenBody: tokenData, tokenIsValid: true }
|
||||
return next(tokenData)
|
||||
}
|
||||
|
||||
export default checkTokenIsValid
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue