feat: Destroy session + introduce http config (#7336)
This commit is contained in:
@@ -53,19 +53,28 @@ export const POST = async (
|
||||
userData: req.validatedBody,
|
||||
authUserId: req.auth.auth_user_id,
|
||||
},
|
||||
throwOnError: false,
|
||||
}
|
||||
|
||||
const { errors } = await createUserAccountWorkflow(req.scope).run(input)
|
||||
|
||||
if (Array.isArray(errors) && errors[0]) {
|
||||
throw errors[0].error
|
||||
}
|
||||
|
||||
const { result } = await createUserAccountWorkflow(req.scope).run(input)
|
||||
const user = await refetchUser(
|
||||
req.auth.auth_user_id,
|
||||
req.scope,
|
||||
req.remoteQueryConfig.fields
|
||||
)
|
||||
|
||||
const { jwt_secret } = req.scope.resolve(
|
||||
const { http } = req.scope.resolve(
|
||||
ContainerRegistrationKeys.CONFIG_MODULE
|
||||
).projectConfig
|
||||
const token = jwt.sign(user, jwt_secret)
|
||||
|
||||
const token = jwt.sign(user, http.jwtSecret, {
|
||||
expiresIn: http.jwtExpiresIn,
|
||||
})
|
||||
|
||||
res.status(200).json({ user, token })
|
||||
}
|
||||
|
||||
@@ -25,9 +25,11 @@ export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
|
||||
const { success, error, authUser, successRedirectUrl } = authResult
|
||||
|
||||
if (success) {
|
||||
const { jwt_secret } = req.scope.resolve("configModule").projectConfig
|
||||
const { http } = req.scope.resolve("configModule").projectConfig
|
||||
|
||||
const token = jwt.sign(authUser, jwt_secret)
|
||||
const { jwtSecret, jwtExpiresIn } = http
|
||||
|
||||
const token = jwt.sign(authUser, jwtSecret, { expiresIn: jwtExpiresIn })
|
||||
|
||||
if (successRedirectUrl) {
|
||||
const url = new URL(successRedirectUrl!)
|
||||
|
||||
@@ -30,8 +30,11 @@ export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
|
||||
}
|
||||
|
||||
if (success) {
|
||||
const { jwt_secret } = req.scope.resolve("configModule").projectConfig
|
||||
const token = jwt.sign(authUser, jwt_secret)
|
||||
const { http } = req.scope.resolve("configModule").projectConfig
|
||||
|
||||
const token = jwt.sign(authUser, http.jwtSecret, {
|
||||
expiresIn: http.jwtExpiresIn,
|
||||
})
|
||||
|
||||
return res.status(200).json({ token })
|
||||
}
|
||||
|
||||
@@ -7,6 +7,11 @@ export const authRoutesMiddlewares: MiddlewareRoute[] = [
|
||||
matcher: "/auth/session",
|
||||
middlewares: [authenticate(/.*/, "bearer")],
|
||||
},
|
||||
{
|
||||
method: ["DELETE"],
|
||||
matcher: "/auth/session",
|
||||
middlewares: [authenticate(/.*/, ["session"])],
|
||||
},
|
||||
{
|
||||
method: ["POST"],
|
||||
matcher: "/auth/:scope/:auth_provider/callback",
|
||||
|
||||
@@ -11,3 +11,11 @@ export const POST = async (
|
||||
|
||||
res.status(200).json({ user: req.auth })
|
||||
}
|
||||
|
||||
export const DELETE = async (
|
||||
req: AuthenticatedMedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
req.session.destroy()
|
||||
res.json({ success: true })
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ConfigModule } from "@medusajs/types"
|
||||
import { getConfigFile, isDefined } from "medusa-core-utils"
|
||||
import logger from "./logger"
|
||||
import { ConfigModule } from "@medusajs/types"
|
||||
|
||||
const isProduction = ["production", "prod"].includes(process.env.NODE_ENV || "")
|
||||
|
||||
@@ -18,47 +18,55 @@ export const handleConfigError = (error: Error): void => {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
export default (rootDirectory: string): ConfigModule => {
|
||||
const { configModule, error } = getConfigFile<ConfigModule>(
|
||||
rootDirectory,
|
||||
`medusa-config`
|
||||
)
|
||||
const buildHttpConfig = (projectConfig: ConfigModule["projectConfig"]) => {
|
||||
const http = projectConfig.http ?? {}
|
||||
|
||||
if (error) {
|
||||
handleConfigError(error)
|
||||
http.jwtExpiresIn = http?.jwtExpiresIn ?? "1d"
|
||||
http.authCors = http.authCors ?? ""
|
||||
http.storeCors = http.storeCors ?? ""
|
||||
http.adminCors = http.adminCors ?? ""
|
||||
|
||||
http.jwtSecret = http?.jwtSecret ?? process.env.JWT_SECRET
|
||||
|
||||
if (!http.jwtSecret) {
|
||||
errorHandler(
|
||||
`[medusa-config] ⚠️ http.jwtSecret not found.${
|
||||
isProduction ? "" : "Using default 'supersecret'."
|
||||
}`
|
||||
)
|
||||
|
||||
http.jwtSecret = "supersecret"
|
||||
}
|
||||
|
||||
if (!configModule?.projectConfig?.redis_url) {
|
||||
http.cookieSecret =
|
||||
projectConfig.http?.cookieSecret ?? process.env.COOKIE_SECRET
|
||||
|
||||
if (!http.cookieSecret) {
|
||||
errorHandler(
|
||||
`[medusa-config] ⚠️ http.cookieSecret not found.${
|
||||
isProduction ? "" : " Using default 'supersecret'."
|
||||
}`
|
||||
)
|
||||
|
||||
http.cookieSecret = "supersecret"
|
||||
}
|
||||
|
||||
return http
|
||||
}
|
||||
|
||||
const normalizeProjectConfig = (
|
||||
projectConfig: ConfigModule["projectConfig"]
|
||||
) => {
|
||||
if (!projectConfig?.redis_url) {
|
||||
console.log(
|
||||
`[medusa-config] ⚠️ redis_url not found. A fake redis instance will be used.`
|
||||
)
|
||||
}
|
||||
|
||||
const jwt_secret =
|
||||
configModule?.projectConfig?.jwt_secret ?? process.env.JWT_SECRET
|
||||
if (!jwt_secret) {
|
||||
errorHandler(
|
||||
`[medusa-config] ⚠️ jwt_secret not found.${
|
||||
isProduction
|
||||
? ""
|
||||
: " fallback to either cookie_secret or default 'supersecret'."
|
||||
}`
|
||||
)
|
||||
}
|
||||
projectConfig.http = buildHttpConfig(projectConfig)
|
||||
|
||||
const cookie_secret =
|
||||
configModule?.projectConfig?.cookie_secret ?? process.env.COOKIE_SECRET
|
||||
if (!cookie_secret) {
|
||||
errorHandler(
|
||||
`[medusa-config] ⚠️ cookie_secret not found.${
|
||||
isProduction
|
||||
? ""
|
||||
: " fallback to either cookie_secret or default 'supersecret'."
|
||||
}`
|
||||
)
|
||||
}
|
||||
let worker_mode = projectConfig?.worker_mode
|
||||
|
||||
let worker_mode = configModule?.projectConfig?.worker_mode
|
||||
if (!isDefined(worker_mode)) {
|
||||
const env = process.env.MEDUSA_WORKER_MODE
|
||||
if (isDefined(env)) {
|
||||
@@ -71,12 +79,25 @@ export default (rootDirectory: string): ConfigModule => {
|
||||
}
|
||||
|
||||
return {
|
||||
projectConfig: {
|
||||
jwt_secret: jwt_secret ?? "supersecret",
|
||||
cookie_secret: cookie_secret ?? "supersecret",
|
||||
...configModule?.projectConfig,
|
||||
worker_mode,
|
||||
},
|
||||
...projectConfig,
|
||||
worker_mode,
|
||||
}
|
||||
}
|
||||
|
||||
export default (rootDirectory: string): ConfigModule => {
|
||||
const { configModule, error } = getConfigFile<ConfigModule>(
|
||||
rootDirectory,
|
||||
`medusa-config`
|
||||
)
|
||||
|
||||
if (error) {
|
||||
handleConfigError(error)
|
||||
}
|
||||
|
||||
const projectConfig = normalizeProjectConfig(configModule.projectConfig)
|
||||
|
||||
return {
|
||||
projectConfig,
|
||||
admin: configModule?.admin ?? {},
|
||||
modules: configModule.modules ?? {},
|
||||
featureFlags: configModule?.featureFlags ?? {},
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { ConfigModule } from "@medusajs/types"
|
||||
import createStore from "connect-redis"
|
||||
import cookieParser from "cookie-parser"
|
||||
import { Express } from "express"
|
||||
import session from "express-session"
|
||||
import morgan from "morgan"
|
||||
import Redis from "ioredis"
|
||||
import { ConfigModule } from "@medusajs/types"
|
||||
import morgan from "morgan"
|
||||
|
||||
type Options = {
|
||||
app: Express
|
||||
@@ -28,14 +28,14 @@ export default async ({
|
||||
sameSite = "none"
|
||||
}
|
||||
|
||||
const { cookie_secret, session_options } = configModule.projectConfig
|
||||
const { http, session_options } = configModule.projectConfig
|
||||
const sessionOpts = {
|
||||
name: session_options?.name ?? "connect.sid",
|
||||
resave: session_options?.resave ?? true,
|
||||
rolling: session_options?.rolling ?? false,
|
||||
saveUninitialized: session_options?.saveUninitialized ?? true,
|
||||
proxy: true,
|
||||
secret: session_options?.secret ?? cookie_secret,
|
||||
secret: session_options?.secret ?? http?.cookieSecret,
|
||||
cookie: {
|
||||
sameSite,
|
||||
secure,
|
||||
|
||||
@@ -4,11 +4,13 @@ export const storeGlobalMiddlewareMock = jest.fn()
|
||||
|
||||
export const config = {
|
||||
projectConfig: {
|
||||
store_cors: "http://localhost:8000",
|
||||
admin_cors: "http://localhost:7001",
|
||||
database_logging: false,
|
||||
jwt_secret: "supersecret",
|
||||
cookie_secret: "superSecret",
|
||||
http: {
|
||||
storeCors: "http://localhost:8000",
|
||||
adminCors: "http://localhost:7001",
|
||||
jwtSecret: "supersecret",
|
||||
cookieSecret: "superSecret",
|
||||
},
|
||||
},
|
||||
featureFlags: {},
|
||||
plugins: [],
|
||||
|
||||
@@ -124,7 +124,7 @@ export const createServer = async (rootDir) => {
|
||||
user_id: opts.adminSession.userId || opts.adminSession.jwt?.userId,
|
||||
domain: "admin",
|
||||
},
|
||||
config.projectConfig.jwt_secret
|
||||
config.projectConfig.http.jwtSecret
|
||||
)
|
||||
|
||||
headers.Authorization = `Bearer ${token}`
|
||||
@@ -137,7 +137,7 @@ export const createServer = async (rootDir) => {
|
||||
opts.clientSession.jwt?.customer_id,
|
||||
domain: "store",
|
||||
},
|
||||
config.projectConfig.jwt_secret
|
||||
config.projectConfig.http.jwtSecret
|
||||
)
|
||||
|
||||
headers.Authorization = `Bearer ${token}`
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
import { ConfigModule } from "@medusajs/types"
|
||||
import { promiseAll, wrapHandler } from "@medusajs/utils"
|
||||
import cors from "cors"
|
||||
import { type Express, json, Router, text, urlencoded } from "express"
|
||||
import { Router, json, text, urlencoded, type Express } from "express"
|
||||
import { readdir } from "fs/promises"
|
||||
import { parseCorsOrigins } from "medusa-core-utils"
|
||||
import { extname, join, sep } from "path"
|
||||
import { MedusaRequest, MedusaResponse } from "../../../types/routing"
|
||||
import {
|
||||
authenticateCustomer,
|
||||
authenticateLegacy,
|
||||
errorHandler,
|
||||
requireCustomerAuthentication,
|
||||
} from "../../../utils/middlewares"
|
||||
import { MedusaRequest, MedusaResponse } from "../../../types/routing"
|
||||
import logger from "../../logger"
|
||||
import {
|
||||
AsyncRouteHandler,
|
||||
GlobalMiddlewareDescriptor,
|
||||
HTTP_METHODS,
|
||||
MiddlewareRoute,
|
||||
MiddlewaresConfig,
|
||||
MiddlewareVerb,
|
||||
MiddlewaresConfig,
|
||||
ParserConfigArgs,
|
||||
RouteConfig,
|
||||
RouteDescriptor,
|
||||
RouteVerb,
|
||||
} from "./types"
|
||||
import { ConfigModule } from "@medusajs/types"
|
||||
|
||||
const log = ({
|
||||
activityId,
|
||||
@@ -610,7 +610,7 @@ export class RoutesLoader {
|
||||
descriptor.route,
|
||||
cors({
|
||||
origin: parseCorsOrigins(
|
||||
this.configModule.projectConfig.admin_cors || ""
|
||||
this.configModule.projectConfig.http.adminCors
|
||||
),
|
||||
credentials: true,
|
||||
})
|
||||
@@ -625,7 +625,7 @@ export class RoutesLoader {
|
||||
descriptor.route,
|
||||
cors({
|
||||
origin: parseCorsOrigins(
|
||||
this.configModule.projectConfig.auth_cors || ""
|
||||
this.configModule.projectConfig.http.authCors
|
||||
),
|
||||
credentials: true,
|
||||
})
|
||||
@@ -640,7 +640,7 @@ export class RoutesLoader {
|
||||
descriptor.route,
|
||||
cors({
|
||||
origin: parseCorsOrigins(
|
||||
this.configModule.projectConfig.store_cors || ""
|
||||
this.configModule.projectConfig.http.storeCors
|
||||
),
|
||||
credentials: true,
|
||||
})
|
||||
|
||||
@@ -3,9 +3,6 @@ import {
|
||||
MedusaAppMigrateDown,
|
||||
MedusaAppMigrateUp,
|
||||
MedusaAppOutput,
|
||||
MedusaModule,
|
||||
MODULE_PACKAGE_NAMES,
|
||||
Modules,
|
||||
ModulesDefinition,
|
||||
} from "@medusajs/modules-sdk"
|
||||
import {
|
||||
@@ -188,29 +185,6 @@ export const loadMedusaApp = async (
|
||||
injectedDependencies,
|
||||
})
|
||||
|
||||
// TODO: Remove this and make it more dynamic on ensuring all modules are loaded.
|
||||
const requiredModuleKeys = [Modules.PRODUCT, Modules.PRICING]
|
||||
|
||||
const missingPackages: string[] = []
|
||||
|
||||
for (const requiredModuleKey of requiredModuleKeys) {
|
||||
const isModuleInstalled = MedusaModule.isInstalled(requiredModuleKey)
|
||||
|
||||
if (!isModuleInstalled) {
|
||||
missingPackages.push(
|
||||
MODULE_PACKAGE_NAMES[requiredModuleKey] || requiredModuleKey
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (missingPackages.length) {
|
||||
throw new Error(
|
||||
`Medusa requires the following packages/module registration: (${missingPackages.join(
|
||||
", "
|
||||
)})`
|
||||
)
|
||||
}
|
||||
|
||||
if (!config.registerInContainer) {
|
||||
return medusaApp
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ export default async ({
|
||||
|
||||
// After a user has authenticated a JWT will be placed on a cookie, all
|
||||
// calls will be authenticated based on the JWT
|
||||
const { jwt_secret } = configModule.projectConfig
|
||||
const { http } = configModule.projectConfig
|
||||
passport.use(
|
||||
"admin-session",
|
||||
new CustomStrategy(async (req, done) => {
|
||||
@@ -97,7 +97,7 @@ export default async ({
|
||||
new JWTStrategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: jwt_secret,
|
||||
secretOrKey: http.jwtSecret,
|
||||
},
|
||||
(token, done) => {
|
||||
if (token.domain !== "admin") {
|
||||
@@ -121,7 +121,7 @@ export default async ({
|
||||
new JWTStrategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey: jwt_secret,
|
||||
secretOrKey: http.jwtSecret,
|
||||
},
|
||||
(token, done) => {
|
||||
if (token.domain !== "store") {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { PaymentWebhookEvents } from "@medusajs/utils"
|
||||
import { IPaymentModuleService, ProviderWebhookPayload } from "@medusajs/types"
|
||||
import { SubscriberArgs, SubscriberConfig } from "../types/subscribers"
|
||||
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
|
||||
import { IPaymentModuleService, ProviderWebhookPayload } from "@medusajs/types"
|
||||
import { PaymentWebhookEvents } from "@medusajs/utils"
|
||||
import { SubscriberArgs, SubscriberConfig } from "../types/subscribers"
|
||||
|
||||
type SerializedBuffer = {
|
||||
data: ArrayBuffer
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import { Request, Response, NextFunction } from "express"
|
||||
import { HttpCompressionOptions, ProjectConfigOptions } from "@medusajs/types"
|
||||
import compression from "compression"
|
||||
import { Logger } from "@medusajs/types"
|
||||
import {
|
||||
ProjectConfigOptions,
|
||||
HttpCompressionOptions,
|
||||
} from "@medusajs/types"
|
||||
import { Request, Response } from "express"
|
||||
|
||||
export function shouldCompressResponse(req: Request, res: Response) {
|
||||
const logger: Logger = req.scope.resolve("logger")
|
||||
const { projectConfig } = req.scope.resolve("configModule")
|
||||
const { enabled } = compressionOptions(projectConfig)
|
||||
|
||||
@@ -27,9 +22,10 @@ export function shouldCompressResponse(req: Request, res: Response) {
|
||||
export function compressionOptions(
|
||||
config: ProjectConfigOptions
|
||||
): HttpCompressionOptions {
|
||||
const responseCompressionOptions = config.http_compression ?? {}
|
||||
const responseCompressionOptions = config.http.compression ?? {}
|
||||
|
||||
responseCompressionOptions.enabled = responseCompressionOptions.enabled ?? false
|
||||
responseCompressionOptions.enabled =
|
||||
responseCompressionOptions.enabled ?? false
|
||||
responseCompressionOptions.level = responseCompressionOptions.level ?? 6
|
||||
responseCompressionOptions.memLevel = responseCompressionOptions.memLevel ?? 8
|
||||
responseCompressionOptions.threshold =
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
|
||||
import { ApiKeyDTO, AuthUserDTO, IApiKeyModuleService } from "@medusajs/types"
|
||||
import {
|
||||
ApiKeyDTO,
|
||||
AuthUserDTO,
|
||||
ConfigModule,
|
||||
IApiKeyModuleService,
|
||||
} from "@medusajs/types"
|
||||
import { stringEqualsOrRegexMatch } from "@medusajs/utils"
|
||||
import { NextFunction, RequestHandler } from "express"
|
||||
import jwt, { JwtPayload } from "jsonwebtoken"
|
||||
@@ -55,10 +60,11 @@ export const authenticate = (
|
||||
)
|
||||
|
||||
if (!authUser) {
|
||||
const { jwt_secret } = req.scope.resolve("configModule").projectConfig
|
||||
const { http } =
|
||||
req.scope.resolve<ConfigModule>("configModule").projectConfig
|
||||
authUser = getAuthUserFromJwtToken(
|
||||
req.headers.authorization,
|
||||
jwt_secret,
|
||||
http.jwtSecret!,
|
||||
authTypes,
|
||||
authScope
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user