vors
vors3y ago

Checking auth with decorators

This is great, thank you for the reference! Question about that -- why do this middle-ware magic instead of simple function call like
async function checkAuth({db, auth}) {
const identity = await auth.getUserIdentity();
if (!identity) {
throw new Error("Unauthenticated call to mutation");
}
const user = await db
.query("users")
.withIndex("by_token", q =>
q.eq("tokenIdentifier", identity.tokenIdentifier)
)
.unique();
if (!user) {
throw new Error("Unauthenticated call to mutation");
}
}

export default mutation(async ({ db, auth }, body) => {
checkAuth({ db, auth });
const message = { body, user: user._id };
await db.insert("messages", message);
});
async function checkAuth({db, auth}) {
const identity = await auth.getUserIdentity();
if (!identity) {
throw new Error("Unauthenticated call to mutation");
}
const user = await db
.query("users")
.withIndex("by_token", q =>
q.eq("tokenIdentifier", identity.tokenIdentifier)
)
.unique();
if (!user) {
throw new Error("Unauthenticated call to mutation");
}
}

export default mutation(async ({ db, auth }, body) => {
checkAuth({ db, auth });
const message = { body, user: user._id };
await db.insert("messages", message);
});
2 Replies
ballingt
ballingt3y ago
Note that in your code above you're doing something unusual by not awaiting the checkAuth({ db, auth }); call — it should still work (when the async checkAuth task fails the transaction will fail) but I wouldn't recommend it because it's confusing and relies on an unusual property of our runtime, that an unhandled promise rejection will cause the transaction to roll back.
vors
vorsOP3y ago
Oh, thank you for the tip! I'm very much JS noob.

Did you find this page helpful?