Skip to content

Support mapped schema field #35

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/some-corners-relate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'better-auth-harmony': minor
---

Support mapped schema field (#31 thanks @kdcokenny)
113 changes: 113 additions & 0 deletions packages/plugins/src/email/email-schema.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { afterAll, describe, expect, it, vi } from 'vitest';
// eslint-disable-next-line import/no-relative-packages -- couldn't find a better way to include it
import { getTestInstance } from '../../../../better-auth/packages/better-auth/src/test-utils/test-instance';
import emailHarmony, { type UserWithNormalizedEmail } from '.';
import { allEmail, allEmailSignIn, emailForget, emailSignUp } from './matchers';
// eslint-disable-next-line import/no-relative-packages -- couldn't find a better way to include it
import type { BetterAuthPlugin } from '../../../../better-auth/packages/better-auth/src/types';

interface SQLiteDB {
close: () => Promise<void>;
}

describe('Mapped schema', async () => {
const mockSendEmail = vi.fn();
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- false positive
let token = '';

const { client, db, auth } = await getTestInstance(
{
emailAndPassword: {
enabled: true,
async sendResetPassword({ url }) {
token = url.split('?')[0]?.split('/').pop() ?? '';
await mockSendEmail();
}
},
plugins: [
emailHarmony({
allowNormalizedSignin: true,
matchers: {
signIn: [emailForget, allEmailSignIn, emailSignUp],
validation: [emailForget, allEmail]
},
schema: {
user: {
fields: {
normalizedEmail: 'normalized_email'
}
}
}
}) as BetterAuthPlugin
]
},
{
disableTestUser: true
}
);

afterAll(async () => {
// TODO: Open PR for better-auth/src/test-utils/test-instance
await (auth.options.database as unknown as SQLiteDB).close();
});

describe('signup', () => {
it('should normalize email', async () => {
const rawEmail = '[email protected]';
await client.signUp.email({
email: rawEmail,
password: 'new-password',
name: 'new-name'
});
const userYes = await db.findOne<UserWithNormalizedEmail>({
model: 'user',
where: [
{
field: 'email',
value: rawEmail
}
]
});
// expect(userNo?.email).toBeUndefined();
expect(userYes?.email).toBe(rawEmail);
});

it('should reject temporary emails', async () => {
const rawEmail = '[email protected]';
const { error } = await client.signUp.email({
email: rawEmail,
password: 'new-password',
name: 'new-name'
});
expect(error).not.toBeNull();
});

it('should prevent signups with email variations', async () => {
const rawEmail = '[email protected]';
await client.signUp.email({
email: rawEmail,
password: 'new-password',
name: 'new-name'
});
const user = await db.findOne<UserWithNormalizedEmail>({
model: 'user',
where: [
{
field: 'normalizedEmail',
value: '[email protected]'
}
]
});
expect(user?.email).toBe(rawEmail);

// Duplicate signup attempt
const { error } = await client.signUp.email({
email: '[email protected]',
password: 'new-password',
name: 'new-name'
});

expect(error?.status).toBe(422);
});
});
});
13 changes: 13 additions & 0 deletions packages/plugins/src/email/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ export interface UserWithNormalizedEmail extends User {
normalizedEmail?: string | null;
}

export interface EmailHarmonySchema {
user: {
fields: {
/** Map the normalizedEmail field name to a custom value */
normalizedEmail?: string;
};
};
}

export interface EmailHarmonyOptions {
/**
* Allow logging in with any version of the unnormalized email address. Also works for password
Expand Down Expand Up @@ -57,6 +66,8 @@ export interface EmailHarmonyOptions {
*/
validation?: Matcher[];
};
/** Pass the `schema` option to customize the field names */
schema?: EmailHarmonySchema;
}

interface Context {
Expand Down Expand Up @@ -84,6 +95,7 @@ const emailHarmony = ({
allowNormalizedSignin = false,
validator = validateEmail,
matchers = {},
schema,
normalizer = normalizeEmail
}: EmailHarmonyOptions = {}): BetterAuthPlugin =>
({
Expand Down Expand Up @@ -126,6 +138,7 @@ const emailHarmony = ({
fields: {
normalizedEmail: {
type: 'string',
fieldName: schema?.user.fields.normalizedEmail ?? 'normalizedEmail',
required: false,
unique: true,
input: false,
Expand Down