feat: add auth to convex fns

This commit is contained in:
2025-09-15 21:44:41 +00:00
parent b898d4a737
commit 72ac4df486
10 changed files with 166 additions and 33 deletions

38
convex/model/user.ts Normal file
View File

@@ -0,0 +1,38 @@
import type { MutationCtx, QueryCtx } from "../_generated/server"
import * as Err from "./error"
/**
* 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
* 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",
)
}
return user
}