|
| 1 | +import { RuntimeError, ScriptContext } from "../module.gen.ts"; |
| 2 | + |
| 3 | +export interface Request { |
| 4 | + flowToken: string; |
| 5 | + userToken: string; |
| 6 | +} |
| 7 | + |
| 8 | +export type Response = ReturnType<ScriptContext["modules"]["authProviders"]["addProviderToUser"]>; |
| 9 | + |
| 10 | +export async function run( |
| 11 | + ctx: ScriptContext, |
| 12 | + req: Request, |
| 13 | +): Promise<Response> { |
| 14 | + await ctx.modules.rateLimit.throttlePublic({}); |
| 15 | + |
| 16 | + if (!req.flowToken) throw new RuntimeError("missing_token", { statusCode: 400 }); |
| 17 | + |
| 18 | + const { tokens: [flowToken] } = await ctx.modules.tokens.fetchByToken({ tokens: [req.flowToken] }); |
| 19 | + if (!flowToken) { |
| 20 | + throw new RuntimeError("invalid_token", { statusCode: 400 }); |
| 21 | + } |
| 22 | + if (new Date(flowToken.expireAt ?? 0) < new Date()) { |
| 23 | + throw new RuntimeError("expired_token", { statusCode: 400 }); |
| 24 | + } |
| 25 | + |
| 26 | + const flowId = flowToken.meta.flowId; |
| 27 | + if (!flowId) throw new RuntimeError("invalid_token", { statusCode: 400 }); |
| 28 | + |
| 29 | + const flow = await ctx.db.loginAttempts.findFirst({ |
| 30 | + where: { |
| 31 | + id: flowId, |
| 32 | + } |
| 33 | + }); |
| 34 | + if (!flow) throw new RuntimeError("invalid_token", { statusCode: 400 }); |
| 35 | + |
| 36 | + if (!flow.identifier || !flow.tokenData) { |
| 37 | + throw new RuntimeError("flow_not_complete", { statusCode: 400 }); |
| 38 | + } |
| 39 | + |
| 40 | + await ctx.modules.users.authenticateToken({ userToken: req.userToken }); |
| 41 | + |
| 42 | + const tokenData = flow.tokenData; |
| 43 | + if (!tokenData) { |
| 44 | + throw new RuntimeError("internal_error", { statusCode: 500 }); |
| 45 | + } |
| 46 | + if (typeof tokenData !== "object") { |
| 47 | + throw new RuntimeError("internal_error", { statusCode: 500 }); |
| 48 | + } |
| 49 | + if (Array.isArray(tokenData)) { |
| 50 | + throw new RuntimeError("internal_error", { statusCode: 500 }); |
| 51 | + } |
| 52 | + |
| 53 | + return await ctx.modules.authProviders.addProviderToUser({ |
| 54 | + userToken: req.userToken, |
| 55 | + info: { |
| 56 | + providerType: "oauth2", |
| 57 | + providerId: flow.providerId, |
| 58 | + }, |
| 59 | + uniqueData: { |
| 60 | + identifier: flow.identifier, |
| 61 | + }, |
| 62 | + additionalData: tokenData, |
| 63 | + }); |
| 64 | +} |
0 commit comments