I think monorepo is fairly correct now but I don't know for sure

This commit is contained in:
2026-01-11 13:56:30 -05:00
parent 67daefb919
commit 674b224467
38 changed files with 485 additions and 412 deletions

View File

@@ -1,7 +1,7 @@
export default {
providers: [
{
domain: process.env.CLERK_ISSUER_URL,
domain: process.env.CONVEX_SITE_URL,
applicationID: 'convex',
},
],

View File

@@ -0,0 +1,114 @@
import Authentik from '@auth/core/providers/authentik';
import {
convexAuth,
getAuthUserId,
modifyAccountCredentials,
retrieveAccount,
} from '@convex-dev/auth/server';
import { ConvexError, v } from 'convex/values';
import type { Doc, Id } from './_generated/dataModel';
import type { MutationCtx, QueryCtx } from './_generated/server';
import { api } from './_generated/api';
import { action, mutation, query } from './_generated/server';
import { Password, validatePassword } from './custom/auth';
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
providers: [Authentik({ allowDangerousEmailAccountLinking: true }), Password],
});
const getUserById = async (
ctx: QueryCtx,
userId: Id<'users'>,
): Promise<Doc<'users'>> => {
const user = await ctx.db.get(userId);
if (!user) throw new ConvexError('User not found.');
return user;
};
const isSignedIn = async (ctx: QueryCtx): Promise<Doc<'users'> | null> => {
const userId = await getAuthUserId(ctx);
if (!userId) return null;
const user = await ctx.db.get(userId);
if (!user) return null;
return user;
};
export const getUser = query({
args: { userId: v.optional(v.id('users')) },
handler: async (ctx, args) => {
const user = await isSignedIn(ctx);
const userId = args.userId ?? user?._id;
if (!userId) throw new ConvexError('Not authenticated or no ID provided.');
return getUserById(ctx, userId);
},
});
export const getAllUsers = query(async (ctx) => {
const users = await ctx.db.query('users').collect();
return users ?? null;
});
export const getAllUserIds = query(async (ctx) => {
const users = await ctx.db.query('users').collect();
return users.map((u) => u._id);
});
export const updateUser = mutation({
args: {
name: v.optional(v.string()),
email: v.optional(v.string()),
image: v.optional(v.id('_storage')),
},
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new ConvexError('Not authenticated.');
const user = await ctx.db.get(userId);
if (!user) throw new ConvexError('User not found.');
const patch: Partial<{
name: string;
email: string;
image: Id<'_storage'>;
}> = {};
if (args.name !== undefined) patch.name = args.name;
if (args.email !== undefined) patch.email = args.email;
if (args.image !== undefined) {
const oldImage = user.image as Id<'_storage'> | undefined;
patch.image = args.image;
if (oldImage && oldImage !== args.image) {
await ctx.storage.delete(oldImage);
}
}
if (Object.keys(patch).length > 0) {
await ctx.db.patch(userId, patch);
}
return { success: true };
},
});
export const updateUserPassword = action({
args: {
currentPassword: v.string(),
newPassword: v.string(),
},
handler: async (ctx, { currentPassword, newPassword }) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new ConvexError('Not authenticated.');
const user = await ctx.runQuery(api.auth.getUser, { userId });
if (!user?.email) throw new ConvexError('User not found.');
const verified = await retrieveAccount(ctx, {
provider: 'password',
account: { id: user.email, secret: currentPassword },
});
if (!verified) throw new ConvexError('Current password is incorrect.');
if (!validatePassword(newPassword))
throw new ConvexError('Invalid password.');
await modifyAccountCredentials(ctx, {
provider: 'password',
account: { id: user.email, secret: newPassword },
});
return { success: true };
},
});

View File

@@ -0,0 +1,2 @@
export { Password, validatePassword } from './providers/password';
export { UseSendOTP, UseSendOTPPasswordReset } from './providers/usesend';

View File

@@ -0,0 +1,33 @@
import { Password as DefaultPassword } from '@convex-dev/auth/providers/Password';
import { ConvexError } from 'convex/values';
import { UseSendOTP, UseSendOTPPasswordReset } from '..';
import { DataModel } from '../../../_generated/dataModel';
export const Password = DefaultPassword<DataModel>({
profile(params, ctx) {
return {
email: params.email as string,
name: params.name as string,
};
},
validatePasswordRequirements: (password: string) => {
if (!validatePassword(password)) {
throw new ConvexError('Invalid password.');
}
},
reset: UseSendOTPPasswordReset,
verify: UseSendOTP,
});
export const validatePassword = (password: string): boolean => {
if (
password.length < 8 ||
password.length > 100 ||
!/\d/.test(password) ||
!/[a-z]/.test(password) ||
!/[A-Z]/.test(password)
) {
return false;
}
return true;
};

View File

@@ -0,0 +1,90 @@
import type { EmailConfig, EmailUserConfig } from '@auth/core/providers/email';
import { generateRandomString, RandomReader } from '@oslojs/crypto/random';
import { alphabet } from 'oslo/crypto';
import { UseSend } from 'usesend-js';
export default function UseSendProvider(config: EmailUserConfig): EmailConfig {
return {
id: 'usesend',
type: 'email',
name: 'UseSend',
from: 'TechTracker <admin@techtracker.gbrown.org>',
maxAge: 24 * 60 * 60, // 24 hours
async generateVerificationToken() {
const random: RandomReader = {
read(bytes) {
crypto.getRandomValues(bytes);
},
};
return generateRandomString(random, alphabet('0-9'), 6);
},
async sendVerificationRequest(params) {
const { identifier: to, provider, url, theme, token } = params;
//const { host } = new URL(url);
const host = 'TechTracker';
const useSend = new UseSend(
process.env.USESEND_API_KEY!,
'https://usesend.gbrown.org',
);
// For password reset, we want to send the code, not the magic link
const isPasswordReset =
url.includes('reset') || provider.id?.includes('reset');
const result = await useSend.emails.send({
from: provider.from!,
to: [to],
subject: isPasswordReset
? `Reset your password - ${host}`
: `Sign in to ${host}`,
text: isPasswordReset
? `Your password reset code is ${token}`
: `Your sign in code is ${token}`,
html: isPasswordReset
? `
<div style="max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif;">
<h2>Password Reset Request</h2>
<p>You requested a password reset. Your reset code is:</p>
<div style="font-size: 32px; font-weight: bold; text-align: center; padding: 20px; background: #f5f5f5; margin: 20px 0; border-radius: 8px;">
${token}
</div>
<p>This code expires in 1 hour.</p>
<p>If you didn't request this, please ignore this email.</p>
</div>
`
: `
<div style="max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif;">
<h2>Your Sign In Code</h2>
<p>Your verification code is:</p>
<div style="font-size: 32px; font-weight: bold; text-align: center; padding: 20px; background: #f5f5f5; margin: 20px 0; border-radius: 8px;">
${token}
</div>
<p>This code expires in 24 hours.</p>
</div>
`,
});
if (result.error) {
throw new Error('UseSend error: ' + JSON.stringify(result.error));
}
},
options: config,
};
}
// Create specific instances for password reset and email verification
export const UseSendOTPPasswordReset = UseSendProvider({
id: 'usesend-otp-password-reset',
apiKey: process.env.USESEND_API_KEY,
maxAge: 60 * 60, // 1 hour
});
export const UseSendOTP = UseSendProvider({
id: 'usesend-otp',
apiKey: process.env.USESEND_API_KEY,
maxAge: 60 * 20, // 20 minutes
});

View File

@@ -0,0 +1,9 @@
import { httpRouter } from 'convex/server';
import { auth } from './auth';
const http = httpRouter();
auth.addHttpRoutes(http);
export default http;

View File

@@ -1,71 +0,0 @@
import { Auth } from 'convex/server';
import { v } from 'convex/values';
import { internal } from '../convex/_generated/api';
import { mutation, query } from './_generated/server';
export const getUserId = async (ctx: { auth: Auth }) => {
return (await ctx.auth.getUserIdentity())?.subject;
};
// Get all notes for a specific user
export const getNotes = query({
args: {},
handler: async (ctx) => {
const userId = await getUserId(ctx);
if (!userId) return null;
const notes = await ctx.db
.query('notes')
.filter((q) => q.eq(q.field('userId'), userId))
.collect();
return notes;
},
});
// Get note for a specific note
export const getNote = query({
args: {
id: v.optional(v.id('notes')),
},
handler: async (ctx, args) => {
const { id } = args;
if (!id) return null;
const note = await ctx.db.get(id);
return note;
},
});
// Create a new note for a user
export const createNote = mutation({
args: {
title: v.string(),
content: v.string(),
isSummary: v.boolean(),
},
handler: async (ctx, { title, content, isSummary }) => {
const userId = await getUserId(ctx);
if (!userId) throw new Error('User not found');
const noteId = await ctx.db.insert('notes', { userId, title, content });
if (isSummary) {
await ctx.scheduler.runAfter(0, internal.openai.summary, {
id: noteId,
title,
content,
});
}
return noteId;
},
});
export const deleteNote = mutation({
args: {
noteId: v.id('notes'),
},
handler: async (ctx, args) => {
await ctx.db.delete(args.noteId);
},
});

View File

@@ -1,76 +0,0 @@
import { v } from 'convex/values';
import OpenAI from 'openai';
import { internal } from './_generated/api';
import { internalAction, internalMutation, query } from './_generated/server';
import { missingEnvVariableUrl } from './utils';
export const openaiKeySet = query({
args: {},
handler: async () => {
return !!process.env.OPENAI_API_KEY;
},
});
export const summary = internalAction({
args: {
id: v.id('notes'),
title: v.string(),
content: v.string(),
},
handler: async (ctx, { id, title, content }) => {
const prompt = `Take in the following note and return a summary: Title: ${title}, Note content: ${content}`;
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
const error = missingEnvVariableUrl(
'OPENAI_API_KEY',
'https://platform.openai.com/account/api-keys',
);
console.error(error);
await ctx.runMutation(internal.openai.saveSummary, {
id: id,
summary: error,
});
return;
}
const openai = new OpenAI({ apiKey });
const output = await openai.chat.completions.create({
messages: [
{
role: 'system',
content:
'You are a helpful assistant designed to output JSON in this format: {summary: string}',
},
{ role: 'user', content: prompt },
],
model: 'gpt-4-1106-preview',
response_format: { type: 'json_object' },
});
// Pull the message content out of the response
const messageContent = output.choices[0]?.message.content;
console.log({ messageContent });
const parsedOutput = JSON.parse(messageContent!);
console.log({ parsedOutput });
await ctx.runMutation(internal.openai.saveSummary, {
id: id,
summary: parsedOutput.summary,
});
},
});
export const saveSummary = internalMutation({
args: {
id: v.id('notes'),
summary: v.string(),
},
handler: async (ctx, { id, summary }) => {
await ctx.db.patch(id, {
summary: summary,
});
},
});

View File

@@ -1,11 +1,36 @@
import { defineSchema, defineTable } from 'convex/server';
import { v } from 'convex/values';
import { authTables } from '@convex-dev/auth/server';
const applicationTables = {
// Users contains name image & email.
// If you would like to save any other information,
// I would recommend including this profiles table
// where you can include settings & anything else you would like tied to the user.
profiles: defineTable({
userId: v.id('users'),
theme_preference: v.optional(v.string()),
})
.index('userId', ['userId'])
};
export default defineSchema({
notes: defineTable({
userId: v.string(),
title: v.string(),
content: v.string(),
summary: v.optional(v.string()),
}),
...authTables,
// Default table for users directly from authTable.
// You can extend it if you would like, but it may
// be better to just use the profiles table example
// below.
users: defineTable({
name: v.optional(v.string()),
image: v.optional(v.string()),
email: v.optional(v.string()),
emailVerificationTime: v.optional(v.number()),
phone: v.optional(v.string()),
phoneVerificationTime: v.optional(v.number()),
isAnonymous: v.optional(v.boolean()),
})
.index("email", ["email"])
.index('name', ['name'])
.index("phone", ["phone"]),
...applicationTables,
});