|
| 1 | +import { defineAPIAction } from "../../api/cloud-action.ts"; |
| 2 | +import { raiseServerException } from "../../serve/server-exception.ts"; |
| 3 | +import type { SessionData } from "../types.ts"; |
| 4 | + |
| 5 | +export const switchAccount = defineAPIAction("switchAccount", { |
| 6 | + label: "Switch Logged-in Account", |
| 7 | + description: |
| 8 | + "Switch the current logged-in account to another account that the user has access to", |
| 9 | + params: [{ |
| 10 | + key: "accountId", |
| 11 | + label: "Account ID", |
| 12 | + type: "DataField", |
| 13 | + description: "The ID of the account to switch to", |
| 14 | + required: true, |
| 15 | + }], |
| 16 | + async action({ |
| 17 | + inCloud, |
| 18 | + inRequest, |
| 19 | + params, |
| 20 | + }) { |
| 21 | + const { accountId } = params; |
| 22 | + const user = inRequest.context.get<SessionData>("user"); |
| 23 | + if (!user) { |
| 24 | + raiseServerException(401, "unauthorized"); |
| 25 | + } |
| 26 | + const foundId = user.accounts.find((acc) => acc.accountId === accountId); |
| 27 | + if (!foundId) { |
| 28 | + raiseServerException(403, "forbidden"); |
| 29 | + } |
| 30 | + user.accountId = accountId; |
| 31 | + const orm = inCloud.orm.withUser(inCloud.orm.systemGobalUser); |
| 32 | + const sessionEntry = await orm.findEntry("userSession", { |
| 33 | + sessionId: user.sessionId, |
| 34 | + }); |
| 35 | + if (!sessionEntry) { |
| 36 | + raiseServerException(401, "unauthorized"); |
| 37 | + } |
| 38 | + sessionEntry.update({ |
| 39 | + sessionData: user, |
| 40 | + }); |
| 41 | + await sessionEntry.save(); |
| 42 | + inRequest.context.update("user", user); |
| 43 | + inCloud.inCache.setValue("userSession", user.sessionId, user); |
| 44 | + return user; |
| 45 | + }, |
| 46 | +}); |
0 commit comments