This commit is contained in:
Joseph J Helfenbein
2025-01-25 00:55:08 -05:00
parent e79aeffdc3
commit e3aff8c229
7 changed files with 324 additions and 2 deletions

View File

@@ -0,0 +1,60 @@
import mongoose from 'mongoose';
import { User } from '../../../models/User';
import crypto from 'crypto';
const CLERK_WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET;
async function connectDB() {
if (mongoose.connection.readyState >= 1) return;
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
}
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).send('Method Not Allowed');
}
try {
const webhookSignature = req.headers['clerk-signature'];
const payload = JSON.stringify(req.body);
const hmac = crypto.createHmac('sha256', CLERK_WEBHOOK_SECRET);
hmac.update(payload);
const computedSignature = hmac.digest('hex');
if (computedSignature !== webhookSignature) {
return res.status(400).send('Invalid webhook signature');
}
await connectDB();
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).send('Name and email are required');
}
let user = await User.findOne({ email });
if (user) {
return res.status(400).send('User already exists');
}
user = new User({
name,
email,
role: 'patient',
medicalConditions: [],
medications: [],
});
await user.save();
res.status(200).json({ message: 'User successfully created' });
} catch (error) {
console.error(error);
res.status(500).send('Internal server error');
}
}

33
src/app/lib/connectDB.js Normal file
View File

@@ -0,0 +1,33 @@
import mongoose from "mongoose";
const DATABASE_URL = process.env.MONGO_URI;
if (!DATABASE_URL) {
throw new Error("Please define the DATABASE_URL environment variable inside .env.local");
}
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
async function connectDB() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect(DATABASE_URL, opts).then((mongoose) => {
return mongoose;
});
}
cached.conn = await cached.promise;
return cached.conn;
}
export default connectDB;