Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .changeset/icy-poems-wear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tern-secure/backend': patch
'@tern-secure/nextjs': patch
---

feat: add Postgres sync functions and update package configurations
1 change: 0 additions & 1 deletion packages/auth/src/instance/ternsecure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,6 @@ export class TernSecureAuth implements TernSecureAuthInterface {
}

this.#options = this.#initOptions(options);
console.debug('[TernSecureAuth] Loading with options:', this.#options);

if (this.#options.sdkMetadata) {
TernSecureAuth.sdkMetadata = this.#options.sdkMetadata;
Expand Down
3 changes: 1 addition & 2 deletions packages/auth/src/ui/components/sign-up/SignUpStart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import { useTernSecure } from '@tern-secure/shared/react';
import type { SignUpFormValues } from '@tern-secure/types';

import { cn } from '../../../lib/utils';
import { useTernSecureOptions } from '../../ctx';
import { useAuthSignUp, useSignUpContext } from '../../ctx';
import { useAuthSignUp, useSignUpContext,useTernSecureOptions } from '../../ctx';
import {
Alert,
AlertDescription,
Expand Down
5 changes: 5 additions & 0 deletions packages/backend/functions/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"main": "../dist/functions/index.js",
"module": "../dist/functions/index.mjs",
"types": "../dist/functions/index.d.ts"
}
15 changes: 13 additions & 2 deletions packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@
"default": "./dist/jwt/index.js"
}
},
"./functions": {
"import": {
"types": "./dist/functions/index.d.ts",
"default": "./dist/functions/index.mjs"
},
"require": {
"types": "./dist/functions/index.d.ts",
"default": "./dist/functions/index.js"
}
},
"./package.json": "./package.json"
},
"main": "./dist/index.js",
Expand All @@ -96,7 +106,6 @@
"dependencies": {
"@tern-secure/shared": "workspace:*",
"@tern-secure/types": "workspace:*",
"@upstash/redis": "^1.35.2",
"cookie": "1.0.2",
"jose": "^5.10.0",
"tslib": "catalog:repo"
Expand All @@ -107,7 +116,9 @@
"vitest-environment-miniflare": "2.14.4"
},
"peerDependencies": {
"firebase-admin": "catalog:peer-firebase"
"@upstash/redis": "^1.35.2",
"firebase-admin": "catalog:peer-firebase",
"firebase-functions": "^6.1.2"
},
"engines": {
"node": ">=20"
Expand Down
179 changes: 179 additions & 0 deletions packages/backend/src/functions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import type { UserRecord } from 'firebase-admin/auth';
import * as functions from 'firebase-functions/v1';

export interface PostgresSyncOptions {
/**
* A function that executes a SQL query.
* Compatible with 'pg' Pool.query or Client.query.
* You can pass `pool.query.bind(pool)` here.
*/
query: (text: string, params?: any[]) => Promise<any>;

/**
* The name of the table to insert users into.
* @example 'users'
* @example 'public.profiles'
*/
tableName: string;

/**
* Map Firebase UserRecord fields to your database columns.
* Key: Firebase field (e.g., 'uid', 'email', 'displayName', 'photoURL')
* Value: Database column name
*/
fieldMapping: Partial<Record<keyof UserRecord, string>>;

/**
* Optional: Add extra static values or computed values.
* @example { role: 'user', created_at: new Date() }
*/
extraFields?: (user: UserRecord) => Record<string, any>;

/**
* Optional: Callback to run after successful sync
*/
onSuccess?: (user: UserRecord) => Promise<void>;

/**
* Optional: Callback to run on error
*/
onError?: (error: any, user: UserRecord) => Promise<void>;
}

/**
* Creates a Firebase Authentication Trigger that syncs new users to a Postgres database.
*
* @example
* export const syncUser = createPostgresSync({
* query: pool.query.bind(pool),
* tableName: 'users',
* fieldMapping: {
* uid: 'id',
* email: 'email',
* displayName: 'full_name'
* }
* });
*/
export const createPostgresSync = (options: PostgresSyncOptions) => {
return functions.auth.user().onCreate(async (user) => {
const { query, tableName, fieldMapping, extraFields, onSuccess, onError } = options;

try {
const columns: string[] = [];
const values: any[] = [];
const placeholders: string[] = [];

// Handle mapped fields
Object.entries(fieldMapping).forEach(([userField, dbColumn]) => {
if (dbColumn) {
columns.push(dbColumn);
values.push((user as any)[userField]);
placeholders.push(`$${values.length}`);
}
});

// Handle extra fields
if (extraFields) {
const extras = extraFields(user);
Object.entries(extras).forEach(([column, value]) => {
columns.push(column);
values.push(value);
placeholders.push(`$${values.length}`);
});
}

if (columns.length === 0) {
console.warn('createPostgresSync: No fields mapped for insertion.');
return;
}

const queryText = `
INSERT INTO ${tableName} (${columns.join(', ')})
VALUES (${placeholders.join(', ')})
ON CONFLICT DO NOTHING
`;

await query(queryText, values);

if (onSuccess) {
await onSuccess(user);
}
} catch (error) {
console.error('createPostgresSync: Failed to sync user', error);
if (onError) {
await onError(error, user);
} else {
throw error;
}
}
});
};

export interface GenericSyncOptions {
/**
* Map Firebase UserRecord fields to your database columns/fields.
* Key: Firebase field (e.g., 'uid', 'email')
* Value: Your database field name
*/
fieldMapping: Partial<Record<keyof UserRecord, string>>;

/**
* Optional: Add extra static values or computed values.
*/
extraFields?: (user: UserRecord) => Record<string, any>;

/**
* Function to save the mapped data to your database.
* Receives a plain object with the mapped keys and values.
*/
syncFn: (data: Record<string, any>, user: UserRecord) => Promise<void>;

/**
* Optional: Callback to run on error
*/
onError?: (error: any, user: UserRecord) => Promise<void>;
}

/**
* Creates a generic Firebase Authentication Trigger for syncing users to any database (Prisma, Drizzle, Mongo, etc).
*
* @example
* export const syncUser = createGenericSync({
* fieldMapping: { uid: 'id', email: 'email' },
* syncFn: async (data) => {
* await prisma.user.create({ data });
* }
* });
*/
export const createGenericSync = (options: GenericSyncOptions) => {
return functions.auth.user().onCreate(async (user) => {
const { fieldMapping, extraFields, syncFn, onError } = options;

try {
const data: Record<string, any> = {};

// Handle mapped fields
Object.entries(fieldMapping).forEach(([userField, dbField]) => {
if (dbField) {
data[dbField] = (user as any)[userField];
}
});

// Handle extra fields
if (extraFields) {
const extras = extraFields(user);
Object.assign(data, extras);
}

await syncFn(data, user);

} catch (error) {
console.error('createGenericSync: Failed to sync user', error);
if (onError) {
await onError(error, user);
} else {
throw error;
}
}
});
};
2 changes: 1 addition & 1 deletion packages/backend/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { runAfterLast } from '../../scripts/utils';
import { name, version } from "./package.json";

const config: Options = {
entry: ['src/index.ts', 'src/admin/index.ts', 'src/auth/index.ts', 'src/jwt/index.ts', 'src/app-check/index.ts'],
entry: ['src/index.ts', 'src/admin/index.ts', 'src/auth/index.ts', 'src/jwt/index.ts', 'src/app-check/index.ts', 'src/functions/index.ts'],
onSuccess: `cpy 'src/runtime/**/*.{mjs,js,cjs}' dist/runtime`,
bundle: true,
sourcemap: true,
Expand Down
1 change: 0 additions & 1 deletion packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@
"tslib": "catalog:repo"
},
"peerDependencies": {
"@upstash/redis": "^1.35.2",
"firebase": "catalog:peer-firebase",
"next": "^13.5.7 || ^14.2.25 || ^15.2.3 || ^16",
"react": "catalog:peer-react",
Expand Down
12 changes: 0 additions & 12 deletions packages/nextjs/src/utils/redis.ts

This file was deleted.

24 changes: 21 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading