|
| 1 | +import { ScriptContext } from "../module.gen.ts"; |
| 2 | +import { getUserId } from "../utils/db.ts"; |
| 3 | +import { IdentityDataInput, IdentityProviderInfo } from "../utils/types.ts"; |
| 4 | + |
| 5 | +export interface Request { |
| 6 | + info: IdentityProviderInfo; |
| 7 | + uniqueData: IdentityDataInput; |
| 8 | + additionalData: IdentityDataInput; |
| 9 | + |
| 10 | + username?: string; |
| 11 | +} |
| 12 | + |
| 13 | +export interface Response { |
| 14 | + userToken: string; |
| 15 | + userId: string; |
| 16 | +} |
| 17 | + |
| 18 | +export async function run( |
| 19 | + ctx: ScriptContext, |
| 20 | + req: Request, |
| 21 | +): Promise<Response> { |
| 22 | + return await ctx.db.$transaction(async tx => { |
| 23 | + const userId = await getUserId(tx, req.info.identityType, req.info.identityId, req.uniqueData); |
| 24 | + |
| 25 | + // If the identity provider is associated with a user, sign in |
| 26 | + if (userId) { |
| 27 | + // Generate a user token |
| 28 | + const { token: { token } } = await ctx.modules.users.createToken({ userId }); |
| 29 | + return { |
| 30 | + userToken: token, |
| 31 | + userId, |
| 32 | + }; |
| 33 | + } else { |
| 34 | + // Otherwise, create a new user |
| 35 | + const { user } = await ctx.modules.users.create({ username: req.username }); |
| 36 | + |
| 37 | + // Insert the identity data with the newly-created user |
| 38 | + await tx.userIdentities.create({ |
| 39 | + data: { |
| 40 | + userId: user.id, |
| 41 | + identityType: req.info.identityType, |
| 42 | + identityId: req.info.identityId, |
| 43 | + uniqueData: req.uniqueData, |
| 44 | + additionalData: req.additionalData, |
| 45 | + }, |
| 46 | + }); |
| 47 | + |
| 48 | + // Generate a user token and return it |
| 49 | + const { token: { token } } = await ctx.modules.users.createToken({ userId: user.id }); |
| 50 | + return { |
| 51 | + userToken: token, |
| 52 | + userId: user.id, |
| 53 | + }; |
| 54 | + } |
| 55 | + }); |
| 56 | +} |
0 commit comments