Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/develop' into feat/customer-admi…
Browse files Browse the repository at this point in the history
…n-groups
  • Loading branch information
srindom committed Jan 30, 2024
2 parents b19a475 + 7d5a6f8 commit 344ea8c
Show file tree
Hide file tree
Showing 30 changed files with 1,001 additions and 252 deletions.
71 changes: 71 additions & 0 deletions integration-tests/plugins/__tests__/cart/store/get-cart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { ICartModuleService } from "@medusajs/types"
import path from "path"
import { startBootstrapApp } from "../../../../environment-helpers/bootstrap-app"
import { useApi } from "../../../../environment-helpers/use-api"
import { getContainer } from "../../../../environment-helpers/use-container"
import { initDb, useDb } from "../../../../environment-helpers/use-db"
import adminSeeder from "../../../../helpers/admin-seeder"

const env = { MEDUSA_FF_MEDUSA_V2: true }

describe("GET /store/:id", () => {
let dbConnection
let appContainer
let shutdownServer
let cartModuleService: ICartModuleService

beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", "..", ".."))
dbConnection = await initDb({ cwd, env } as any)
shutdownServer = await startBootstrapApp({ cwd, env })
appContainer = getContainer()
cartModuleService = appContainer.resolve(ModuleRegistrationName.CART)
})

afterAll(async () => {
const db = useDb()
await db.shutdown()
await shutdownServer()
})

beforeEach(async () => {
await adminSeeder(dbConnection)
})

afterEach(async () => {
const db = useDb()
await db.teardown()
})

it("should get cart", async () => {
const cart = await cartModuleService.create({
currency_code: "usd",
items: [
{
unit_price: 1000,
quantity: 1,
title: "Test item",
},
],
})

const api = useApi() as any
const response = await api.get(`/store/carts/${cart.id}`)

expect(response.status).toEqual(200)
expect(response.data.cart).toEqual(
expect.objectContaining({
id: cart.id,
currency_code: "usd",
items: expect.arrayContaining([
expect.objectContaining({
unit_price: 1000,
quantity: 1,
title: "Test item",
}),
]),
})
)
})
})
5 changes: 5 additions & 0 deletions integration-tests/plugins/medusa-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,10 @@ module.exports = {
resources: "shared",
resolve: "@medusajs/sales-channel",
},
[Modules.CART]: {
scope: "internal",
resources: "shared",
resolve: "@medusajs/cart",
},
},
}
109 changes: 77 additions & 32 deletions packages/auth/src/services/auth-module.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import jwt from "jsonwebtoken"

import {
AuthenticationInput,
AuthenticationResponse,
Expand All @@ -8,6 +10,7 @@ import {
InternalModuleDeclaration,
MedusaContainer,
ModuleJoinerConfig,
JWTGenerationOptions,
} from "@medusajs/types"

import { AuthProvider, AuthUser } from "@models"
Expand All @@ -33,6 +36,15 @@ import {
} from "@medusajs/types"
import { ServiceTypes } from "@types"

type AuthModuleOptions = {
jwt_secret: string
}

type AuthJWTPayload = {
id: string
scope: string
}

type InjectedDependencies = {
baseRepository: DAL.RepositoryService
authUserService: AuthUserService<any>
Expand All @@ -57,19 +69,22 @@ export default class AuthModuleService<

protected authUserService_: AuthUserService<TAuthUser>
protected authProviderService_: AuthProviderService<TAuthProvider>
protected options_: AuthModuleOptions

constructor(
{
authUserService,
authProviderService,
baseRepository,
}: InjectedDependencies,
options: AuthModuleOptions,
protected readonly moduleDeclaration: InternalModuleDeclaration
) {
this.__container__ = arguments[0]
this.baseRepository_ = baseRepository
this.authUserService_ = authUserService
this.authProviderService_ = authProviderService
this.options_ = options
}

async retrieveAuthProvider(
Expand Down Expand Up @@ -100,9 +115,10 @@ export default class AuthModuleService<
sharedContext
)

return await this.baseRepository_.serialize<
AuthTypes.AuthProviderDTO[]
>(authProviders, { populate: true })
return await this.baseRepository_.serialize<AuthTypes.AuthProviderDTO[]>(
authProviders,
{ populate: true }
)
}

@InjectManager("baseRepository_")
Expand All @@ -118,13 +134,54 @@ export default class AuthModuleService<
)

return [
await this.baseRepository_.serialize<
AuthTypes.AuthProviderDTO[]
>(authProviders, { populate: true }),
await this.baseRepository_.serialize<AuthTypes.AuthProviderDTO[]>(
authProviders,
{ populate: true }
),
count,
]
}

async generateJwtToken(
authUserId: string,
scope: string,
options: JWTGenerationOptions = {}
): Promise<string> {
const authUser = await this.authUserService_.retrieve(authUserId)
return jwt.sign({ id: authUser.id, scope }, this.options_.jwt_secret, {
expiresIn: options.expiresIn || "1d",
})
}

async retrieveAuthUserFromJwtToken(
token: string,
scope: string
): Promise<AuthUserDTO> {
let decoded: AuthJWTPayload
try {
const verifiedToken = jwt.verify(token, this.options_.jwt_secret)
decoded = verifiedToken as AuthJWTPayload
} catch (err) {
throw new MedusaError(
MedusaError.Types.UNAUTHORIZED,
"The provided JWT token is invalid"
)
}

if (decoded.scope !== scope) {
throw new MedusaError(
MedusaError.Types.UNAUTHORIZED,
"The provided JWT token is invalid"
)
}

const authUser = await this.authUserService_.retrieve(decoded.id)
return await this.baseRepository_.serialize<AuthTypes.AuthUserDTO>(
authUser,
{ populate: true }
)
}

async createAuthProvider(
data: CreateAuthProviderDTO[],
sharedContext?: Context
Expand All @@ -139,9 +196,7 @@ export default class AuthModuleService<
async createAuthProvider(
data: CreateAuthProviderDTO | CreateAuthProviderDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<
AuthTypes.AuthProviderDTO | AuthTypes.AuthProviderDTO[]
> {
): Promise<AuthTypes.AuthProviderDTO | AuthTypes.AuthProviderDTO[]> {
const input = Array.isArray(data) ? data : [data]

const providers = await this.createAuthProviders_(input, sharedContext)
Expand Down Expand Up @@ -174,13 +229,9 @@ export default class AuthModuleService<

@InjectManager("baseRepository_")
async updateAuthProvider(
data:
| AuthTypes.UpdateAuthProviderDTO[]
| AuthTypes.UpdateAuthProviderDTO,
data: AuthTypes.UpdateAuthProviderDTO[] | AuthTypes.UpdateAuthProviderDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<
AuthTypes.AuthProviderDTO | AuthTypes.AuthProviderDTO[]
> {
): Promise<AuthTypes.AuthProviderDTO | AuthTypes.AuthProviderDTO[]> {
const input = Array.isArray(data) ? data : [data]

const providers = await this.updateAuthProvider_(input, sharedContext)
Expand Down Expand Up @@ -241,11 +292,12 @@ export default class AuthModuleService<
sharedContext
)

return await this.baseRepository_.serialize<
AuthTypes.AuthUserDTO[]
>(authUsers, {
populate: true,
})
return await this.baseRepository_.serialize<AuthTypes.AuthUserDTO[]>(
authUsers,
{
populate: true,
}
)
}

@InjectManager("baseRepository_")
Expand All @@ -261,12 +313,9 @@ export default class AuthModuleService<
)

return [
await this.baseRepository_.serialize<AuthTypes.AuthUserDTO[]>(
authUsers,
{
populate: true,
}
),
await this.baseRepository_.serialize<AuthTypes.AuthUserDTO[]>(authUsers, {
populate: true,
}),
count,
]
}
Expand All @@ -284,9 +333,7 @@ export default class AuthModuleService<
async createAuthUser(
data: CreateAuthUserDTO[] | CreateAuthUserDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<
AuthTypes.AuthUserDTO | AuthTypes.AuthUserDTO[]
> {
): Promise<AuthTypes.AuthUserDTO | AuthTypes.AuthUserDTO[]> {
const input = Array.isArray(data) ? data : [data]

const authUsers = await this.createAuthUsers_(input, sharedContext)
Expand Down Expand Up @@ -321,9 +368,7 @@ export default class AuthModuleService<
async updateAuthUser(
data: UpdateAuthUserDTO | UpdateAuthUserDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<
AuthTypes.AuthUserDTO | AuthTypes.AuthUserDTO[]
> {
): Promise<AuthTypes.AuthUserDTO | AuthTypes.AuthUserDTO[]> {
const input = Array.isArray(data) ? data : [data]

const updatedUsers = await this.updateAuthUsers_(input, sharedContext)
Expand Down
2 changes: 2 additions & 0 deletions packages/cart/src/migrations/CartModuleSetup20240122122952.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export class CartModuleSetup20240122122952 extends Migration {
);
ALTER TABLE "cart" ADD COLUMN IF NOT EXISTS "currency_code" TEXT NOT NULL;
ALTER TABLE "cart" ALTER COLUMN "region_id" DROP NOT NULL;
ALTER TABLE "cart" ALTER COLUMN "email" DROP NOT NULL;
ALTER TABLE "cart" DROP CONSTRAINT IF EXISTS "FK_242205c81c1152fab1b6e848470";
ALTER TABLE "cart" DROP CONSTRAINT IF EXISTS "FK_484c329f4783be4e18e5e2ff090";
Expand Down
27 changes: 13 additions & 14 deletions packages/cart/src/models/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import {
OnInit,
OptionalProps,
PrimaryKey,
Property
Property,
} from "@mikro-orm/core"


type OptionalAddressProps = DAL.EntityDateColumns // TODO: To be revisited when more clear

@Entity({ tableName: "cart_address" })
Expand All @@ -20,40 +19,40 @@ export default class Address {
id!: string

@Property({ columnType: "text", nullable: true })
customer_id?: string | null
customer_id: string | null = null

@Property({ columnType: "text", nullable: true })
company?: string | null
company: string | null = null

@Property({ columnType: "text", nullable: true })
first_name?: string | null
first_name: string | null = null

@Property({ columnType: "text", nullable: true })
last_name?: string | null
last_name: string | null = null

@Property({ columnType: "text", nullable: true })
address_1?: string | null
address_1: string | null = null

@Property({ columnType: "text", nullable: true })
address_2?: string | null
address_2: string | null = null

@Property({ columnType: "text", nullable: true })
city?: string | null
city: string | null = null

@Property({ columnType: "text", nullable: true })
country_code?: string | null
country_code: string | null = null

@Property({ columnType: "text", nullable: true })
province?: string | null
province: string | null = null

@Property({ columnType: "text", nullable: true })
postal_code?: string | null
postal_code: string | null = null

@Property({ columnType: "text", nullable: true })
phone?: string | null
phone: string | null = null

@Property({ columnType: "jsonb", nullable: true })
metadata?: Record<string, unknown> | null
metadata: Record<string, unknown> | null = null

@Property({
onCreate: () => new Date(),
Expand Down
Loading

0 comments on commit 344ea8c

Please sign in to comment.