Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(auth): Migrate auth module to DML #10387

Merged
merged 3 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 53 additions & 7 deletions packages/modules/auth/src/migrations/.snapshot-medusa-auth.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"namespaces": ["public"],
"namespaces": [
"public"
],
"name": "public",
"tables": [
{
Expand Down Expand Up @@ -43,14 +45,34 @@
"length": 6,
"default": "now()",
"mappedType": "datetime"
},
"deleted_at": {
"name": "deleted_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"length": 6,
"mappedType": "datetime"
}
},
"name": "auth_identity",
"schema": "public",
"indexes": [
{
"keyName": "IDX_auth_identity_deleted_at",
"columnNames": [],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_auth_identity_deleted_at\" ON \"auth_identity\" (deleted_at) WHERE deleted_at IS NULL"
},
{
"keyName": "auth_identity_pkey",
"columnNames": ["id"],
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
Expand Down Expand Up @@ -136,6 +158,16 @@
"length": 6,
"default": "now()",
"mappedType": "datetime"
},
"deleted_at": {
"name": "deleted_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"length": 6,
"mappedType": "datetime"
}
},
"name": "provider_identity",
Expand All @@ -147,19 +179,29 @@
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_provider_identity_auth_identity_id\" ON \"provider_identity\" (auth_identity_id)"
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_provider_identity_auth_identity_id\" ON \"provider_identity\" (auth_identity_id) WHERE deleted_at IS NULL"
},
{
"keyName": "IDX_provider_identity_deleted_at",
"columnNames": [],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_provider_identity_deleted_at\" ON \"provider_identity\" (deleted_at) WHERE deleted_at IS NULL"
},
{
"keyName": "IDX_provider_identity_provider_entity_id",
"columnNames": [],
"composite": false,
"primary": false,
"unique": false,
"expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_provider_identity_provider_entity_id\" ON \"provider_identity\" (entity_id, provider)"
"expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_provider_identity_provider_entity_id\" ON \"provider_identity\" (entity_id, provider) WHERE deleted_at IS NULL"
},
{
"keyName": "provider_identity_pkey",
"columnNames": ["id"],
"columnNames": [
"id"
],
"composite": false,
"primary": true,
"unique": true
Expand All @@ -169,9 +211,13 @@
"foreignKeys": {
"provider_identity_auth_identity_id_foreign": {
"constraintName": "provider_identity_auth_identity_id_foreign",
"columnNames": ["auth_identity_id"],
"columnNames": [
"auth_identity_id"
],
"localTableName": "public.provider_identity",
"referencedColumnNames": ["id"],
"referencedColumnNames": [
"id"
],
"referencedTableName": "public.auth_identity",
"deleteRule": "cascade",
"updateRule": "cascade"
Expand Down
31 changes: 31 additions & 0 deletions packages/modules/auth/src/migrations/Migration20241202100304.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Migration } from "@mikro-orm/migrations"

export class Migration20241202100304 extends Migration {
async up(): Promise<void> {
this.addSql(
'alter table if exists "auth_identity" add column if not exists "deleted_at" timestamptz null;'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_auth_identity_deleted_at" ON "auth_identity" (deleted_at) WHERE deleted_at IS NULL;'
)

this.addSql(
'alter table if exists "provider_identity" add column if not exists "deleted_at" timestamptz null;'
)
this.addSql(
'CREATE INDEX IF NOT EXISTS "IDX_provider_identity_deleted_at" ON "provider_identity" (deleted_at) WHERE deleted_at IS NULL;'
)
Comment on lines +5 to +17
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOTE: The entities were not soft deletable and are now by default, this is why there is this migration.

}

async down(): Promise<void> {
this.addSql('drop index if exists "IDX_auth_identity_deleted_at";')
this.addSql(
'alter table if exists "auth_identity" drop column if exists "deleted_at";'
)

this.addSql('drop index if exists "IDX_provider_identity_deleted_at";')
this.addSql(
'alter table if exists "provider_identity" drop column if exists "deleted_at";'
)
}
}
55 changes: 12 additions & 43 deletions packages/modules/auth/src/models/auth-identity.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,14 @@
import {
BeforeCreate,
Collection,
Entity,
OneToMany,
OnInit,
PrimaryKey,
Property,
} from "@mikro-orm/core"

import { generateEntityId } from "@medusajs/framework/utils"
import ProviderIdentity from "./provider-identity"

@Entity()
export default class AuthIdentity {
@PrimaryKey({ columnType: "text" })
id!: string

@OneToMany(() => ProviderIdentity, (o) => o.auth_identity)
provider_identities = new Collection<ProviderIdentity>(this)

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

@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
import { model } from "@medusajs/framework/utils"
import { ProviderIdentity } from "./provider-identity"

export const AuthIdentity = model
.define("auth_identity", {
id: model.id({ prefix: "authid" }).primaryKey(),
provider_identities: model.hasMany(() => ProviderIdentity, {
mappedBy: "auth_identity",
}),
app_metadata: model.json().nullable(),
})
created_at: Date

@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
.cascades({
delete: ["provider_identities"],
})
updated_at: Date

@BeforeCreate()
@OnInit()
onCreate() {
this.id = generateEntityId(this.id, "authid")
}
}
4 changes: 2 additions & 2 deletions packages/modules/auth/src/models/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { default as AuthIdentity } from "./auth-identity"
export { default as ProviderIdentity } from "./provider-identity"
export { AuthIdentity } from "./auth-identity"
export { ProviderIdentity } from "./provider-identity"
104 changes: 20 additions & 84 deletions packages/modules/auth/src/models/provider-identity.ts
Original file line number Diff line number Diff line change
@@ -1,85 +1,21 @@
import {
BeforeCreate,
Entity,
ManyToOne,
OnInit,
PrimaryKey,
Property,
Rel,
} from "@mikro-orm/core"

import {
createPsqlIndexStatementHelper,
generateEntityId,
} from "@medusajs/framework/utils"
import AuthIdentity from "./auth-identity"

const providerEntityIdIndexName = "IDX_provider_identity_provider_entity_id"
const providerEntityIdIndexStatement = createPsqlIndexStatementHelper({
name: providerEntityIdIndexName,
tableName: "provider_identity",
columns: ["entity_id", "provider"],
unique: true,
})

const authIdentityIndexName = "IDX_provider_identity_auth_identity_id"
const authIdentityIndexStatement = createPsqlIndexStatementHelper({
name: authIdentityIndexName,
tableName: "provider_identity",
columns: ["auth_identity_id"],
})

@Entity()
@providerEntityIdIndexStatement.MikroORMIndex()
@authIdentityIndexStatement.MikroORMIndex()
export default class ProviderIdentity {
@PrimaryKey({ columnType: "text" })
id!: string

@Property({ columnType: "text" })
entity_id: string

@Property({ columnType: "text" })
provider: string

@ManyToOne(() => AuthIdentity, {
columnType: "text",
fieldName: "auth_identity_id",
mapToPk: true,
onDelete: "cascade",
})
auth_identity_id: string

@ManyToOne(() => AuthIdentity, {
persist: false,
})
auth_identity: Rel<AuthIdentity>

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

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

@Property({
onCreate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
})
created_at: Date

@Property({
onCreate: () => new Date(),
onUpdate: () => new Date(),
columnType: "timestamptz",
defaultRaw: "now()",
import { model } from "@medusajs/framework/utils"
import { AuthIdentity } from "./auth-identity"

export const ProviderIdentity = model
.define("provider_identity", {
id: model.id().primaryKey(),
entity_id: model.text(),
provider: model.text(),
auth_identity: model.belongsTo(() => AuthIdentity, {
mappedBy: "provider_identities",
}),
user_metadata: model.json().nullable(),
provider_metadata: model.json().nullable(),
})
updated_at: Date

@BeforeCreate()
@OnInit()
onCreate() {
this.id = generateEntityId(this.id, "provid")
this.auth_identity_id ??= this.auth_identity?.id ?? null
}
}
.indexes([
{
name: "IDX_provider_identity_provider_entity_id",
on: ["entity_id", "provider"],
unique: true,
},
])
9 changes: 7 additions & 2 deletions packages/modules/auth/src/services/auth-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
AuthTypes,
Context,
DAL,
InferEntityType,
InternalModuleDeclaration,
Logger,
ModuleJoinerConfig,
Expand Down Expand Up @@ -35,8 +36,12 @@ export default class AuthModuleService
implements AuthTypes.IAuthModuleService
{
protected baseRepository_: DAL.RepositoryService
protected authIdentityService_: ModulesSdkTypes.IMedusaInternalService<AuthIdentity>
protected providerIdentityService_: ModulesSdkTypes.IMedusaInternalService<ProviderIdentity>
protected authIdentityService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof AuthIdentity>
>
protected providerIdentityService_: ModulesSdkTypes.IMedusaInternalService<
InferEntityType<typeof ProviderIdentity>
>
protected readonly authProviderService_: AuthProviderService

constructor(
Expand Down