29 lines
921 B
TypeScript
29 lines
921 B
TypeScript
import { rejectionErrorFns } from "../errors"
|
|
import jwtVerifyCatch from "../jwtVerifyCatch"
|
|
import type { IdToken, RawToken } from "./createTokenDB"
|
|
import sendError, { API } from "./sendError"
|
|
import jwt from "jsonwebtoken"
|
|
|
|
async function checkTokenIsValid<T>(
|
|
context: API<T>,
|
|
rawToken: RawToken,
|
|
next: (token: IdToken) => void
|
|
) {
|
|
const { value, type } = rawToken
|
|
|
|
// Verify the token and get the payload
|
|
let data: string | jwt.JwtPayload
|
|
try {
|
|
data = jwt.verify(value, process.env.TOKEN_SECRET as string)
|
|
} catch (err: any) {
|
|
// Deal with the problem in more detail
|
|
return sendError(context, jwtVerifyCatch(type, err))
|
|
}
|
|
// Making sure the token data is not a string (because it should be an object)
|
|
if (typeof data === "string")
|
|
return sendError(context, rejectionErrorFns.tokenWasString(type, value))
|
|
|
|
return next({ id: data.id, type })
|
|
}
|
|
|
|
export default checkTokenIsValid
|