From 3c87da75437b36b2a15a54768d00c0049cd08461 Mon Sep 17 00:00:00 2001
From: Tony Xiao <tonyx.ca@gmail.com>
Date: Wed, 25 Oct 2023 06:59:19 -0700
Subject: [PATCH] wip: Use trpc context to allow impersonating endUser

---
 .../(admin)/(authenticated)/magic-link/page.tsx   | 15 ++++++++++++++-
 packages/engine-frontend/TRPCProvider.tsx         |  6 ++++++
 2 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/apps/web/app/(admin)/(authenticated)/magic-link/page.tsx b/apps/web/app/(admin)/(authenticated)/magic-link/page.tsx
index d911d56d..49c1bcc2 100644
--- a/apps/web/app/(admin)/(authenticated)/magic-link/page.tsx
+++ b/apps/web/app/(admin)/(authenticated)/magic-link/page.tsx
@@ -1,15 +1,21 @@
 'use client'
 
+import React from 'react'
+
 import {adminRouterSchema} from '@usevenice/engine-backend/router/adminRouter'
 import {_trpcReact} from '@usevenice/engine-frontend'
-import {SchemaForm, useToast} from '@usevenice/ui'
+import {Input, Label, SchemaForm, useToast} from '@usevenice/ui'
 
 import {copyToClipboard} from '@/lib-client/copyToClipboard'
 
 export default function MagicLinkPage() {
   const {toast} = useToast()
 
+  const [endUserId, setEndUserId] = React.useState('')
+
   const createMagicLink = _trpcReact.adminCreateMagicLink.useMutation({
+    trpc: {context: {impersonatedEndUserId: endUserId}},
+    meta: {},
     onError: (err) => {
       toast({
         title: 'Error creating magic link',
@@ -22,6 +28,13 @@ export default function MagicLinkPage() {
   return (
     <div className="p-6">
       <h2 className="mb-4 text-2xl font-semibold tracking-tight">Magic link</h2>
+      <Label htmlFor="endUserId">End user ID</Label>
+      <Input
+        id="endUserId"
+        value={endUserId}
+        onChange={(e) => setEndUserId(e.target.value)}
+      />
+      <hr />
       <SchemaForm
         schema={adminRouterSchema.adminCreateMagicLink.input}
         loading={createMagicLink.isLoading}
diff --git a/packages/engine-frontend/TRPCProvider.tsx b/packages/engine-frontend/TRPCProvider.tsx
index 7f05429c..83c37e41 100644
--- a/packages/engine-frontend/TRPCProvider.tsx
+++ b/packages/engine-frontend/TRPCProvider.tsx
@@ -31,6 +31,12 @@ export function TRPCProvider({
       // createTRPCProxyClient<FlatRouter>({
       _trpcReact.createClient({
         links: [
+          () =>
+            ({op, next}) => {
+              // TODO: Implement  impersonation here based on context
+              console.log('op.context', op.context)
+              return next(op)
+            },
           (debug ? httpLink : httpBatchLink)({
             url: apiUrl ?? '/api/trpc',
             headers: () => ({