NickN
Convex Community11mo ago
3 replies
Nick

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;
  },
});


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.
Was this page helpful?