feat(auth): Revamp authentication setup (#7387)

* chore: Clean up authentication middlewares

* chore: Rename AuthUser to AuthIdentity

* feat: Define link between user, customer, and auth identity

* feat: Use links for auth, update auth context content

* fix: Adjust user create command with new auth setup

* fix: Make auth login more dynamic, review fixes

* fix: Change test assertions for created by
This commit is contained in:
Stevche Radevski
2024-05-22 10:27:32 +02:00
committed by GitHub
parent b7df447682
commit 5ede560f70
88 changed files with 887 additions and 1014 deletions
@@ -1 +0,0 @@
export * from "./steps"
@@ -1 +0,0 @@
export * from "./set-auth-app-metadata"
@@ -1,60 +0,0 @@
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IAuthModuleService } from "@medusajs/types"
import { isDefined } from "@medusajs/utils"
type StepInput = {
authUserId: string
key: string
value: string
}
export const setAuthAppMetadataStepId = "set-auth-app-metadata"
export const setAuthAppMetadataStep = createStep(
setAuthAppMetadataStepId,
async (data: StepInput, { container }) => {
const service = container.resolve<IAuthModuleService>(
ModuleRegistrationName.AUTH
)
const authUser = await service.retrieve(data.authUserId)
const appMetadata = authUser.app_metadata || {}
if (isDefined(appMetadata[data.key])) {
throw new Error(`Key ${data.key} already exists in app metadata`)
}
appMetadata[data.key] = data.value
await service.update({
id: authUser.id,
app_metadata: appMetadata,
})
return new StepResponse(authUser, { id: authUser.id, key: data.key })
},
async (idAndKey, { container }) => {
if (!idAndKey) {
return
}
const { id, key } = idAndKey
const service = container.resolve<IAuthModuleService>(
ModuleRegistrationName.AUTH
)
const authUser = await service.retrieve(id)
const appMetadata = authUser.app_metadata || {}
if (isDefined(appMetadata[key])) {
delete appMetadata[key]
}
await service.update({
id: authUser.id,
app_metadata: appMetadata,
})
}
)
@@ -1,11 +1,12 @@
import { CreateCustomerDTO, CustomerDTO } from "@medusajs/types"
import { createWorkflow, WorkflowData } from "@medusajs/workflows-sdk"
import { createCustomersStep } from "../steps"
import { setAuthAppMetadataStep } from "../../auth/steps"
import { transform } from "@medusajs/workflows-sdk"
import { Modules } from "@medusajs/modules-sdk"
import { createLinkStep } from "../../common"
type WorkflowInput = {
authUserId: string
authIdentityId: string
customersData: CreateCustomerDTO
}
@@ -20,12 +21,19 @@ export const createCustomerAccountWorkflow = createWorkflow(
(customers: CustomerDTO[]) => customers[0]
)
setAuthAppMetadataStep({
authUserId: input.authUserId,
key: "customer_id",
value: customer.id,
})
const link = transform(
{ customer, authIdentityId: input.authIdentityId },
(data) => {
return [
{
[Modules.CUSTOMER]: { customer_id: data.customer.id },
[Modules.AUTH]: { auth_identity_id: data.authIdentityId },
},
]
}
)
createLinkStep(link)
return customer
}
)
-1
View File
@@ -1,5 +1,4 @@
export * from "./api-key"
export * from "./auth"
export * from "./common"
export * from "./customer"
export * from "./customer-group"
@@ -4,10 +4,11 @@ import {
createWorkflow,
transform,
} from "@medusajs/workflows-sdk"
import { setAuthAppMetadataStep } from "../../auth"
import { createUsersStep } from "../../user"
import { deleteInvitesStep } from "../steps"
import { validateTokenStep } from "../steps/validate-token"
import { Modules } from "@medusajs/modules-sdk"
import { createLinkStep } from "../../common"
export const acceptInviteWorkflowId = "accept-invite-workflow"
export const acceptInviteWorkflow = createWorkflow(
@@ -31,18 +32,20 @@ export const acceptInviteWorkflow = createWorkflow(
const users = createUsersStep(createUserInput)
const authUserInput = transform({ input, users }, ({ input, users }) => {
const createdUser = users[0]
return {
authUserId: input.auth_user_id,
key: "user_id",
value: createdUser.id,
const link = transform(
{ users, authIdentityId: input.auth_identity_id },
(data) => {
const user = data.users[0]
return [
{
[Modules.USER]: { user_id: user.id },
[Modules.AUTH]: { auth_identity_id: data.authIdentityId },
},
]
}
})
setAuthAppMetadataStep(authUserInput)
)
createLinkStep(link)
deleteInvitesStep([invite.id])
return users
@@ -4,11 +4,12 @@ import {
createWorkflow,
transform,
} from "@medusajs/workflows-sdk"
import { setAuthAppMetadataStep } from "../../auth/steps"
import { createUsersStep } from "../steps"
import { Modules } from "@medusajs/modules-sdk"
import { createLinkStep } from "../../common"
type WorkflowInput = {
authUserId: string
authIdentityId: string
userData: CreateUserDTO
}
@@ -17,15 +18,21 @@ export const createUserAccountWorkflow = createWorkflow(
createUserAccountWorkflowId,
(input: WorkflowData<WorkflowInput>): WorkflowData<UserDTO> => {
const users = createUsersStep([input.userData])
const user = transform(users, (users: UserDTO[]) => users[0])
setAuthAppMetadataStep({
authUserId: input.authUserId,
key: "user_id",
value: user.id,
})
const link = transform(
{ user, authIdentityId: input.authIdentityId },
(data) => {
return [
{
[Modules.USER]: { user_id: data.user.id },
[Modules.AUTH]: { auth_identity_id: data.authIdentityId },
},
]
}
)
createLinkStep(link)
return user
}
)
@@ -3,11 +3,11 @@ import { BaseFilterable } from "../../dal"
/**
* @interface
*
* The auth user details.
* The auth identity details.
*/
export type AuthUserDTO = {
export type AuthIdentityDTO = {
/**
* The ID of the auth user.
* The ID of the auth identity.
*/
id: string
@@ -23,7 +23,7 @@ export type AuthUserDTO = {
entity_id: string
/**
* The scope of the auth user. For example,
* The scope of the auth identity. For example,
* `admin` or `store`.
*/
scope: string
@@ -47,11 +47,11 @@ export type AuthUserDTO = {
/**
* @interface
*
* The auth user to be created.
* The auth identity to be created.
*/
export type CreateAuthUserDTO = {
export type CreateAuthIdentityDTO = {
/**
* The ID of the auth user.
* The ID of the auth identity.
*/
id?: string
@@ -68,7 +68,7 @@ export type CreateAuthUserDTO = {
entity_id: string
/**
* The scope of the auth user. For example,
* The scope of the auth identity. For example,
* `admin` or `store`.
*/
scope: string
@@ -92,11 +92,11 @@ export type CreateAuthUserDTO = {
/**
* @interface
*
* The attributes to update in the auth user.
* The attributes to update in the auth identity.
*/
export type UpdateAuthUserDTO = {
export type UpdateAuthIdentityDTO = {
/**
* The ID of the auth user.
* The ID of the auth identity.
*/
id: string
@@ -117,17 +117,17 @@ export type UpdateAuthUserDTO = {
}
/**
* The filters to apply on the retrieved auth user.
* The filters to apply on the retrieved auth identity.
*/
export interface FilterableAuthUserProps
extends BaseFilterable<FilterableAuthUserProps> {
export interface FilterableAuthIdentityProps
extends BaseFilterable<FilterableAuthIdentityProps> {
/**
* The IDs to filter the auth user by.
* The IDs to filter the auth identity by.
*/
id?: string[]
/**
* Filter the auth users by the ID of their auth provider.
* Filter the auth identitys by the ID of their auth provider.
*/
provider?: string[] | string
}
+1 -1
View File
@@ -1,2 +1,2 @@
export * from "./auth-user"
export * from "./auth-identity"
export * from "./provider"
@@ -12,7 +12,7 @@ export type AuthenticationResponse = {
/**
* The authenticated user's details.
*/
authUser?: any
authIdentity?: any
/**
* If an error occurs during the authentication process,
+62 -56
View File
@@ -1,10 +1,10 @@
import {
AuthUserDTO,
AuthIdentityDTO,
AuthenticationInput,
AuthenticationResponse,
CreateAuthUserDTO,
FilterableAuthUserProps,
UpdateAuthUserDTO,
CreateAuthIdentityDTO,
FilterableAuthIdentityProps,
UpdateAuthIdentityDTO,
} from "./common"
import { Context } from "../shared-context"
import { FindConfig } from "../common"
@@ -37,7 +37,7 @@ export interface IAuthModuleService extends IModuleService {
* `req` is an instance of the `MedusaRequest` object:
*
* ```ts
* const { success, authUser, location, error } =
* const { success, authIdentity, location, error } =
* await authModuleService.authenticate("emailpass", {
* url: req.url,
* headers: req.headers,
@@ -75,7 +75,7 @@ export interface IAuthModuleService extends IModuleService {
* `req` is an instance of the `MedusaRequest` object:
*
* ```ts
* const { success, authUser, error, successRedirectUrl } =
* const { success, authIdentity, error, successRedirectUrl } =
* await authModuleService.validateCallback("google", {
* url: req.url,
* headers: req.headers,
@@ -93,37 +93,37 @@ export interface IAuthModuleService extends IModuleService {
): Promise<AuthenticationResponse>
/**
* This method retrieves an auth user by its ID.
* This method retrieves an auth identity by its ID.
*
* @param {string} id - The ID of the auth user.
* @param {FindConfig<AuthUserDTO>} config - The configurations determining how the auth user is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a auth user.
* @param {string} id - The ID of the auth identity.
* @param {FindConfig<AuthIdentityDTO>} config - The configurations determining how the auth identity is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a auth identity.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<AuthUserDTO>} The retrieved auth user.
* @returns {Promise<AuthIdentityDTO>} The retrieved auth identity.
*
* @example
* const authUser = await authModuleService.retrieve("authusr_1")
* const authIdentity = await authModuleService.retrieve("authusr_1")
*/
retrieve(
id: string,
config?: FindConfig<AuthUserDTO>,
config?: FindConfig<AuthIdentityDTO>,
sharedContext?: Context
): Promise<AuthUserDTO>
): Promise<AuthIdentityDTO>
/**
* This method retrieves a paginated list of auth users based on optional filters and configuration.
* This method retrieves a paginated list of auth identitys based on optional filters and configuration.
*
* @param {FilterableAuthUserProps} filters - The filters to apply on the retrieved auth users.
* @param {FindConfig<AuthUserDTO>} config - The configurations determining how the auth user is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a auth user.
* @param {FilterableAuthIdentityProps} filters - The filters to apply on the retrieved auth identitys.
* @param {FindConfig<AuthIdentityDTO>} config - The configurations determining how the auth identity is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a auth identity.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<AuthUserDTO[]>} The list of auth users.
* @returns {Promise<AuthIdentityDTO[]>} The list of auth identitys.
*
* @example
* To retrieve a list of auth users using their IDs:
* To retrieve a list of auth identitys using their IDs:
*
* ```ts
* const authUsers = await authModuleService.list({
* const authIdentities = await authModuleService.list({
* id: ["authusr_123", "authusr_321"],
* })
* ```
@@ -131,7 +131,7 @@ export interface IAuthModuleService extends IModuleService {
* By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
*
* ```ts
* const authUsers = await authModuleService.list(
* const authIdentities = await authModuleService.list(
* {
* id: ["authusr_123", "authusr_321"],
* },
@@ -143,25 +143,25 @@ export interface IAuthModuleService extends IModuleService {
* ```
*/
list(
filters?: FilterableAuthUserProps,
config?: FindConfig<AuthUserDTO>,
filters?: FilterableAuthIdentityProps,
config?: FindConfig<AuthIdentityDTO>,
sharedContext?: Context
): Promise<AuthUserDTO[]>
): Promise<AuthIdentityDTO[]>
/**
* This method retrieves a paginated list of auth users along with the total count of available auth users satisfying the provided filters.
* This method retrieves a paginated list of auth identitys along with the total count of available auth identitys satisfying the provided filters.
*
* @param {FilterableAuthUserProps} filters - The filters to apply on the retrieved auth users.
* @param {FindConfig<AuthUserDTO>} config - The configurations determining how the auth user is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a auth user.
* @param {FilterableAuthIdentityProps} filters - The filters to apply on the retrieved auth identitys.
* @param {FindConfig<AuthIdentityDTO>} config - The configurations determining how the auth identity is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a auth identity.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<[AuthUserDTO[], number]>} The list of auth users along with their total count.
* @returns {Promise<[AuthIdentityDTO[], number]>} The list of auth identitys along with their total count.
*
* @example
* To retrieve a list of auth users using their IDs:
* To retrieve a list of auth identitys using their IDs:
*
* ```ts
* const [authUsers, count] =
* const [authIdentities, count] =
* await authModuleService.listAndCount({
* id: ["authusr_123", "authusr_321"],
* })
@@ -170,7 +170,7 @@ export interface IAuthModuleService extends IModuleService {
* By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
*
* ```ts
* const [authUsers, count] =
* const [authIdentities, count] =
* await authModuleService.listAndCount(
* {
* id: ["authusr_123", "authusr_321"],
@@ -183,20 +183,20 @@ export interface IAuthModuleService extends IModuleService {
* ```
*/
listAndCount(
filters?: FilterableAuthUserProps,
config?: FindConfig<AuthUserDTO>,
filters?: FilterableAuthIdentityProps,
config?: FindConfig<AuthIdentityDTO>,
sharedContext?: Context
): Promise<[AuthUserDTO[], number]>
): Promise<[AuthIdentityDTO[], number]>
/**
* This method creates auth users.
* This method creates auth identitys.
*
* @param {CreateAuthUserDTO[]} data - The auth users to be created.
* @param {CreateAuthIdentityDTO[]} data - The auth identitys to be created.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<AuthUserDTO[]>} The created auth users.
* @returns {Promise<AuthIdentityDTO[]>} The created auth identitys.
*
* @example
* const authUsers = await authModuleService.create([
* const authIdentities = await authModuleService.create([
* {
* provider: "emailpass",
* entity_id: "user@example.com",
@@ -210,35 +210,38 @@ export interface IAuthModuleService extends IModuleService {
* ])
*/
create(
data: CreateAuthUserDTO[],
data: CreateAuthIdentityDTO[],
sharedContext?: Context
): Promise<AuthUserDTO[]>
): Promise<AuthIdentityDTO[]>
/**
* This method creates an auth user.
* This method creates an auth identity.
*
* @param {CreateAuthUserDTO} data - The auth user to be created.
* @param {CreateAuthIdentityDTO} data - The auth identity to be created.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<AuthUserDTO>} The created auth user.
* @returns {Promise<AuthIdentityDTO>} The created auth identity.
*
* @example
* const authUser = await authModuleService.create({
* const authIdentity = await authModuleService.create({
* provider: "emailpass",
* entity_id: "user@example.com",
* scope: "admin",
* })
*/
create(data: CreateAuthUserDTO, sharedContext?: Context): Promise<AuthUserDTO>
create(
data: CreateAuthIdentityDTO,
sharedContext?: Context
): Promise<AuthIdentityDTO>
/**
* This method updates existing auths.
*
* @param {UpdateAuthUserDTO[]} data - The attributes to update in the auth users.
* @param {UpdateAuthIdentityDTO[]} data - The attributes to update in the auth identitys.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<AuthUserDTO[]>} The updated auths.
* @returns {Promise<AuthIdentityDTO[]>} The updated auths.
*
* @example
* const authUsers = await authModuleService.update([
* const authIdentities = await authModuleService.update([
* {
* id: "authusr_123",
* app_metadata: {
@@ -248,26 +251,29 @@ export interface IAuthModuleService extends IModuleService {
* ])
*/
update(
data: UpdateAuthUserDTO[],
data: UpdateAuthIdentityDTO[],
sharedContext?: Context
): Promise<AuthUserDTO[]>
): Promise<AuthIdentityDTO[]>
/**
* This method updates an existing auth.
*
* @param {UpdateAuthUserDTO} data - The attributes to update in the auth user.
* @param {UpdateAuthIdentityDTO} data - The attributes to update in the auth identity.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<AuthUserDTO>} The updated auth.
* @returns {Promise<AuthIdentityDTO>} The updated auth.
*
* @example
* const authUser = await authModuleService.update({
* const authIdentity = await authModuleService.update({
* id: "authusr_123",
* app_metadata: {
* test: true,
* },
* })
*/
update(data: UpdateAuthUserDTO, sharedContext?: Context): Promise<AuthUserDTO>
update(
data: UpdateAuthIdentityDTO,
sharedContext?: Context
): Promise<AuthIdentityDTO>
/**
* This method deletes a auth by its ID.
@@ -1,6 +1,6 @@
export interface AcceptInviteWorkflowInputDTO {
invite_token: string
auth_user_id: string
auth_identity_id: string
user: {
email?: string
first_name?: string | null
-1
View File
@@ -48,7 +48,6 @@ export * from "./rules"
export * from "./selector-constraints-to-string"
export * from "./set-metadata"
export * from "./simple-hash"
export * from "./string-or-regex-equals"
export * from "./string-to-select-relation-object"
export * from "./stringify-circular"
export * from "./to-camel-case"
@@ -1,9 +0,0 @@
export const stringEqualsOrRegexMatch = (
stringOrRegex: string | RegExp,
testString: string
) => {
if (stringOrRegex instanceof RegExp) {
return stringOrRegex.test(testString)
}
return stringOrRegex === testString
}
+12
View File
@@ -86,4 +86,16 @@ export const LINKS = {
Modules.FULFILLMENT,
"fulfillment_id"
),
UserAuth: composeLinkName(
Modules.USER,
"user_id",
Modules.AUTH,
"auth_identity_id"
),
CustomerAuth: composeLinkName(
Modules.CUSTOMER,
"customer_id",
Modules.AUTH,
"auth_identity_id"
),
}