EMILIANOM
EMILIANOM•3mo ago

Convex + Lucia auth + Svelte | Help

Hello i was able to integrate Lucia with convex (thanks to @v and his repo https://github.com/vynxc/lucia-svelte-convex-demo) Now I'm trying to write queries that filter by auth user id, to show only those rows the user owns.
import { queryWithAuth } from './auth/withAuth';

export const get = queryWithAuth({
args: {},
handler: async (ctx) => {
const identity = ctx.userSessionContext?.user;
if (!identity) {
throw new Error('Not authenticated');
}
console.log(identity);

const tasks = await ctx.db
.query('tasks')
// .filter((task) => task.userId === identity._id)
.collect();
return tasks.map((task) => ({ ...task, assigner: 'tom' }));
}
});
import { queryWithAuth } from './auth/withAuth';

export const get = queryWithAuth({
args: {},
handler: async (ctx) => {
const identity = ctx.userSessionContext?.user;
if (!identity) {
throw new Error('Not authenticated');
}
console.log(identity);

const tasks = await ctx.db
.query('tasks')
// .filter((task) => task.userId === identity._id)
.collect();
return tasks.map((task) => ({ ...task, assigner: 'tom' }));
}
});
Identity is null, even if I'm logged in, can anyone check my implementation and help me with some suggestions Thanks everyone Full code: https://github.com/emilianocalzada/convex-lucia-svelte
GitHub
GitHub - emilianocalzada/convex-lucia-svelte
Contribute to emilianocalzada/convex-lucia-svelte development by creating an account on GitHub.
5 Replies
Convex Bot
Convex Bot•3mo ago
Thanks for posting in <#1088161997662724167>. Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets. - Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.) - Use search.convex.dev to search Docs, Stack, and Discord all at once. - Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI. - Avoid tagging staff unless specifically instructed. Thank you!
v
v•3mo ago
I can check when I'm home @EMILIANOM Make sure you're passing session id when needed
EMILIANOM
EMILIANOMOP•3mo ago
tasks.ts
export const get = queryWithAuth({
args: {},
handler: async (ctx) => {
const user = ctx.userSessionContext?.user;
if (!user) {
throw new ConvexError('Not authenticated');
}

const tasks = await ctx.db
.query('tasks')
.withIndex('by_user', (q) => q.eq('userId', user.id))
.collect();
return tasks.map((task) => ({ ...task, assigner: 'tom' }));
}
});
export const get = queryWithAuth({
args: {},
handler: async (ctx) => {
const user = ctx.userSessionContext?.user;
if (!user) {
throw new ConvexError('Not authenticated');
}

const tasks = await ctx.db
.query('tasks')
.withIndex('by_user', (q) => q.eq('userId', user.id))
.collect();
return tasks.map((task) => ({ ...task, assigner: 'tom' }));
}
});
withAuth.ts
export function queryWithAuth<ArgsValidator extends PropertyValidators, Output>({
args,
handler
}: QueryWithAuth<ArgsValidator, Output>) {
return query({
args: {
...args,
sessionId: v.union(v.null(), v.string())
},
handler: async (ctx, args: any) => {
const auth = getAuth(ctx.db as DatabaseWriter);
const userSessionContext = await getValidExistingSession(auth, args.sessionId);
return handler(
{ ...ctx, userSessionContext, auth, table: entsTableFactory(ctx, entDefinitions) },
args
);
}
});
}
export function queryWithAuth<ArgsValidator extends PropertyValidators, Output>({
args,
handler
}: QueryWithAuth<ArgsValidator, Output>) {
return query({
args: {
...args,
sessionId: v.union(v.null(), v.string())
},
handler: async (ctx, args: any) => {
const auth = getAuth(ctx.db as DatabaseWriter);
const userSessionContext = await getValidExistingSession(auth, args.sessionId);
return handler(
{ ...ctx, userSessionContext, auth, table: entsTableFactory(ctx, entDefinitions) },
args
);
}
});
}
Yeah that was it! I think that it is working now, do you think if im doing it the correcy way pls? not sure if i should check for null user inside every query / mutation or if there is a better way in order to have less code. Pushed the code to my github repo if you need to see the whole code, basically its the same repo as yours 😄 When the page loads it verifies the auth (hooks.server.ts) and then when it calls the database via (query, mutation, etc) it also verifies the auth on every query, i think this is secure but is it the recommended way?
v
v•3mo ago
if you wanted you can make a querywithauth that throws an error for you instead or returning a null object like querywithauth and querywithauthx if you wanted certan routes that will always throw the same error if not authed im not an expert, but this is the basic logic i see in my head that is simple and would work well @ballingt maybe can have something else to say it can all be made alot prettier depending on what you like ofcourse so dont be afraid to experiment @EMILIANOM i just got home so if you have anything else i can take a look ill be going to bed soon
EMILIANOM
EMILIANOMOP•3mo ago
Thank for your time! That’s enough, I will keep experimenting and learning about convex, I’m really liking it, just the major pain point was the auth with svelte but your repo saved me Night 🌙

Did you find this page helpful?