chore: Update auth flow (#9959)

This commit is contained in:
Oli Juhl
2024-11-06 21:21:45 +01:00
committed by GitHub
parent 505768dd9f
commit 441004cc21
3 changed files with 41 additions and 5 deletions
@@ -5,7 +5,11 @@ import {
MedusaResponse,
} from "@medusajs/framework/http"
import { ConfigModule, IAuthModuleService } from "@medusajs/framework/types"
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
import {
ContainerRegistrationKeys,
MedusaError,
Modules,
} from "@medusajs/framework/utils"
import { decode, JwtPayload, verify } from "jsonwebtoken"
// Middleware to validate that a token is valid
@@ -20,8 +24,13 @@ export const validateToken = () => {
const req_ = req as AuthenticatedMedusaRequest
const errorObject = new MedusaError(
MedusaError.Types.UNAUTHORIZED,
`Invalid token`
)
if (!token) {
return next()
return next(errorObject)
}
// @ts-ignore
@@ -33,6 +42,10 @@ export const validateToken = () => {
const decoded = decode(token as string) as JwtPayload
if (!decoded?.entity_id) {
return next(errorObject)
}
const [providerIdentity] = await authModule.listProviderIdentities(
{
entity_id: decoded.entity_id,
@@ -44,7 +57,7 @@ export const validateToken = () => {
)
if (!providerIdentity) {
return res.status(401).json({ message: "Invalid token" })
return next(errorObject)
}
let verified: JwtPayload | null = null
@@ -52,7 +65,7 @@ export const validateToken = () => {
try {
verified = verify(token as string, http.jwtSecret as string) as JwtPayload
} catch (error) {
return res.status(401).json({ message: "Invalid token" })
return next(errorObject)
}
req_.auth_context = {