-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI_Routes.gs
More file actions
401 lines (356 loc) · 16.4 KB
/
Copy pathAPI_Routes.gs
File metadata and controls
401 lines (356 loc) · 16.4 KB
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/**
* @file API_Routes.gs
* @description Registro e implementação de todas as funções top-level chamáveis
* via google.script.run (única forma de invocar código backend do GAS a partir
* do frontend).
*
* GAS restringe google.script.run a funções declaradas no escopo global.
* Cada wrapper aqui:
* 1. Encapsula a lógica em Response_Handler.wrap para tratamento uniforme de erros.
* 2. Retorna o envelope {success, data, message, code} via Response_Handler.
* 3. Usa Security.sanitizeObject em dados provenientes do frontend.
*
* Nomes seguem o padrão: api_{domínio}_{ação} (ex.: api_patients_list).
* Exceções mantidas por compatibilidade com chamadas existentes:
* Auth_login_wrapper, getDashboardRealtimeIndicators, eegProcessLiveBatch,
* exportSessionRawCsv (já globais em seus módulos de origem).
*/
// ─── REGISTRO (documentação, não usado em runtime) ─────────────────────────────
const API_Routes = {
routes: {
auth: ['Auth_login_wrapper', 'auth_register_wrapper', 'auth_logout_wrapper', 'auth_verify_wrapper'],
security: ['api_security_csrf'],
patients: ['api_patients_list', 'api_patients_get', 'api_patients_create', 'api_patients_update', 'api_patients_delete'],
sessions: ['api_sessions_list', 'api_sessions_get', 'api_sessions_create', 'api_sessions_update', 'api_sessions_delete'],
biometrics: ['saveBiometricBatch'],
dashboard: ['getDashboardRealtimeIndicators'],
eeg: ['eegProcessLiveBatch'],
export: ['exportSessionRawCsv'],
sync: ['processSyncQueue'],
},
init: function() {
Logger.log('API_Routes.gs inicializado. Domínios: ' +
Object.keys(API_Routes.routes).join(', '));
}
};
// ─── GUARDA DE SESSÃO (CONTROLE DE ACESSO) ──────────────────────────────────────
/**
* Papéis autorizados a acessar dados clínicos (PII de pacientes, sessões,
* biometria, dashboard, EEG e exportações). O papel 'paciente' — único criável
* pelo registro público — NÃO acessa dados clínicos de terceiros.
* Mantido aqui como fonte única; os wrappers em Dashboard_Data/EEG_Processor/
* Export_Data referenciam esta mesma constante (escopo global do GAS).
* @const {string[]}
*/
const ROLES_CLINICAL = ['admin', 'terapeuta'];
/**
* Guarda de autenticação + autorização para rotas que tocam dados clínicos.
*
* Verifica o token de sessão via Auth.verify e, quando allowedRoles é informado,
* exige o papel correto via Security.requireRole. Em falha lança um Error com um
* `.code` ('UNAUTHORIZED' para token ausente/inválido/expirado, 'FORBIDDEN' para
* papel sem permissão):
* • Dentro de Response_Handler.wrap o erro vira o envelope correspondente.
* • Fora dele (wrappers não-envelopados) propaga ao withFailureHandler do
* google.script.run no frontend.
* Em ambos os casos a operação é abortada ANTES de tocar qualquer dado.
*
* @param {string} token Token emitido por Auth.login.
* @param {string[]} [allowedRoles] Papéis autorizados; se omitido, basta sessão válida.
* @returns {{valid:boolean,userId:string,role:string,username:string}} sessão verificada
* @throws {Error} com .code 'UNAUTHORIZED' | 'FORBIDDEN'
*/
function requireSession_(token, allowedRoles) {
var session = Auth.verify(token);
if (!session || !session.valid) {
var unauth = new Error('Sessão inválida ou expirada. Faça login novamente.');
unauth.code = 'UNAUTHORIZED';
throw unauth;
}
if (allowedRoles && allowedRoles.length) {
try {
Security.requireRole(session.role, allowedRoles);
} catch (e) {
var forbidden = new Error('Acesso negado: o papel "' + session.role +
'" não tem permissão para esta operação.');
forbidden.code = 'FORBIDDEN';
throw forbidden;
}
}
return session;
}
// ─── HELPERS DE PAYLOAD ─────────────────────────────────────────────────────
function parsePayloadObject_(payload, label) {
if (!payload) {
var missing = new Error((label || 'Payload') + ' obrigatório.');
missing.code = 'VALIDATION_ERROR';
throw missing;
}
var data = payload;
if (typeof payload === 'string') {
try {
data = JSON.parse(payload);
} catch (e) {
var invalidJson = new Error((label || 'Payload') + ' contém JSON inválido: ' + e.message);
invalidJson.code = 'VALIDATION_ERROR';
throw invalidJson;
}
}
if (!data || typeof data !== 'object' || Array.isArray(data)) {
var invalid = new Error((label || 'Payload') + ' deve ser um objeto JSON.');
invalid.code = 'VALIDATION_ERROR';
throw invalid;
}
return Security.sanitizeObject(data);
}
function ensureId_(id, label) {
if (id) return String(id);
var err = new Error((label || 'ID') + ' obrigatório.');
err.code = 'VALIDATION_ERROR';
throw err;
}
// ─── AUTH ──────────────────────────────────────────────────────────────────────
function auth_register_wrapper(username, password, email) {
return Response_Handler.wrap(function() {
var result = Auth.register(username, password, email);
if (result && result.success) {
return Response_Handler.success(
{ username: result.username, role: result.role },
result.message || 'Registro realizado com sucesso.'
);
}
return Response_Handler.error(
(result && result.message) ? result.message : 'Falha no registro.',
'REGISTER_ERROR'
);
});
}
function auth_logout_wrapper(token) {
return Response_Handler.wrap(function() {
Auth.logout(token);
return Response_Handler.success(null, 'Sessão encerrada.');
});
}
function auth_verify_wrapper(token) {
return Response_Handler.wrap(function() {
var result = Auth.verify(token);
if (result && result.valid) {
return Response_Handler.success({
valid: true,
username: result.username || '',
role: result.role || ''
});
}
return Response_Handler.unauthorized('Token inválido ou expirado.');
});
}
// ─── SECURITY ───────────────────────────────────────────────────────────────
function api_security_csrf(token) {
return Response_Handler.wrap(function() {
requireSession_(token);
return Response_Handler.success({
csrfToken: Security.createCsrfToken(token),
expiresInSeconds: Security._CSRF_TTL_SECONDS
}, 'Token CSRF emitido.');
});
}
// ─── PATIENTS ──────────────────────────────────────────────────────────────────
function api_patients_list(token) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
return Response_Handler.success(Patient_CRUD.list());
});
}
function api_patients_get(token, id) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
id = ensureId_(id, 'ID do paciente');
var patient = Patient_CRUD.getById(id);
if (!patient) return Response_Handler.notFound('Paciente');
return Response_Handler.success(patient);
});
}
function api_patients_create(token, dataJson) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
var data = parsePayloadObject_(dataJson, 'Dados do paciente');
if (!data.Name && !data.Nome) return Response_Handler.validation('Nome do paciente é obrigatório.');
var id = Patient_CRUD.create(data);
return Response_Handler.success({ id: id }, 'Paciente criado com sucesso.');
});
}
function api_patients_update(token, id, dataJson) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
id = ensureId_(id, 'ID do paciente');
var data = parsePayloadObject_(dataJson, 'Dados do paciente');
var updated = Patient_CRUD.update(id, data);
if (!updated) return Response_Handler.notFound('Paciente');
return Response_Handler.success(null, 'Paciente atualizado.');
});
}
function api_patients_delete(token, id) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
id = ensureId_(id, 'ID do paciente');
var removed = Patient_CRUD.delete(id);
if (!removed) return Response_Handler.notFound('Paciente');
return Response_Handler.success(null, 'Paciente removido.');
});
}
// ─── SESSIONS ──────────────────────────────────────────────────────────────────
function api_sessions_list(token, patientId) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
return Response_Handler.success(Session_CRUD.list(patientId));
});
}
function api_sessions_get(token, id) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
id = ensureId_(id, 'ID da sessão');
var session = Session_CRUD.getById(id);
if (!session) return Response_Handler.notFound('Sessão');
return Response_Handler.success(session);
});
}
function api_sessions_create(token, dataJson) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
var data = parsePayloadObject_(dataJson, 'Dados da sessão');
if (!data.PatientID) return Response_Handler.validation('PatientID é obrigatório.');
var id = Session_CRUD.create(data);
return Response_Handler.success({ id: id }, 'Sessão criada com sucesso.');
});
}
function api_sessions_update(token, id, dataJson) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
id = ensureId_(id, 'ID da sessão');
var data = parsePayloadObject_(dataJson, 'Dados da sessão');
var updated = Session_CRUD.update(id, data);
if (!updated) return Response_Handler.notFound('Sessão');
return Response_Handler.success(null, 'Sessão atualizada.');
});
}
function api_sessions_delete(token, id) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
id = ensureId_(id, 'ID da sessão');
var removed = Session_CRUD.delete(id);
if (!removed) return Response_Handler.notFound('Sessão');
return Response_Handler.success(null, 'Sessão removida.');
});
}
// ─── BIOMETRICS ────────────────────────────────────────────────────────────────
/**
* Persiste um lote de métricas biométricas na planilha Biometrics.
* Chamado por js_vfc.html (ENS_VFC._handleSave) com payload de métricas VFC.
*
* Payload esperado (JSON string):
* { type, sessionId, patientId, timestamp, rmssd, sdnn, pnn50, meanRR,
* meanHR, lfhf, lf, hf, totalPower, sampleCount, windowMs }
*
* @param {string} token Token de sessão (papel admin|terapeuta).
* @param {string} payloadJson JSON serializado com as métricas.
* @returns {{success: bool, data: {id: string}, message: string, code: string}}
*/
function saveBiometricBatch(token, payloadJson) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
if (!payloadJson) return Response_Handler.error('Payload obrigatório.', 'VALIDATION_ERROR');
var payload;
try {
payload = JSON.parse(payloadJson);
} catch (e) {
return Response_Handler.error('JSON inválido: ' + e.message, 'VALIDATION_ERROR');
}
payload = Security.sanitizeObject(payload);
var signalType = String(payload.type || 'UNKNOWN').toUpperCase();
var sessionId = payload.sessionId || null;
var patientId = payload.patientId || null;
var record = {
SessionID: sessionId,
PatientID: patientId,
Timestamp: payload.timestamp ? new Date(payload.timestamp) : new Date(),
Device: payload.device || 'BLE',
SignalType: signalType,
RMSSD: payload.rmssd != null ? payload.rmssd : null,
SDNN: payload.sdnn != null ? payload.sdnn : null,
LF_HF: payload.lfhf != null ? payload.lfhf : null,
Notes: JSON.stringify({
pnn50: payload.pnn50 != null ? payload.pnn50 : null,
meanRR: payload.meanRR != null ? payload.meanRR : null,
meanHR: payload.meanHR != null ? payload.meanHR : null,
lf: payload.lf != null ? payload.lf : null,
hf: payload.hf != null ? payload.hf : null,
totalPower: payload.totalPower != null ? payload.totalPower : null,
sampleCount: payload.sampleCount != null ? payload.sampleCount : null,
windowMs: payload.windowMs != null ? payload.windowMs : null,
})
};
var id = DB_Core.insert('Biometrics', record);
// Atualiza os campos resumidos na sessão ativa (VFC_RMSSD)
if (sessionId && signalType === 'VFC' && payload.rmssd != null) {
try {
DB_Core.updateById('Sessions', sessionId, { VFC_RMSSD: payload.rmssd });
} catch (e) {
Logger.log('[saveBiometricBatch] Aviso: não foi possível atualizar sessão: ' + e.message);
}
}
return Response_Handler.success({ id: id }, 'Métricas salvas com sucesso.');
});
}
// ─── SYNC QUEUE ────────────────────────────────────────────────────────────────
/**
* Processa a fila de sincronização enviada em Payload Único.
*
* Cada transação deve conter apenas os argumentos de negócio em `tx.args`
* (SEM token): o token verificado do lote é reanexado como primeiro argumento
* de cada sub-rota protegida, pois todas passaram a exigi-lo.
*
* @param {string} token Token de sessão (papel admin|terapeuta).
* @param {string} transactionsJson String JSON contendo array de transações offline.
* @returns {{success: bool, data: Object, message: string}}
*/
function processSyncQueue(token, transactionsJson) {
return Response_Handler.wrap(function() {
requireSession_(token, ROLES_CLINICAL);
var transactions;
try {
transactions = JSON.parse(transactionsJson);
} catch(e) {
return Response_Handler.error('JSON de transações inválido.', 'VALIDATION_ERROR');
}
// Mapeamos de forma explícita as rotas seguras globais a serem chamadas
var results = [];
var errors = [];
for (var j = 0; j < transactions.length; j++) {
var tx = transactions[j];
try {
var globalFn;
if (tx.fn === 'saveBiometricBatch') globalFn = saveBiometricBatch;
else if (tx.fn === 'api_patients_create') globalFn = api_patients_create;
else if (tx.fn === 'api_patients_update') globalFn = api_patients_update;
else if (tx.fn === 'api_sessions_create') globalFn = api_sessions_create;
else if (tx.fn === 'api_sessions_update') globalFn = api_sessions_update;
else if (tx.fn === 'api_sessions_delete') globalFn = api_sessions_delete;
if (globalFn) {
// Reanexa o token verificado do lote como 1º argumento de cada sub-rota.
var res = globalFn.apply(null, [token].concat(tx.args || []));
results.push(res);
} else {
errors.push('Rota restrita ou inexistente para offline: ' + tx.fn);
}
} catch(e) {
errors.push('Erro ao processar ' + tx.fn + ': ' + e.message);
}
}
return Response_Handler.success({
processed: transactions.length,
successCount: results.length,
errorsCount: errors.length,
errors: errors
}, 'Sincronização offline em lote processada com ' + transactions.length + ' itens.');
});
}