|
| 1 | +import { ScriptContext } from "../module.gen.ts"; |
| 2 | +import { ProviderDataInput, ProviderInfo } from "../utils/types.ts"; |
| 3 | + |
| 4 | +export interface Request { |
| 5 | + info: ProviderInfo; |
| 6 | + uniqueData: ProviderDataInput; |
| 7 | + additionalData: ProviderDataInput; |
| 8 | + |
| 9 | + suggestedUsername?: string; |
| 10 | +} |
| 11 | + |
| 12 | +export interface Response { |
| 13 | + userToken: string; |
| 14 | +} |
| 15 | + |
| 16 | +export async function run( |
| 17 | + ctx: ScriptContext, |
| 18 | + req: Request, |
| 19 | +): Promise<Response> { |
| 20 | + const key = req.info.providerType + ":" + req.info.providerId + ":" + JSON.stringify(req.uniqueData); |
| 21 | + await ctx.modules.rateLimit.throttle({ |
| 22 | + key, |
| 23 | + period: 10, |
| 24 | + requests: 10, |
| 25 | + type: "user", |
| 26 | + }); |
| 27 | + |
| 28 | + // Get users the provider is associated with |
| 29 | + const providers = await ctx.db.providerEntries.findFirst({ |
| 30 | + where: { |
| 31 | + providerType: req.info.providerType, |
| 32 | + providerId: req.info.providerId, |
| 33 | + uniqueData: { equals: req.uniqueData }, |
| 34 | + }, |
| 35 | + select: { |
| 36 | + userId: true, |
| 37 | + }, |
| 38 | + }); |
| 39 | + |
| 40 | + // If the provider is associated with a user, generate a user token and |
| 41 | + // return it |
| 42 | + if (providers) { |
| 43 | + const { token: { token } } = await ctx.modules.users.createToken({ userId: providers.userId }); |
| 44 | + return { userToken: token }; |
| 45 | + } |
| 46 | + |
| 47 | + // If the provider is not associated with a user, create a new user |
| 48 | + const { user } = await ctx.modules.users.create({ username: req.suggestedUsername }); |
| 49 | + |
| 50 | + // Insert the provider data with the newly-created user |
| 51 | + await ctx.db.providerEntries.create({ |
| 52 | + data: { |
| 53 | + userId: user.id, |
| 54 | + providerType: req.info.providerType, |
| 55 | + providerId: req.info.providerId, |
| 56 | + uniqueData: req.uniqueData, |
| 57 | + additionalData: req.additionalData, |
| 58 | + }, |
| 59 | + }); |
| 60 | + |
| 61 | + // Generate a user token and return it |
| 62 | + const { token: { token } } = await ctx.modules.users.createToken({ userId: user.id }); |
| 63 | + |
| 64 | + return { userToken: token }; |
| 65 | +} |
0 commit comments