mirror of
https://github.com/get-drexa/drive.git
synced 2025-11-30 21:41:39 +00:00
4
packages/convex/_generated/api.d.ts
vendored
4
packages/convex/_generated/api.d.ts
vendored
@@ -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;
|
||||
|
||||
|
||||
@@ -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)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -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
8
packages/convex/user.ts
Normal 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)
|
||||
},
|
||||
})
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -1,12 +0,0 @@
|
||||
import {
|
||||
convexClient,
|
||||
crossDomainClient,
|
||||
} from "@convex-dev/better-auth/client/plugins"
|
||||
import { createAuthClient } from "better-auth/react"
|
||||
|
||||
export type AuthErrorCode = keyof typeof authClient.$ERROR_CODES
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: process.env.BUN_PUBLIC_CONVEX_SITE_URL,
|
||||
plugins: [convexClient(), crossDomainClient()],
|
||||
})
|
||||
27
packages/web/src/auth.ts
Normal file
27
packages/web/src/auth.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
convexClient,
|
||||
crossDomainClient,
|
||||
} from "@convex-dev/better-auth/client/plugins"
|
||||
import { createAuthClient } from "better-auth/react"
|
||||
import { createContext, useContext } from "react"
|
||||
|
||||
export type AuthErrorCode = keyof typeof authClient.$ERROR_CODES
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: process.env.BUN_PUBLIC_CONVEX_SITE_URL,
|
||||
plugins: [convexClient(), crossDomainClient()],
|
||||
})
|
||||
|
||||
export type Session = NonNullable<
|
||||
Awaited<ReturnType<typeof authClient.useSession>>["data"]
|
||||
>
|
||||
|
||||
export const SessionContext = createContext<Session | null>(null)
|
||||
|
||||
export function useSession() {
|
||||
const context = useContext(SessionContext)
|
||||
if (!context) {
|
||||
throw new Error("useSession must be used within a SessionProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { toast } from "sonner"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import { formatError } from "@/lib/error"
|
||||
import { useKeyboardModifierListener } from "@/lib/keyboard"
|
||||
import { authClient } from "../auth-client"
|
||||
import { authClient } from "../auth"
|
||||
|
||||
export const Route = createRootRoute({
|
||||
component: RootLayout,
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
useConvexAuth,
|
||||
} from "convex/react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { authClient } from "@/auth-client"
|
||||
import { authClient, SessionContext } from "@/auth"
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner"
|
||||
|
||||
export const Route = createFileRoute("/_authenticated")({
|
||||
@@ -21,7 +21,7 @@ export const Route = createFileRoute("/_authenticated")({
|
||||
function AuthenticatedLayout() {
|
||||
const { search } = useLocation()
|
||||
const { isLoading } = useConvexAuth()
|
||||
const { isPending: sessionLoading } = authClient.useSession()
|
||||
const { data: session, isPending: sessionLoading } = authClient.useSession()
|
||||
const [hasProcessedAuth, setHasProcessedAuth] = useState(false)
|
||||
|
||||
// Check if we're in the middle of processing an auth code
|
||||
@@ -50,6 +50,11 @@ function AuthenticatedLayout() {
|
||||
return (
|
||||
<>
|
||||
<Authenticated>
|
||||
{session ? (
|
||||
<SessionContext value={session}>
|
||||
<Outlet />
|
||||
</SessionContext>
|
||||
) : null}
|
||||
<Outlet />
|
||||
</Authenticated>
|
||||
<Unauthenticated>
|
||||
|
||||
@@ -16,7 +16,6 @@ function RouteComponent() {
|
||||
<Outlet />
|
||||
</SidebarInset>
|
||||
</div>
|
||||
<Toaster />
|
||||
</SidebarProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { type AuthErrorCode, authClient } from "../auth-client"
|
||||
import { type AuthErrorCode, authClient } from "../auth"
|
||||
|
||||
export const Route = createFileRoute("/sign-up")({
|
||||
component: SignupPage,
|
||||
@@ -145,8 +145,6 @@ function SignupForm() {
|
||||
passwordFieldError = "Passwords do not match"
|
||||
}
|
||||
|
||||
console.log({ passwordFieldError })
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<FieldGroup>
|
||||
|
||||
Reference in New Issue
Block a user