fix: root directory creation

Co-authored-by: Ona <no-reply@ona.com>
This commit is contained in:
2025-10-05 22:14:44 +00:00
parent 1fcdaf4f86
commit f7bc5fd958
14 changed files with 95 additions and 107 deletions

View File

@@ -18,7 +18,7 @@ import type * as model_error from "../model/error.js";
import type * as model_files from "../model/files.js";
import type * as model_filesystem from "../model/filesystem.js";
import type * as model_user from "../model/user.js";
import type * as users from "../users.js";
import type * as user from "../user.js";
import type {
ApiFromModules,
@@ -45,7 +45,7 @@ declare const fullApi: ApiFromModules<{
"model/files": typeof model_files;
"model/filesystem": typeof model_filesystem;
"model/user": typeof model_user;
users: typeof users;
user: typeof user;
}>;
declare const fullApiWithMounts: typeof fullApi;

View File

@@ -3,13 +3,26 @@ import { convex, crossDomain } from "@convex-dev/better-auth/plugins"
import { betterAuth } from "better-auth"
import { components } from "./_generated/api"
import type { DataModel } from "./_generated/dataModel"
import { query } from "./_generated/server"
const siteUrl = process.env.SITE_URL!
// The component client has methods needed for integrating Convex with Better Auth,
// as well as helper methods for general use.
export const authComponent = createClient<DataModel>(components.betterAuth)
export const authComponent = createClient<DataModel>(components.betterAuth, {
triggers: {
user: {
onCreate: async (ctx, user) => {
const now = Date.now()
await ctx.db.insert("directories", {
name: "",
userId: user._id,
createdAt: now,
updatedAt: now,
})
},
},
},
})
export const createAuth = (
ctx: GenericCtx<DataModel>,
@@ -36,12 +49,3 @@ export const createAuth = (
],
})
}
// Example function for getting the current user
// Feel free to edit, omit, etc.
export const getCurrentUser = query({
args: {},
handler: async (ctx) => {
return authComponent.getAuthUser(ctx)
},
})

View File

@@ -4,18 +4,17 @@ import {
customMutation,
customQuery,
} from "convex-helpers/server/customFunctions"
import type { Doc } from "./_generated/dataModel"
import type { MutationCtx, QueryCtx } from "./_generated/server"
import { mutation, query } from "./_generated/server"
import { userIdentityOrThrow, userOrThrow } from "./model/user"
import { type AuthUser, userIdentityOrThrow, userOrThrow } from "./model/user"
export type AuthenticatedQueryCtx = QueryCtx & {
user: Doc<"users">
user: AuthUser
identity: UserIdentity
}
export type AuthenticatedMutationCtx = MutationCtx & {
user: Doc<"users">
user: AuthUser
identity: UserIdentity
}

View File

@@ -2,6 +2,7 @@ import { v } from "convex/values"
import type { Doc, Id } from "../_generated/dataModel"
import type { AuthenticatedMutationCtx } from "../functions"
import * as Directories from "./directories"
import * as Err from "./error"
import * as Files from "./files"
export enum FileType {
@@ -81,6 +82,29 @@ export const VFileHandle = v.object({
})
export const VFileSystemHandle = v.union(VFileHandle, VDirectoryHandle)
export async function ensureRootDirectory(
ctx: AuthenticatedMutationCtx,
): Promise<Id<"directories">> {
const existing = await ctx.db
.query("directories")
.withIndex("byParentId", (q) =>
q.eq("userId", ctx.user._id).eq("parentId", undefined),
)
.first()
if (existing) {
return existing._id
}
const now = Date.now()
return await ctx.db.insert("directories", {
name: "",
createdAt: now,
updatedAt: now,
userId: ctx.user._id,
})
}
/**
* Recursively collects all file and directory handles from the given handles,
* including all nested items. Only includes items that are in trash (deletedAt >= 0).

View File

@@ -1,54 +1,25 @@
import type { MutationCtx, QueryCtx } from "../_generated/server"
import type { AuthenticatedMutationCtx } from "../functions"
import { authComponent } from "../auth"
import * as Err from "./error"
export type AuthUser = Awaited<ReturnType<typeof authComponent.getAuthUser>>
/**
* Get the current authenticated user identity
* Throws an error if the user is not authenticated */
export async function userIdentityOrThrow(ctx: QueryCtx | MutationCtx) {
const identity = await ctx.auth.getUserIdentity()
if (!identity) {
throw Err.create(Err.Code.Unauthenticated, "Not authenticated")
}
return identity
}
/**
* Get internal user document from JWT authentication
* Get user document from JWT authentication
* Throws an error if the user is not authenticated
*/
export async function userOrThrow(ctx: QueryCtx | MutationCtx) {
const identity = await userIdentityOrThrow(ctx)
// Look for existing user by JWT subject
const user = await ctx.db
.query("users")
.withIndex("byJwtSubject", (q) => q.eq("jwtSubject", identity.subject))
.first()
if (!user) {
throw Err.create(
Err.Code.Unauthenticated,
"User not found - please sync user first",
)
}
const user = await authComponent.getAuthUser(ctx)
return user
}
export async function register(ctx: AuthenticatedMutationCtx) {
const now = Date.now()
await Promise.all([
ctx.db.insert("users", {
jwtSubject: ctx.identity.subject,
}),
ctx.db.insert("directories", {
name: "",
userId: ctx.user._id,
createdAt: now,
updatedAt: now,
}),
])
}

View File

@@ -2,12 +2,9 @@ import { defineSchema, defineTable } from "convex/server"
import { v } from "convex/values"
const schema = defineSchema({
users: defineTable({
jwtSubject: v.string(),
}).index("byJwtSubject", ["jwtSubject"]),
files: defineTable({
storageId: v.id("_storage"),
userId: v.id("users"),
userId: v.string(), // BetterAuth user IDs are strings, not Convex Ids
directoryId: v.optional(v.id("directories")),
name: v.string(),
size: v.number(),
@@ -27,7 +24,7 @@ const schema = defineSchema({
]),
directories: defineTable({
name: v.string(),
userId: v.id("users"),
userId: v.string(), // BetterAuth user IDs are strings, not Convex Ids
parentId: v.optional(v.id("directories")),
createdAt: v.number(),
updatedAt: v.number(),

8
packages/convex/user.ts Normal file
View File

@@ -0,0 +1,8 @@
import { authenticatedMutation } from "./functions"
import * as FileSystem from "./model/filesystem"
export const ensureRootDirectory = authenticatedMutation({
handler: async (ctx) => {
return await FileSystem.ensureRootDirectory(ctx)
},
})

View File

@@ -1,32 +0,0 @@
import { mutation } from "./_generated/server"
import { authenticatedQuery } from "./functions"
import * as Err from "./model/error"
export const getCurrentUser = authenticatedQuery({
handler: async (ctx) => {
// ctx.user is the internal Convex user document
return ctx.user
},
})
export const syncUser = mutation({
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity()
if (!identity) {
throw Err.create(Err.Code.Unauthenticated)
}
const existingUser = await ctx.db
.query("users")
.withIndex("byJwtSubject", (q) =>
q.eq("jwtSubject", identity.subject),
)
.first()
if (!existingUser) {
await ctx.db.insert("users", {
jwtSubject: identity.subject,
})
}
},
})