chore: Update auth flow (#9959)
This commit is contained in:
@@ -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 = {
|
||||
|
||||
Reference in New Issue
Block a user