summaryrefslogtreecommitdiff
path: root/components/file-manager/SecurePDFViewer.tsx
blob: cd7c081aadb34d5be50becfad84ed6e3851441e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
'use client';

import React, { useEffect, useRef, useState } from 'react';
import { useSession } from 'next-auth/react';
import { WebViewerInstance } from '@pdftron/webviewer';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';

interface SecurePDFViewerProps {
  documentUrl: string;
  fileName: string;
  onClose?: () => void;
}

export function SecurePDFViewer({ documentUrl, fileName, onClose }: SecurePDFViewerProps) {
  const viewerRef = useRef<HTMLDivElement>(null);
  const instanceRef = useRef<WebViewerInstance | null>(null);
  const initialized = useRef(false);
  const isCancelled = useRef(false);
  const { data: session } = useSession();
  const [isLoading, setIsLoading] = useState(true);

  // WebViewer 초기화
  useEffect(() => {
    if (!initialized.current && viewerRef.current) {
      initialized.current = true;
      isCancelled.current = false;

      requestAnimationFrame(() => {
        if (viewerRef.current) {
          import('@pdftron/webviewer').then(({ default: WebViewer }) => {
            if (isCancelled.current) {
              console.log('📛 WebViewer 초기화 취소됨');
              return;
            }

            const viewerElement = viewerRef.current;
            if (!viewerElement) return;

            WebViewer(
              {
                path: '/pdftronWeb', // BasicContractTemplateViewer와 동일한 경로
                licenseKey: process.env.NEXT_PUBLIC_PDFTRON_WEBVIEW_KEY, // 동일한 라이센스 키
                fullAPI: true,
                enableFilePicker: false,
                enableMeasurement: false,
                enableRedaction: false,
                enableAnnotations: false,
                enableTextSelection: false,
                enableFormFilling: false,
                enablePrint: false,
                enableDownload: false,
              },
              viewerElement
            ).then(async (instance: WebViewerInstance) => {
              instanceRef.current = instance;
              
              try {
                const { disableElements } = instance.UI;
                
                // 보안을 위해 모든 도구 비활성화
                disableElements([
                  'toolsHeader',
                  'viewControlsButton',
                  'panToolButton',
                  'selectToolButton',
                  'menuButton',
                  'leftPanel',
                  'leftPanelButton',
                  'searchButton',
                  'notesPanel',
                  'notesPanelButton',
                  'toolbarGroup-Annotate',
                  'toolbarGroup-Shapes',
                  'toolbarGroup-Edit',
                  'toolbarGroup-Insert',
                  'toolbarGroup-FillAndSign',
                  'toolbarGroup-Forms',
                  'toolsOverlay',
                  'printButton',
                  'downloadButton',
                  'saveAsButton',
                  'filePickerHandler',
                  'textPopup',
                  'contextMenuPopup',
                  'pageManipulationOverlay',
                  'documentControl',
                  'header',
                  'ribbons',
                  'toggleNotesButton'
                ]);

                // CSS 적용으로 추가 보안
                const iframeWindow = instance.UI.iframeWindow;
                if (iframeWindow && iframeWindow.document) {
                  const style = iframeWindow.document.createElement('style');
                  style.textContent = `
                    /* Hide all toolbars and buttons */
                    .HeaderToolsContainer,
                    .Header,
                    .ToolsHeader,
                    .LeftHeader,
                    .RightHeader,
                    .DocumentContainer > div:first-child {
                      display: none !important;
                    }
                    
                    /* Disable right-click context menu */
                    * {
                      -webkit-user-select: none !important;
                      -moz-user-select: none !important;
                      -ms-user-select: none !important;
                      user-select: none !important;
                    }
                    
                    /* Hide page controls */
                    .DocumentContainer .PageControls {
                      display: none !important;
                    }
                    
                    /* Disable text selection cursor */
                    .pageContainer {
                      cursor: default !important;
                    }
                    
                    /* Prevent drag and drop */
                    * {
                      -webkit-user-drag: none !important;
                      -khtml-user-drag: none !important;
                      -moz-user-drag: none !important;
                      -o-user-drag: none !important;
                      user-drag: none !important;
                    }
                  `;
                  iframeWindow.document.head.appendChild(style);
                }

                console.log('📝 WebViewer 초기화 완료');
                
                // 문서 로드
                await loadSecureDocument(instance, documentUrl, fileName);
                
              } catch (uiError) {
                console.warn('⚠️ UI 설정 중 오류:', uiError);
                toast.error('뷰어 설정 중 오류가 발생했습니다.');
              }
            }).catch((error) => {
              console.error('❌ WebViewer 초기화 실패:', error);
              setIsLoading(false);
              toast.error('뷰어 초기화에 실패했습니다.');
            });
          });
        }
      });
    }

    return () => {
      if (instanceRef.current) {
        instanceRef.current.UI.dispose();
        instanceRef.current = null;
      }
      isCancelled.current = true;
    };
  }, []);

  // 문서 로드 함수
  const loadSecureDocument = async (
    instance: WebViewerInstance, 
    documentPath: string, 
    docFileName: string
  ) => {
    setIsLoading(true);
    try {
      // 절대 URL로 변환
      const fullPath = documentPath.startsWith('http') 
        ? documentPath 
        : `${window.location.origin}${documentPath}`;
      
      console.log('📄 보안 문서 로드 시작:', fullPath);
      
      // 문서 로드
      await instance.UI.loadDocument(fullPath, {
        filename: docFileName,
        extension: docFileName.split('.').pop()?.toLowerCase(),
      });

      const { documentViewer, annotationManager } = instance.Core;

      // 문서 로드 완료 이벤트
      documentViewer.addEventListener('documentLoaded', async () => {
        setIsLoading(false);
        
        // 워터마크 추가
        const watermarkText = `${session?.user?.email || 'CONFIDENTIAL'}\n${new Date().toLocaleString()}`;
        
        // 대각선 워터마크
        documentViewer.setWatermark({
          text: watermarkText,
          fontSize: 30,
          fontFamily: 'Arial',
          color: 'rgba(255, 0, 0, 0.3)',
          opacity: 30,
          diagonal: true,
        });

        // 각 페이지에 커스텀 워터마크 추가
        const pageCount = documentViewer.getPageCount();
        for (let i = 1; i <= pageCount; i++) {
          const pageInfo = documentViewer.getDocument().getPageInfo(i);
          const { width, height } = pageInfo;
          
          // FreeTextAnnotation 생성
          const watermarkAnnot = new instance.Core.Annotations.FreeTextAnnotation();
          watermarkAnnot.PageNumber = i;
          watermarkAnnot.X = width / 4;
          watermarkAnnot.Y = height / 2;
          watermarkAnnot.Width = width / 2;
          watermarkAnnot.Height = 100;
          watermarkAnnot.setContents(
            `${session?.user?.email}\n${docFileName}\n${new Date().toLocaleDateString()}`
          );
          watermarkAnnot.FillColor = new instance.Core.Annotations.Color(255, 0, 0, 0.1);
          watermarkAnnot.TextColor = new instance.Core.Annotations.Color(255, 0, 0, 0.3);
          watermarkAnnot.FontSize = '24pt';
          watermarkAnnot.TextAlign = 'center';
          watermarkAnnot.Rotation = -45;
          watermarkAnnot.ReadOnly = true;
          watermarkAnnot.Locked = true;
          watermarkAnnot.Printable = true;
          
          annotationManager.addAnnotation(watermarkAnnot);
        }
        
        annotationManager.drawAnnotations(documentViewer.getCurrentPage());
        
        // Pan 모드로 설정 (텍스트 선택 불가)
        documentViewer.setToolMode(documentViewer.getTool('Pan'));
        
        // 페이지 이동 로깅
        documentViewer.addEventListener('pageNumberUpdated', (pageNumber: number) => {
          console.log(`Page ${pageNumber} viewed at ${new Date().toISOString()}`);
          // 서버로 감사 로그 전송 가능
        });
        
        console.log('✅ 보안 문서 로드 완료');
        toast.success('문서가 안전하게 로드되었습니다.');
      });

      // 에러 처리
      documentViewer.addEventListener('error', (error: any) => {
        console.error('Document loading error:', error);
        setIsLoading(false);
        toast.error('문서 로드 중 오류가 발생했습니다.');
      });
      
    } catch (err) {
      console.error('❌ 문서 로딩 중 오류:', err);
      toast.error(`문서 로드 실패: ${err instanceof Error ? err.message : '알 수 없는 오류'}`);
      setIsLoading(false);
    }
  };

  // 키보드 단축키 차단
  useEffect(() => {
    const preventShortcuts = (e: KeyboardEvent) => {
      // Ctrl+C, Ctrl+A, Ctrl+P, Ctrl+S, F12 등 차단
      if (
        (e.ctrlKey && ['c', 'a', 'p', 's', 'x', 'v'].includes(e.key.toLowerCase())) ||
        (e.metaKey && ['c', 'a', 'p', 's', 'x', 'v'].includes(e.key.toLowerCase())) ||
        e.key === 'F12' ||
        (e.ctrlKey && e.shiftKey && ['I', 'C', 'J'].includes(e.key))
      ) {
        e.preventDefault();
        e.stopPropagation();
        return false;
      }
    };

    const preventContextMenu = (e: MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();
      return false;
    };

    const preventDrag = (e: DragEvent) => {
      e.preventDefault();
      e.stopPropagation();
      return false;
    };

    document.addEventListener('keydown', preventShortcuts);
    document.addEventListener('contextmenu', preventContextMenu);
    document.addEventListener('dragstart', preventDrag);
    
    return () => {
      document.removeEventListener('keydown', preventShortcuts);
      document.removeEventListener('contextmenu', preventContextMenu);
      document.removeEventListener('dragstart', preventDrag);
    };
  }, []);

  return (
    <div className="relative w-full h-full overflow-hidden">
      <div 
        ref={viewerRef} 
        className="w-full h-full"
        style={{
          position: 'relative',
          overflow: 'hidden',
          contain: 'layout style paint',
          minHeight: '600px'
        }}
        onCopy={(e) => {
          e.preventDefault();
          e.stopPropagation();
          return false;
        }}
        onCut={(e) => {
          e.preventDefault();
          e.stopPropagation();
          return false;
        }}
        onPaste={(e) => {
          e.preventDefault();
          e.stopPropagation();
          return false;
        }}
      >
        {isLoading && (
          <div className="absolute inset-0 flex flex-col items-center justify-center bg-white bg-opacity-90 z-50">
            <Loader2 className="h-8 w-8 text-blue-500 animate-spin mb-4" />
            <p className="text-sm text-muted-foreground">보안 문서 로딩 중...</p>
          </div>
        )}
      </div>
      
      {/* 보안 오버레이 */}
      <div 
        className="absolute inset-0 z-10 pointer-events-none"
        style={{ 
          background: 'transparent',
          userSelect: 'none',
          WebkitUserSelect: 'none',
          MozUserSelect: 'none',
          msUserSelect: 'none'
        }}
      />
    </div>
  );
}