File size: 14,402 Bytes
78494de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SecureMed</title>
  <style>
    :root { color-scheme: light; font-family: system-ui, -apple-system, sans-serif; color: #183044; background: #f2f6f8; }
    * { box-sizing: border-box; }
    body { margin: 0; }
    header { background: #123b52; color: white; padding: 1.2rem max(1rem, calc((100vw - 980px)/2)); display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
    header strong { font-size: 1.25rem; letter-spacing: .02em; }
    header span { color: #c5e7ed; font-size: .9rem; }
    main { max-width: 980px; margin: 2rem auto; padding: 0 1rem; }
    .card { background: white; border: 1px solid #d9e5e9; border-radius: 15px; padding: 1.5rem; box-shadow: 0 10px 30px #16384b0b; margin-bottom: 1rem; }
    h1 { font-size: clamp(1.7rem, 4vw, 2.4rem); margin: 0 0 .7rem; }
    h2 { font-size: 1.15rem; margin: 0 0 1rem; }
    p { line-height: 1.55; }
    .muted { color: #607584; }
    .row { display: flex; gap: .7rem; flex-wrap: wrap; align-items: center; }
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(270px, 1fr)); gap: 1rem; }
    button { border: 0; border-radius: 9px; padding: .75rem 1rem; font: inherit; font-weight: 650; cursor: pointer; background: #007b83; color: white; }
    button.secondary { background: #e7f2f3; color: #075d66; }
    button:disabled { opacity: .55; cursor: wait; }
    input { width: 100%; padding: .72rem .8rem; border: 1px solid #afc3cc; border-radius: 8px; font: inherit; background: white; }
    label { display: block; font-weight: 620; margin: .7rem 0 .35rem; }
    form button { margin-top: .9rem; }
    #notice { min-height: 1.5rem; margin: 0 0 1rem; color: #005f66; }
    #notice.error { color: #a12c30; }
    .record { border-top: 1px solid #e1ebef; padding: .65rem 0; }
    [hidden] { display: none !important; }
  </style>
</head>
<body>
  <header><strong>SecureMed</strong><span>Medical image diagnosis portal</span></header>
  <main>
    <p id="notice" role="status" aria-live="polite"></p>
    <section id="guest" class="card">
      <h1>安全地查看诊断记录</h1>
      <p class="muted">患者可以注册、查看本人记录并上传图片;医生可以查询患者并提交诊断。</p>
      <div class="row">
        <button id="google-login">使用 Google 登录</button>
        <button id="cognito-login" class="secondary">账号登录</button>
        <button id="sign-up" class="secondary">注册患者账号</button>
      </div>
      <p class="muted">身份验证由 Amazon Cognito 完成。医生账号由管理员创建。</p>
    </section>

    <section id="signed-in" hidden>
      <div class="card row" style="justify-content:space-between">
        <div><strong id="identity"></strong><div class="muted" id="role-label"></div></div>
        <button id="sign-out" class="secondary">退出登录</button>
      </div>

      <section id="patient" hidden>
        <div class="grid">
          <div class="card">
            <h2>我的病历</h2>
            <p id="patient-summary"></p>
            <div id="patient-diagnoses"></div>
            <button id="refresh-patient" class="secondary">刷新记录</button>
          </div>
          <div class="card">
            <h2>上传图片诊断</h2>
            <form id="patient-scan-form">
              <label for="patient-image">JPEG 或 PNG 图片</label>
              <input id="patient-image" type="file" accept="image/jpeg,image/png" required>
              <button type="submit">提交诊断</button>
            </form>
          </div>
        </div>
      </section>

      <section id="doctor" hidden>
        <div class="grid">
          <div class="card">
            <h2>查询患者</h2>
            <form id="lookup-form">
              <label for="lookup-id">患者 ID</label>
              <input id="lookup-id" required placeholder="P1001">
              <button type="submit">查询病历</button>
            </form>
            <div id="lookup-result"></div>
          </div>
          <div class="card">
            <h2>为患者提交诊断</h2>
            <form id="doctor-scan-form">
              <label for="doctor-patient-id">患者 ID</label>
              <input id="doctor-patient-id" required placeholder="P1001">
              <label for="doctor-image">JPEG 或 PNG 图片</label>
              <input id="doctor-image" type="file" accept="image/jpeg,image/png" required>
              <button type="submit">提交诊断</button>
            </form>
          </div>
        </div>
      </section>
    </section>
  </main>
  <script>
    const $ = id => document.getElementById(id);
    let redirectUri;
    let config;

    function notice(message, error = false) {
      $('notice').textContent = message;
      $('notice').classList.toggle('error', error);
    }

    function decodeClaims(token) {
      const payload = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
      return JSON.parse(atob(payload));
    }

    function base64url(bytes) {
      return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }

    function sha256(input) {
      const k = [
        0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
        0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
        0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
        0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
        0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
        0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
        0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
        0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
      ];
      const h = [0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];
      const bytes = Array.from(new TextEncoder().encode(input));
      const bitLength = bytes.length * 8;
      bytes.push(0x80);
      while (bytes.length % 64 !== 56) bytes.push(0);
      for (let i = 7; i >= 0; i--) bytes.push(Math.floor(bitLength / 2 ** (i * 8)) & 255);
      const rotr = (x, n) => (x >>> n) | (x << (32 - n));
      for (let start = 0; start < bytes.length; start += 64) {
        const w = new Array(64);
        for (let i = 0; i < 16; i++) {
          const j = start + i * 4;
          w[i] = ((bytes[j] << 24) | (bytes[j+1] << 16) | (bytes[j+2] << 8) | bytes[j+3]) >>> 0;
        }
        for (let i = 16; i < 64; i++) {
          const s0 = rotr(w[i-15],7) ^ rotr(w[i-15],18) ^ (w[i-15] >>> 3);
          const s1 = rotr(w[i-2],17) ^ rotr(w[i-2],19) ^ (w[i-2] >>> 10);
          w[i] = (w[i-16] + s0 + w[i-7] + s1) >>> 0;
        }
        let [a,b,c,d,e,f,g,q] = h;
        for (let i = 0; i < 64; i++) {
          const s1 = rotr(e,6) ^ rotr(e,11) ^ rotr(e,25);
          const ch = (e & f) ^ (~e & g);
          const t1 = (q + s1 + ch + k[i] + w[i]) >>> 0;
          const s0 = rotr(a,2) ^ rotr(a,13) ^ rotr(a,22);
          const maj = (a & b) ^ (a & c) ^ (b & c);
          const t2 = (s0 + maj) >>> 0;
          q=g; g=f; f=e; e=(d+t1)>>>0; d=c; c=b; b=a; a=(t1+t2)>>>0;
        }
        [a,b,c,d,e,f,g,q].forEach((v,i) => h[i] = (h[i] + v) >>> 0);
      }
      return new Uint8Array(h.flatMap(v => [v >>> 24, (v >>> 16)&255, (v >>> 8)&255, v&255]));
    }

    async function beginAuth(kind) {
      if (!config.domain || !config.client_id) {
        notice('登录尚未配置,请联系管理员。', true);
        return;
      }
      const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
      const challenge = base64url(sha256(verifier));
      const state = base64url(crypto.getRandomValues(new Uint8Array(16)));
      sessionStorage.setItem('securemed_pkce', JSON.stringify({verifier, state}));
      const params = new URLSearchParams({
        response_type: 'code', client_id: config.client_id, redirect_uri: redirectUri,
        scope: 'openid email profile', state, code_challenge: challenge, code_challenge_method: 'S256'
      });
      if (kind === 'google') params.set('identity_provider', 'Google');
      const path = kind === 'signup' ? '/signup' : '/oauth2/authorize';
      location.assign(config.domain + path + '?' + params);
    }

    async function finishAuth() {
      const params = new URLSearchParams(location.search);
      if (params.has('error')) throw new Error(params.get('error_description') || '登录失败');
      if (!params.has('code')) return;
      const pending = JSON.parse(sessionStorage.getItem('securemed_pkce') || 'null');
      sessionStorage.removeItem('securemed_pkce');
      if (!pending || pending.state !== params.get('state')) throw new Error('登录状态校验失败,请重新登录');
      const body = new URLSearchParams({
        grant_type: 'authorization_code', client_id: config.client_id,
        code: params.get('code'), redirect_uri: redirectUri, code_verifier: pending.verifier
      });
      const response = await fetch(config.domain + '/oauth2/token', {
        method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body
      });
      const result = await response.json();
      if (!response.ok || !result.access_token) throw new Error('无法取得登录令牌');
      sessionStorage.setItem('securemed_access_token', result.access_token);
      history.replaceState(null, '', '/');
    }

    async function api(path, options = {}) {
      const token = sessionStorage.getItem('securemed_access_token');
      const response = await fetch(path, {
        ...options,
        headers: {...options.headers, Authorization: 'Bearer ' + token}
      });
      let data;
      try { data = await response.json(); } catch { data = {}; }
      if (!response.ok) {
        const error = new Error(typeof data.detail === 'string' ? data.detail : '请求失败');
        error.status = response.status;
        throw error;
      }
      return data;
    }

    function showRecords(target, records) {
      target.replaceChildren();
      if (!records.length) { target.textContent = '暂无诊断记录'; return; }
      records.forEach((item, index) => {
        const row = document.createElement('div');
        row.className = 'record';
        row.textContent = `第 ${index + 1} 次诊断:等级 ${item.diagnosis}`;
        target.append(row);
      });
    }

    async function loadPatient() {
      const data = await api('/api/patient/me');
      $('patient-summary').textContent = `${data.name} · ${data.patient_id}`;
      showRecords($('patient-diagnoses'), data.diagnoses);
      $('patient').hidden = false;
    }

    async function showSession() {
      const token = sessionStorage.getItem('securemed_access_token');
      if (!token) return;
      const claims = decodeClaims(token);
      if (claims.exp * 1000 <= Date.now()) {
        sessionStorage.removeItem('securemed_access_token');
        notice('登录已过期,请重新登录。', true);
        return;
      }
      const groups = claims['cognito:groups'] || [];
      const doctor = Array.isArray(groups) && groups.includes('doctor');
      $('identity').textContent = claims.username || claims.sub;
      $('role-label').textContent = doctor ? '医生' : '患者';
      $('guest').hidden = true;
      $('signed-in').hidden = false;
      if (doctor) {
        $('doctor').hidden = false;
      } else {
        await loadPatient();
      }
    }

    $('google-login').onclick = () => beginAuth('google');
    $('cognito-login').onclick = () => beginAuth('login');
    $('sign-up').onclick = () => beginAuth('signup');
    $('sign-out').onclick = () => {
      sessionStorage.removeItem('securemed_access_token');
      $('signed-in').hidden = true;
      $('guest').hidden = false;
      notice('已退出登录');
    };
    $('refresh-patient').onclick = () => loadPatient().catch(error => notice(error.message, true));

    async function submitScan(form, path, fileInput) {
      const body = new FormData();
      body.append('image', fileInput.files[0]);
      const result = await api(path, {method: 'POST', body});
      notice(`诊断完成:等级 ${result.diagnosis}`);
      form.reset();
      return result;
    }

    $('patient-scan-form').onsubmit = async event => {
      event.preventDefault();
      try {
        await submitScan(event.target, '/api/patient/scan', $('patient-image'));
        await loadPatient();
      } catch (error) { notice(error.message, true); }
    };
    $('lookup-form').onsubmit = async event => {
      event.preventDefault();
      try {
        const id = encodeURIComponent($('lookup-id').value.trim());
        const data = await api('/api/doctor/patients/' + id);
        $('lookup-result').replaceChildren();
        const heading = document.createElement('p');
        heading.textContent = `${data.name} · ${data.patient_id}`;
        $('lookup-result').append(heading);
        const records = document.createElement('div');
        showRecords(records, data.diagnoses);
        $('lookup-result').append(records);
        $('doctor-patient-id').value = data.patient_id;
        notice('已找到患者');
      } catch (error) { notice(error.message, true); }
    };
    $('doctor-scan-form').onsubmit = async event => {
      event.preventDefault();
      try {
        const id = encodeURIComponent($('doctor-patient-id').value.trim());
        await submitScan(event.target, '/api/doctor/scan?patient_id=' + id, $('doctor-image'));
        $('lookup-id').value = decodeURIComponent(id);
        $('lookup-form').requestSubmit();
      } catch (error) { notice(error.message, true); }
    };

    (async () => {
      try {
        const response = await fetch('/api/web-config');
        config = await response.json();
        config.domain = config.domain.replace(/\/$/, '');
        redirectUri = config.redirect_uri || location.origin + '/';
        await finishAuth();
        await showSession();
      } catch (error) { notice(error.message, true); }
    })();
  </script>
</body>
</html>