Skip to content

Commit

Permalink
Merge pull request #17 from ETLOnline/feature/create-db-user-on-webhook
Browse files Browse the repository at this point in the history
fix(auth): dont create new user if user is already created
  • Loading branch information
usama-tariq1 authored Dec 7, 2024
2 parents 1473939 + 9c61ea0 commit 9949f53
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/app/api/webhook/user-created/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Webhook } from 'svix'
import { headers } from 'next/headers'
import { WebhookEvent } from '@clerk/nextjs/server'
import { InsertUser } from '@/src/db/schema'
import { CreateUser } from '@/src/db/data-access/user/query'
import { CreateUser, SelectUserByEmail, SelectUserById } from '@/src/db/data-access/user/query'

export async function POST(req: Request) {

Expand Down Expand Up @@ -59,6 +59,14 @@ export async function POST(req: Request) {

if (evt.type === 'user.created') {
const userObj = evt.data

const userById = await SelectUserById(userObj.id)
const userByEmail = await SelectUserByEmail(userObj.email_addresses[0].email_address)

if (userById || userByEmail) {
return new Response('', { status: 200 })
}

const newUser:InsertUser ={
first_name: userObj.first_name || '',
last_name: userObj.last_name || '',
Expand Down
9 changes: 8 additions & 1 deletion src/db/data-access/user/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,11 @@ export async function SelectUserById(id: string) {
return await db.query.usersTable.findFirst({
where: eq(usersTable.external_auth_id, id)
});
}
}

export async function SelectUserByEmail(email: string) {
return await db.query.usersTable.findFirst({
where: eq(usersTable.email, email)
});
}

0 comments on commit 9949f53

Please sign in to comment.