fix: customer endpoints shouldn't use customer id already provided through authentication (#402)

* Updated customers/:id to customers/me - untested

* fix: integration +unit tests

* docs: fix oas docs

Co-authored-by: ColdMeekly <20516479+ColdMeekly@users.noreply.github.com>
This commit is contained in:
Sebastian Rindom
2021-09-17 08:27:46 +02:00
committed by GitHub
co-authored by ColdMeekly
parent b0420b3249
commit bf43896d19
13 changed files with 139 additions and 203 deletions
@@ -1,67 +1,67 @@
const path = require("path"); const path = require("path")
const { Address, Customer } = require("@medusajs/medusa"); const { Address, Customer } = require("@medusajs/medusa")
const setupServer = require("../../../helpers/setup-server"); const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api"); const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db"); const { initDb, useDb } = require("../../../helpers/use-db")
const customerSeeder = require("../../helpers/customer-seeder"); const customerSeeder = require("../../helpers/customer-seeder")
jest.setTimeout(30000); jest.setTimeout(30000)
describe("/store/customers", () => { describe("/store/customers", () => {
let medusaProcess; let medusaProcess
let dbConnection; let dbConnection
const doAfterEach = async () => { const doAfterEach = async () => {
const db = useDb(); const db = useDb()
await db.teardown(); await db.teardown()
}; }
beforeAll(async () => { beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", "..")); const cwd = path.resolve(path.join(__dirname, "..", ".."))
dbConnection = await initDb({ cwd }); dbConnection = await initDb({ cwd })
medusaProcess = await setupServer({ cwd }); medusaProcess = await setupServer({ cwd })
}); })
afterAll(async () => { afterAll(async () => {
const db = useDb(); const db = useDb()
await db.shutdown(); await db.shutdown()
medusaProcess.kill(); medusaProcess.kill()
}); })
describe("POST /store/customers", () => { describe("POST /store/customers", () => {
beforeEach(async () => { beforeEach(async () => {
const manager = dbConnection.manager; const manager = dbConnection.manager
await manager.insert(Customer, { await manager.insert(Customer, {
id: "test_customer", id: "test_customer",
first_name: "John", first_name: "John",
last_name: "Deere", last_name: "Deere",
email: "john@deere.com", email: "john@deere.com",
has_account: true, has_account: true,
}); })
}); })
afterEach(async () => { afterEach(async () => {
await doAfterEach(); await doAfterEach()
}); })
it("creates a customer", async () => { it("creates a customer", async () => {
const api = useApi(); const api = useApi()
const response = await api.post("/store/customers", { const response = await api.post("/store/customers", {
first_name: "James", first_name: "James",
last_name: "Bond", last_name: "Bond",
email: "james@bond.com", email: "james@bond.com",
password: "test", password: "test",
}); })
expect(response.status).toEqual(200); expect(response.status).toEqual(200)
expect(response.data.customer).not.toHaveProperty("password_hash"); expect(response.data.customer).not.toHaveProperty("password_hash")
}); })
it("responds 409 on duplicate", async () => { it("responds 409 on duplicate", async () => {
const api = useApi(); const api = useApi()
const response = await api const response = await api
.post("/store/customers", { .post("/store/customers", {
@@ -70,15 +70,15 @@ describe("/store/customers", () => {
email: "john@deere.com", email: "john@deere.com",
password: "test", password: "test",
}) })
.catch((err) => err.response); .catch((err) => err.response)
expect(response.status).toEqual(402); expect(response.status).toEqual(402)
}); })
}); })
describe("POST /store/customers/:id", () => { describe("POST /store/customers/me", () => {
beforeEach(async () => { beforeEach(async () => {
const manager = dbConnection.manager; const manager = dbConnection.manager
await manager.insert(Address, { await manager.insert(Address, {
id: "addr_test", id: "addr_test",
first_name: "String", first_name: "String",
@@ -88,7 +88,7 @@ describe("/store/customers", () => {
postal_code: "1236", postal_code: "1236",
province: "ca", province: "ca",
country_code: "us", country_code: "us",
}); })
await manager.insert(Customer, { await manager.insert(Customer, {
id: "test_customer", id: "test_customer",
@@ -98,26 +98,26 @@ describe("/store/customers", () => {
password_hash: password_hash:
"c2NyeXB0AAEAAAABAAAAAVMdaddoGjwU1TafDLLlBKnOTQga7P2dbrfgf3fB+rCD/cJOMuGzAvRdKutbYkVpuJWTU39P7OpuWNkUVoEETOVLMJafbI8qs8Qx/7jMQXkN", // password matching "test" "c2NyeXB0AAEAAAABAAAAAVMdaddoGjwU1TafDLLlBKnOTQga7P2dbrfgf3fB+rCD/cJOMuGzAvRdKutbYkVpuJWTU39P7OpuWNkUVoEETOVLMJafbI8qs8Qx/7jMQXkN", // password matching "test"
has_account: true, has_account: true,
}); })
}); })
afterEach(async () => { afterEach(async () => {
await doAfterEach(); await doAfterEach()
}); })
it("updates a customer", async () => { it("updates a customer", async () => {
const api = useApi(); const api = useApi()
const authResponse = await api.post("/store/auth", { const authResponse = await api.post("/store/auth", {
email: "john@deere.com", email: "john@deere.com",
password: "test", password: "test",
}); })
const customerId = authResponse.data.customer.id; const customerId = authResponse.data.customer.id
const [authCookie] = authResponse.headers["set-cookie"][0].split(";"); const [authCookie] = authResponse.headers["set-cookie"][0].split(";")
const response = await api.post( const response = await api.post(
`/store/customers/${customerId}`, `/store/customers/me`,
{ {
password: "test", password: "test",
metadata: { key: "value" }, metadata: { key: "value" },
@@ -127,30 +127,30 @@ describe("/store/customers", () => {
Cookie: authCookie, Cookie: authCookie,
}, },
} }
); )
expect(response.status).toEqual(200); expect(response.status).toEqual(200)
expect(response.data.customer).not.toHaveProperty("password_hash"); expect(response.data.customer).not.toHaveProperty("password_hash")
expect(response.data.customer).toEqual( expect(response.data.customer).toEqual(
expect.objectContaining({ expect.objectContaining({
metadata: { key: "value" }, metadata: { key: "value" },
}) })
); )
}); })
it("updates customer billing address", async () => { it("updates customer billing address", async () => {
const api = useApi(); const api = useApi()
const authResponse = await api.post("/store/auth", { const authResponse = await api.post("/store/auth", {
email: "john@deere.com", email: "john@deere.com",
password: "test", password: "test",
}); })
const customerId = authResponse.data.customer.id; const customerId = authResponse.data.customer.id
const [authCookie] = authResponse.headers["set-cookie"][0].split(";"); const [authCookie] = authResponse.headers["set-cookie"][0].split(";")
const response = await api.post( const response = await api.post(
`/store/customers/${customerId}`, `/store/customers/me`,
{ {
billing_address: { billing_address: {
first_name: "test", first_name: "test",
@@ -167,10 +167,10 @@ describe("/store/customers", () => {
Cookie: authCookie, Cookie: authCookie,
}, },
} }
); )
expect(response.status).toEqual(200); expect(response.status).toEqual(200)
expect(response.data.customer).not.toHaveProperty("password_hash"); expect(response.data.customer).not.toHaveProperty("password_hash")
expect(response.data.customer.billing_address).toEqual( expect(response.data.customer.billing_address).toEqual(
expect.objectContaining({ expect.objectContaining({
first_name: "test", first_name: "test",
@@ -181,22 +181,22 @@ describe("/store/customers", () => {
province: "ca", province: "ca",
country_code: "us", country_code: "us",
}) })
); )
}); })
it("updates customer billing address with string", async () => { it("updates customer billing address with string", async () => {
const api = useApi(); const api = useApi()
const authResponse = await api.post("/store/auth", { const authResponse = await api.post("/store/auth", {
email: "john@deere.com", email: "john@deere.com",
password: "test", password: "test",
}); })
const customerId = authResponse.data.customer.id; const customerId = authResponse.data.customer.id
const [authCookie] = authResponse.headers["set-cookie"][0].split(";"); const [authCookie] = authResponse.headers["set-cookie"][0].split(";")
const response = await api.post( const response = await api.post(
`/store/customers/${customerId}`, `/store/customers/me`,
{ {
billing_address: "addr_test", billing_address: "addr_test",
}, },
@@ -205,10 +205,10 @@ describe("/store/customers", () => {
Cookie: authCookie, Cookie: authCookie,
}, },
} }
); )
expect(response.status).toEqual(200); expect(response.status).toEqual(200)
expect(response.data.customer).not.toHaveProperty("password_hash"); expect(response.data.customer).not.toHaveProperty("password_hash")
expect(response.data.customer.billing_address).toEqual( expect(response.data.customer.billing_address).toEqual(
expect.objectContaining({ expect.objectContaining({
first_name: "String", first_name: "String",
@@ -219,7 +219,7 @@ describe("/store/customers", () => {
province: "ca", province: "ca",
country_code: "us", country_code: "us",
}) })
); )
}); })
}); })
}); })
@@ -7,21 +7,17 @@ describe("POST /store/customers/:id", () => {
describe("successfully updates a customer", () => { describe("successfully updates a customer", () => {
let subject let subject
beforeAll(async () => { beforeAll(async () => {
subject = await request( subject = await request("POST", `/store/customers/me`, {
"POST", payload: {
`/store/customers/${IdMap.getId("lebron")}`, first_name: "LeBron",
{ last_name: "James",
payload: { },
first_name: "LeBron", clientSession: {
last_name: "James", jwt: {
customer_id: IdMap.getId("lebron"),
}, },
clientSession: { },
jwt: { })
customer_id: IdMap.getId("lebron"),
},
},
}
)
}) })
afterAll(() => { afterAll(() => {
@@ -59,20 +55,16 @@ describe("POST /store/customers/:id", () => {
describe("successfully updates a customer with billing address id", () => { describe("successfully updates a customer with billing address id", () => {
let subject let subject
beforeAll(async () => { beforeAll(async () => {
subject = await request( subject = await request("POST", `/store/customers/me`, {
"POST", payload: {
`/store/customers/${IdMap.getId("lebron")}`, billing_address: "test",
{ },
payload: { clientSession: {
billing_address: "test", jwt: {
customer_id: IdMap.getId("lebron"),
}, },
clientSession: { },
jwt: { })
customer_id: IdMap.getId("lebron"),
},
},
}
)
}) })
afterAll(() => { afterAll(() => {
@@ -97,28 +89,24 @@ describe("POST /store/customers/:id", () => {
describe("successfully updates a customer with billing address object", () => { describe("successfully updates a customer with billing address object", () => {
let subject let subject
beforeAll(async () => { beforeAll(async () => {
subject = await request( subject = await request("POST", `/store/customers/me`, {
"POST", payload: {
`/store/customers/${IdMap.getId("lebron")}`, billing_address: {
{ first_name: "Olli",
payload: { last_name: "Juhl",
billing_address: { address_1: "Laksegade",
first_name: "Olli", city: "Copenhagen",
last_name: "Juhl", country_code: "dk",
address_1: "Laksegade", postal_code: "2100",
city: "Copenhagen", phone: "+1 (222) 333 4444",
country_code: "dk",
postal_code: "2100",
phone: "+1 (222) 333 4444",
},
}, },
clientSession: { },
jwt: { clientSession: {
customer_id: IdMap.getId("lebron"), jwt: {
}, customer_id: IdMap.getId("lebron"),
}, },
} },
) })
}) })
afterAll(() => { afterAll(() => {
@@ -147,33 +135,4 @@ describe("POST /store/customers/:id", () => {
expect(subject.status).toEqual(200) expect(subject.status).toEqual(200)
}) })
}) })
describe("fails if not authenticated", () => {
let subject
beforeAll(async () => {
subject = await request(
"POST",
`/store/customers/${IdMap.getId("customer1")}`,
{
payload: {
first_name: "LeBron",
last_name: "James",
},
clientSession: {
jwt: {
customer_id: IdMap.getId("lebron"),
},
},
}
)
})
afterAll(() => {
jest.clearAllMocks()
})
it("status code 400", () => {
expect(subject.status).toEqual(400)
})
})
}) })
@@ -1,12 +0,0 @@
import { MedusaError } from "medusa-core-utils"
export default async (req, res, next, id) => {
if (!(req.user && req.user.customer_id === id)) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"You must be logged in to update"
)
} else {
next()
}
}
@@ -30,7 +30,7 @@ import { defaultRelations, defaultFields } from "./"
* $ref: "#/components/schemas/customer" * $ref: "#/components/schemas/customer"
*/ */
export default async (req, res) => { export default async (req, res) => {
const { id } = req.params const id = req.user.customer_id
const schema = Validator.object().keys({ const schema = Validator.object().keys({
address: Validator.address().required(), address: Validator.address().required(),
@@ -21,7 +21,8 @@ import { defaultRelations, defaultFields } from "./"
* $ref: "#/components/schemas/customer" * $ref: "#/components/schemas/customer"
*/ */
export default async (req, res) => { export default async (req, res) => {
const { id, address_id } = req.params const id = req.user.customer_id
const { address_id } = req.params
const customerService = req.scope.resolve("customerService") const customerService = req.scope.resolve("customerService")
try { try {
@@ -1,12 +1,10 @@
import { defaultRelations, defaultFields } from "./" import { defaultRelations, defaultFields } from "./"
/** /**
* @oas [get] /customers/{id} * @oas [get] /customers/me
* operationId: GetCustomersCustomer * operationId: GetCustomersCustomer
* summary: Retrieves a Customer * summary: Retrieves a Customer
* description: "Retrieves a Customer - the Customer must be logged in to retrieve their details." * description: "Retrieves a Customer - the Customer must be logged in to retrieve their details."
* parameters:
* - (path) id=* {string} The id of the Customer.
* tags: * tags:
* - Customer * - Customer
* responses: * responses:
@@ -20,7 +18,7 @@ import { defaultRelations, defaultFields } from "./"
* $ref: "#/components/schemas/customer" * $ref: "#/components/schemas/customer"
*/ */
export default async (req, res) => { export default async (req, res) => {
const { id } = req.params const id = req.user.customer_id
try { try {
const customerService = req.scope.resolve("customerService") const customerService = req.scope.resolve("customerService")
const customer = await customerService.retrieve(id, { const customer = await customerService.retrieve(id, {
@@ -1,5 +1,5 @@
/** /**
* @oas [get] /customers/{id}/payment-methods * @oas [get] /customers/me/payment-methods
* operationId: GetCustomersCustomerPaymentMethods * operationId: GetCustomersCustomerPaymentMethods
* summary: Retrieve saved payment methods * summary: Retrieve saved payment methods
* description: "Retrieves a list of a Customer's saved payment methods. Payment methods are saved with Payment Providers and it is their responsibility to fetch saved methods." * description: "Retrieves a list of a Customer's saved payment methods. Payment methods are saved with Payment Providers and it is their responsibility to fetch saved methods."
@@ -26,7 +26,7 @@
* description: The data needed for the Payment Provider to use the saved payment method. * description: The data needed for the Payment Provider to use the saved payment method.
*/ */
export default async (req, res) => { export default async (req, res) => {
const { id } = req.params const id = req.user.customer_id
try { try {
const storeService = req.scope.resolve("storeService") const storeService = req.scope.resolve("storeService")
const paymentProviderService = req.scope.resolve("paymentProviderService") const paymentProviderService = req.scope.resolve("paymentProviderService")
@@ -37,11 +37,11 @@ export default async (req, res) => {
const store = await storeService.retrieve(["payment_providers"]) const store = await storeService.retrieve(["payment_providers"])
const methods = await Promise.all( const methods = await Promise.all(
store.payment_providers.map(async next => { store.payment_providers.map(async (next) => {
const provider = paymentProviderService.retrieveProvider(next) const provider = paymentProviderService.retrieveProvider(next)
const pMethods = await provider.retrieveSavedMethods(customer) const pMethods = await provider.retrieveSavedMethods(customer)
return pMethods.map(m => ({ return pMethods.map((m) => ({
provider_id: next, provider_id: next,
data: m, data: m,
})) }))
@@ -7,7 +7,6 @@ export default (app, container) => {
const middlewareService = container.resolve("middlewareService") const middlewareService = container.resolve("middlewareService")
app.use("/customers", route) app.use("/customers", route)
route.param("id", middlewares.wrap(require("./authorize-customer").default))
// Inject plugin routes // Inject plugin routes
const routers = middlewareService.getRouters("store/customers") const routers = middlewareService.getRouters("store/customers")
@@ -30,28 +29,28 @@ export default (app, container) => {
// Authenticated endpoints // Authenticated endpoints
route.use(middlewares.authenticate()) route.use(middlewares.authenticate())
route.get("/:id", middlewares.wrap(require("./get-customer").default)) route.get("/me", middlewares.wrap(require("./get-customer").default))
route.post("/:id", middlewares.wrap(require("./update-customer").default)) route.post("/me", middlewares.wrap(require("./update-customer").default))
route.get("/:id/orders", middlewares.wrap(require("./list-orders").default)) route.get("/me/orders", middlewares.wrap(require("./list-orders").default))
route.post( route.post(
"/:id/addresses", "/me/addresses",
middlewares.wrap(require("./create-address").default) middlewares.wrap(require("./create-address").default)
) )
route.post( route.post(
"/:id/addresses/:address_id", "/me/addresses/:address_id",
middlewares.wrap(require("./update-address").default) middlewares.wrap(require("./update-address").default)
) )
route.delete( route.delete(
"/:id/addresses/:address_id", "/me/addresses/:address_id",
middlewares.wrap(require("./delete-address").default) middlewares.wrap(require("./delete-address").default)
) )
route.get( route.get(
"/:id/payment-methods", "/me/payment-methods",
middlewares.wrap(require("./get-payment-methods").default) middlewares.wrap(require("./get-payment-methods").default)
) )
@@ -7,7 +7,7 @@ import {
} from "../orders" } from "../orders"
/** /**
* @oas [get] /customers/{id}/orders * @oas [get] /customers/me/orders
* operationId: GetCustomersCustomerOrders * operationId: GetCustomersCustomerOrders
* summary: Retrieve Customer Orders * summary: Retrieve Customer Orders
* description: "Retrieves a list of a Customer's Orders." * description: "Retrieves a list of a Customer's Orders."
@@ -28,7 +28,7 @@ import {
* $ref: "#/components/schemas/order" * $ref: "#/components/schemas/order"
*/ */
export default async (req, res) => { export default async (req, res) => {
const { id } = req.params const id = req.user.customer_id
try { try {
const orderService = req.scope.resolve("orderService") const orderService = req.scope.resolve("orderService")
@@ -42,13 +42,13 @@ export default async (req, res) => {
let includeFields = [] let includeFields = []
if ("fields" in req.query) { if ("fields" in req.query) {
includeFields = req.query.fields.split(",") includeFields = req.query.fields.split(",")
includeFields = includeFields.filter(f => allowedFields.includes(f)) includeFields = includeFields.filter((f) => allowedFields.includes(f))
} }
let expandFields = [] let expandFields = []
if ("expand" in req.query) { if ("expand" in req.query) {
expandFields = req.query.expand.split(",") expandFields = req.query.expand.split(",")
expandFields = expandFields.filter(f => allowedRelations.includes(f)) expandFields = expandFields.filter((f) => allowedRelations.includes(f))
} }
const listConfig = { const listConfig = {
@@ -1,12 +1,10 @@
import { MedusaError, Validator } from "medusa-core-utils" import { MedusaError, Validator } from "medusa-core-utils"
/** /**
* @oas [post] /customers/{id}/password-token * @oas [post] /customers/password-token
* operationId: PostCustomersCustomerPasswordToken * operationId: PostCustomersCustomerPasswordToken
* summary: Creates a reset password token * summary: Creates a reset password token
* description: "Creates a reset password token to be used in a subsequent /reset-password request. The password token should be sent out of band e.g. via email and will not be returned." * description: "Creates a reset password token to be used in a subsequent /reset-password request. The password token should be sent out of band e.g. via email and will not be returned."
* parameters:
* - (path) id=* {string} The id of the Customer.
* tags: * tags:
* - Customer * - Customer
* responses: * responses:
@@ -15,9 +13,7 @@ import { MedusaError, Validator } from "medusa-core-utils"
*/ */
export default async (req, res) => { export default async (req, res) => {
const schema = Validator.object().keys({ const schema = Validator.object().keys({
email: Validator.string() email: Validator.string().email().required(),
.email()
.required(),
}) })
const { value, error } = schema.validate(req.body) const { value, error } = schema.validate(req.body)
@@ -2,12 +2,11 @@ import { MedusaError, Validator } from "medusa-core-utils"
import jwt from "jsonwebtoken" import jwt from "jsonwebtoken"
/** /**
* @oas [post] /customers/{id}/reset-password * @oas [post] /customers/reset-password
* operationId: PostCustomersCustomerResetPassword * operationId: PostCustomersResetPassword
* summary: Resets Customer password * summary: Resets Customer password
* description: "Resets a Customer's password using a password token created by a previous /password-token request." * description: "Resets a Customer's password using a password token created by a previous /password-token request."
* parameters: * parameters:
* - (path) id=* {string} The id of the Customer.
* - (body) email=* {string} The Customer's email. * - (body) email=* {string} The Customer's email.
* - (body) token=* {string} The password token created by a /password-token request. * - (body) token=* {string} The password token created by a /password-token request.
* - (body) password=* {string} The new password to set for the Customer. * - (body) password=* {string} The new password to set for the Customer.
@@ -25,9 +24,7 @@ import jwt from "jsonwebtoken"
*/ */
export default async (req, res) => { export default async (req, res) => {
const schema = Validator.object().keys({ const schema = Validator.object().keys({
email: Validator.string() email: Validator.string().email().required(),
.email()
.required(),
token: Validator.string().required(), token: Validator.string().required(),
password: Validator.string().required(), password: Validator.string().required(),
}) })
@@ -2,12 +2,11 @@ import { Validator, MedusaError } from "medusa-core-utils"
import { defaultRelations, defaultFields } from "./" import { defaultRelations, defaultFields } from "./"
/** /**
* @oas [post] /customers/{id}/addresses/{address_id} * @oas [post] /customers/me/addresses/{address_id}
* operationId: PostCustomersCustomerAddressesAddress * operationId: PostCustomersCustomerAddressesAddress
* summary: "Update a Shipping Address" * summary: "Update a Shipping Address"
* description: "Updates a Customer's saved Shipping Address." * description: "Updates a Customer's saved Shipping Address."
* parameters: * parameters:
* - (path) id=* {String} The Customer id.
* - (path) address_id=* {String} The id of the Address to update. * - (path) address_id=* {String} The id of the Address to update.
* requestBody: * requestBody:
* content: * content:
@@ -31,7 +30,8 @@ import { defaultRelations, defaultFields } from "./"
* $ref: "#/components/schemas/customer" * $ref: "#/components/schemas/customer"
*/ */
export default async (req, res) => { export default async (req, res) => {
const { id, address_id } = req.params const id = req.user.customer_id
const { address_id } = req.params
const schema = Validator.object().keys({ const schema = Validator.object().keys({
address: Validator.address().required(), address: Validator.address().required(),
@@ -2,12 +2,10 @@ import { Validator, MedusaError } from "medusa-core-utils"
import { defaultRelations, defaultFields } from "./" import { defaultRelations, defaultFields } from "./"
/** /**
* @oas [post] /customers/{id} * @oas [post] /customers/me
* operationId: PostCustomersCustomer * operationId: PostCustomersCustomer
* summary: Update Customer details * summary: Update Customer details
* description: "Updates a Customer's saved details." * description: "Updates a Customer's saved details."
* parameters:
* - (path) id=* {string} The id of the Customer.
* requestBody: * requestBody:
* content: * content:
* application/json: * application/json:
@@ -45,7 +43,7 @@ import { defaultRelations, defaultFields } from "./"
* $ref: "#/components/schemas/customer" * $ref: "#/components/schemas/customer"
*/ */
export default async (req, res) => { export default async (req, res) => {
const { id } = req.params const id = req.user.customer_id
const schema = Validator.object().keys({ const schema = Validator.object().keys({
billing_address: Validator.address().optional(), billing_address: Validator.address().optional(),