Skip to content

Commit

Permalink
add entity_id and update provider
Browse files Browse the repository at this point in the history
  • Loading branch information
pKorsholm committed Jan 17, 2024
1 parent 2674171 commit 0d5332b
Show file tree
Hide file tree
Showing 9 changed files with 107 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe("AuthenticationModuleService - AuthProvider", () => {
provider: "usernamePassword",
provider_metadata: {
email,
password_hash: passwordHash,
password: passwordHash,
},
},
])
Expand Down
5 changes: 3 additions & 2 deletions packages/authentication/src/initialize/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import {
ExternalModuleDeclaration,
InternalModuleDeclaration,
MedusaModule,
MODULE_PACKAGE_NAMES,
MedusaModule,
Modules,
} from "@medusajs/modules-sdk"
import { IAuthenticationModuleService, ModulesSdkTypes } from "@medusajs/types"
import { moduleDefinition } from "../module-definition"

import { InitializeModuleInjectableDependencies } from "../types"
import { moduleDefinition } from "../module-definition"

export const initialize = async (
options?:
Expand Down
20 changes: 15 additions & 5 deletions packages/authentication/src/loaders/providers.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { LoaderOptions, ModulesSdkTypes } from "@medusajs/types"
import { asClass } from "awilix"
import * as defaultProviders from "@providers"

import { LoaderOptions, ModulesSdkTypes } from "@medusajs/types"

import { AuthProviderService } from "@services"
import { ServiceTypes } from "@types"
import { asClass } from "awilix"

export default async ({
container,
Expand All @@ -20,10 +22,18 @@ export default async ({
const authProviderService: AuthProviderService = container.resolve(
"authProviderService"
)
let providers

const providers = await authProviderService.list({
provider: providersToLoad.map((p) => p.PROVIDER),
})
try {
providers = await authProviderService.list({
provider: providersToLoad.map((p) => p.PROVIDER),
})
} catch (error) {
if (error.name === "TableNotFoundException") {
// we are running loaders in migrations (or fail at a later point)
return
}
}

const loadedProviders = new Map(providers.map((p) => [p.provider, p]))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,15 @@
"nullable": false,
"mappedType": "text"
},
"entity_id": {
"name": "entity_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"mappedType": "text"
},
"provider_id": {
"name": "provider_id",
"type": "text",
Expand Down Expand Up @@ -117,6 +126,16 @@
"name": "auth_user",
"schema": "public",
"indexes": [
{
"keyName": "IDX_auth_user_provider_entity_id",
"columnNames": [
"provider_id",
"entity_id"
],
"composite": true,
"primary": false,
"unique": true
},
{
"keyName": "auth_user_pkey",
"columnNames": [
Expand Down
15 changes: 15 additions & 0 deletions packages/authentication/src/migrations/Migration20240115092929.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Migration } from '@mikro-orm/migrations';

export class Migration20240115092929 extends Migration {

async up(): Promise<void> {
this.addSql('alter table "auth_user" add column "entity_id" text not null;');
this.addSql('alter table "auth_user" add constraint "IDX_auth_user_provider_entity_id" unique ("provider_id", "entity_id");');
}

async down(): Promise<void> {
this.addSql('alter table "auth_user" drop constraint "IDX_auth_user_provider_entity_id";');
this.addSql('alter table "auth_user" drop column "entity_id";');
}

}
9 changes: 8 additions & 1 deletion packages/authentication/src/models/auth-user.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
import { generateEntityId } from "@medusajs/utils"
import {
BeforeCreate,
Cascade,
Entity,
Index,
ManyToOne,
OnInit,
OptionalProps,
PrimaryKey,
Property,
Unique,
} from "@mikro-orm/core"

import AuthProvider from "./auth-provider"
import { generateEntityId } from "@medusajs/utils"

type OptionalFields = "provider_metadata" | "app_metadata" | "user_metadata"

@Entity()
@Unique({ properties: ["provider","entity_id" ], name: "IDX_auth_user_provider_entity_id" })
export default class AuthUser {
[OptionalProps]: OptionalFields

@PrimaryKey({ columnType: "text" })
id!: string

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

@ManyToOne(() => AuthProvider, {
joinColumn: "provider",
fieldName: "provider_id",
Expand Down
19 changes: 9 additions & 10 deletions packages/authentication/src/providers/username-password.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import Scrypt from "scrypt-kdf"

import { AuthUserService } from "@services"
import {
AbstractAuthenticationModuleProvider,
AuthenticationResponse,
} from "@medusajs/types"

import { AuthUserService } from "@services"
import Scrypt from "scrypt-kdf"

class UsernamePasswordProvider extends AbstractAuthenticationModuleProvider {
public static PROVIDER = "usernamePassword"
public static DISPLAY_NAME = "Username/Password Authentication"
Expand All @@ -19,9 +19,9 @@ class UsernamePasswordProvider extends AbstractAuthenticationModuleProvider {
}

async authenticate(
userData: Record<string, unknown>
userData: Record<string, any>
): Promise<AuthenticationResponse> {
const { email, password } = userData
const { email, password } = userData.body

if (typeof password !== "string") {
return {
Expand All @@ -37,11 +37,10 @@ class UsernamePasswordProvider extends AbstractAuthenticationModuleProvider {
}
}

const [authUser] = await this.authUserSerivce_.list({
provider_metadata: {
email,
},
})
const authUser = await this.authUserSerivce_.retrieveByProviderAndEntityId(
email,
UsernamePasswordProvider.PROVIDER
)

const password_hash = authUser.provider_metadata?.password_hash

Expand Down
30 changes: 28 additions & 2 deletions packages/authentication/src/services/auth-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,45 @@ export default class AuthUserService<TEntity extends AuthUser = AuthUser> {

@InjectManager("authUserRepository_")
async retrieve(
provider: string,
id: string,
config: FindConfig<ServiceTypes.AuthUserDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity> {
return (await retrieveEntity<AuthUser, ServiceTypes.AuthUserDTO>({
id: provider,
id,
entityName: AuthUser.name,
repository: this.authUserRepository_,
config,
sharedContext,
})) as TEntity
}

@InjectManager("authUserRepository_")
async retrieveByProviderAndEntityId(
entityId: string,
provider: string,
config: FindConfig<ServiceTypes.AuthUserDTO> = {},
@MedusaContext() sharedContext: Context = {}
): Promise<TEntity> {
const queryConfig = ModulesSdkUtils.buildQuery<AuthUser>(
{ entity_id: entityId, provider },
{ ...config, take: 1 }
)
const [result] = await this.authUserRepository_.find(
queryConfig,
sharedContext
)

if (!result) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`AuthUser with entity_id: "${entityId}" and provider: "${provider}" not found`
)
}

return result
}

@InjectManager("authUserRepository_")
async list(
filters: ServiceTypes.FilterableAuthProviderProps = {},
Expand Down
14 changes: 9 additions & 5 deletions packages/authentication/src/services/authentication-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,11 +367,15 @@ export default class AuthenticationModuleService<
provider: string,
authenticationData: Record<string, unknown>,
@MedusaContext() sharedContext: Context = {}
): Promise<AuthenticationResponse> {
await this.retrieveAuthProvider(provider, {})

const registeredProvider =
this.getRegisteredAuthenticationProvider(provider)
): Promise<AuthenticationResponse> {
let registeredProvider
try {
await this.retrieveAuthProvider(provider, {})

registeredProvider = this.getRegisteredAuthenticationProvider(provider)
} catch (error) {
return { success: false, error: error.message }
}

return await registeredProvider.authenticate(authenticationData)
}
Expand Down

0 comments on commit 0d5332b

Please sign in to comment.