Squirble
Squirble5d ago

How to create a Convex Auth user & authAccount manually

My app uses various chat bots. If someone interacts with a discord bot and creates some things, it'd be nice for those things to be associated with their discord user. Later, if they sign into the app with discord via convex auth, it should know that they're the same user who's been using it through the bot. Here's what I came up with:
export const upsert = mutation({
args: {
discordMember,
},
handler: async (ctx, { discordMember }): Promise<Id<"users">> => {
const existingUserId = await ctx.runQuery(api.discord.user.get, {
discordUserId: discordMember.user.id,
});

if (existingUserId) return existingUserId;

// Create new user
const profile = (await DiscordProvider.profile!(
discordMember.user as DiscordProfile,
undefined as unknown as TokenSet, // TokenSet isn't used by this function
)) as Partial<Doc<"users">>; // slight type mismatch: name can be null

const userId = await ctx.db.insert("users", profile);

// Create auth account
await ctx.db.insert("authAccounts", {
userId,
provider: "discord",
providerAccountId: discordMember.user.id,
});

return userId;
},
});
export const upsert = mutation({
args: {
discordMember,
},
handler: async (ctx, { discordMember }): Promise<Id<"users">> => {
const existingUserId = await ctx.runQuery(api.discord.user.get, {
discordUserId: discordMember.user.id,
});

if (existingUserId) return existingUserId;

// Create new user
const profile = (await DiscordProvider.profile!(
discordMember.user as DiscordProfile,
undefined as unknown as TokenSet, // TokenSet isn't used by this function
)) as Partial<Doc<"users">>; // slight type mismatch: name can be null

const userId = await ctx.db.insert("users", profile);

// Create auth account
await ctx.db.insert("authAccounts", {
userId,
provider: "discord",
providerAccountId: discordMember.user.id,
});

return userId;
},
});
Is this a good way to do it? Will I run into problems later? It would be nice if Convex Auth exposed a nicer way to do this.
2 Replies
Convex Bot
Convex Bot5d 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!
ballingt
ballingt5d ago
If you want to avoid touching Convex Auth table with this you could create an entirely separate table, "unclaimed accounts" say, and associated the messages with those so it's clear that the user hasn't actually created an account yet.

Did you find this page helpful?