-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path47_AuthService.gs
More file actions
592 lines (509 loc) · 19.2 KB
/
Copy path47_AuthService.gs
File metadata and controls
592 lines (509 loc) · 19.2 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/**
* AuthService - Serviço de Autenticação Enterprise
*
* @description Wrapper e funções globais para o sistema de autenticação
* @version 5.0.0
*/
// ============================================================================
// ENTERPRISE AUTH SERVICE CLASS
// ============================================================================
/**
* Autentica usuário - WORKFLOW ÚNICO E PADRONIZADO
*
* FLUXO:
* 1. Recebe Username OU Email + Password (texto plano)
* 2. Consulta aba "Usuarios" na planilha centralizadora
* 3. Busca por Username OU Email (case-insensitive)
* 4. Compara senha em texto plano diretamente
* 5. Retorna objeto padronizado
*
* @param {Object|string} credentialsOrUsername - Username, Email ou {username, password}
* @param {string} password - Senha em texto plano
* @return {Object} {success, user, token, message}
*
* @example
* authenticateUser('admin', 'minhasenha')
* authenticateUser('admin@email.com', 'minhasenha')
* authenticateUser({ username: 'admin', password: 'minhasenha' })
*/
function authenticateUser(credentialsOrUsername, password) {
// Operação de autenticação protegida por CircuitBreaker
const authOperation = function() {
// Usa UnifiedAuthService (texto plano, consulta Usuarios)
if (typeof UnifiedAuthService !== 'undefined') {
return UnifiedAuthService.login(credentialsOrUsername, password);
}
// Fallback para EnterpriseAuthService
if (typeof EnterpriseAuthService !== 'undefined') {
return EnterpriseAuthService.authenticateUser(credentialsOrUsername, password);
}
throw new Error('Serviço de autenticação não inicializado');
};
const authFallback = function() {
Logger.log('[authenticateUser] CircuitBreaker OPEN - serviço temporariamente indisponível');
return {
success: false,
message: 'Serviço temporariamente indisponível. Tente novamente em alguns minutos.',
error: 'CIRCUIT_BREAKER_OPEN'
};
};
try {
if (typeof CircuitBreaker !== 'undefined') {
return CircuitBreaker.execute('auth_main', authOperation, authFallback, {
failureThreshold: 5,
timeout: 60000,
errorThresholdPercentage: 50
});
}
return authOperation();
} catch (e) {
Logger.log('[authenticateUser] Erro: ' + e.message);
return {
success: false,
message: 'Erro no servidor: ' + e.message,
error: e.toString()
};
}
}
/**
* Auth_login - Função chamada pelo frontend via APIClient.run('Auth_login', email, password)
*
* WORKFLOW ÚNICO:
* - Aceita Username OU Email
* - Senha em texto plano
* - Consulta aba Usuarios
*
* @param {string} emailOrUsername - Email ou username do usuário
* @param {string} password - Senha em texto plano
* @return {Object} {success, user, token, message}
*/
function Auth_login(emailOrUsername, password) {
try {
Logger.log('[Auth_login] Chamado com: ' + emailOrUsername);
// Limpa cache do usuário anterior para garantir dados atualizados
try {
CacheService.getUserCache().remove('CURRENT_USER');
} catch (e) {
// Ignora erro de cache
}
// Usa UnifiedAuthService (texto plano)
if (typeof UnifiedAuthService !== 'undefined') {
return UnifiedAuthService.login(emailOrUsername, password);
}
if (typeof EnterpriseAuthService !== 'undefined') {
return EnterpriseAuthService.authenticateUser(emailOrUsername, password);
}
throw new Error('Serviço de autenticação não disponível');
} catch (error) {
Logger.log('[Auth_login] Erro fatal: ' + error.message + '\n' + error.stack);
return {
success: false,
message: 'Erro interno no login: ' + error.message,
error: error.toString()
};
}
}
/**
* Valida sessão (wrapper global)
* @param {string} token
* @return {Object}
*/
function validateSession(token) {
return EnterpriseAuthService.validateSession(token);
}
/**
* Logout (wrapper global)
* @param {string} token
* @return {Object}
*/
function logout(token) {
return EnterpriseAuthService.logout(token);
}
/**
* Verifica permissão (wrapper global)
* @param {string} permission
* @return {boolean}
*/
function hasPermission(permission) {
return EnterpriseAuthService.hasPermission(permission);
}
/**
* Verifica role (wrapper global)
* @param {string|Array} roles
* @return {boolean}
*/
function hasRole(roles) {
return EnterpriseAuthService.hasRole(roles);
}
/**
* Troca de senha (wrapper global)
* Usa UnifiedAuthService para senhas em texto plano
*
* @param {string} username - Username ou Email
* @param {string} currentPassword - Senha atual (texto plano)
* @param {string} newPassword - Nova senha (texto plano)
* @param {boolean} isFirstAccess - Se é primeiro acesso (ignora senha atual)
* @return {Object} {success, message}
*/
function changePassword(username, currentPassword, newPassword, isFirstAccess) {
// Se primeiro acesso, usa senha atual como placeholder
if (isFirstAccess && typeof UnifiedAuthService !== 'undefined') {
// Busca usuário para obter senha atual
const user = UnifiedAuthService.login(username, currentPassword);
if (user.success || isFirstAccess) {
return UnifiedAuthService.changePassword(username, currentPassword, newPassword);
}
}
// Usa UnifiedAuthService se disponível
if (typeof UnifiedAuthService !== 'undefined') {
return UnifiedAuthService.changePassword(username, currentPassword, newPassword);
}
return EnterpriseAuthService.changePassword(username, currentPassword, newPassword, isFirstAccess);
}
/**
* Refresh token (wrapper global)
* @param {string} refreshToken
* @return {Object}
*/
function refreshAccessToken(refreshToken) {
return EnterpriseAuthService.refreshAccessToken(refreshToken);
}
// ============================================================================
// LEGACY AUTHSERVICE CLASS - BACKWARD COMPATIBILITY
// ============================================================================
/**
* @class AuthService
* @description Wrapper de compatibilidade com versões anteriores
*/
var AuthService = (function() {
function AuthService() {}
AuthService.prototype.authenticateUser = function(credentials) {
return EnterpriseAuthService.authenticateUser(credentials);
};
AuthService.prototype.validateSession = function(token) {
return EnterpriseAuthService.validateSession(token);
};
AuthService.prototype.logout = function(token) {
return EnterpriseAuthService.logout(token);
};
AuthService.prototype.changePassword = function(username, current, newPass, isFirst) {
return EnterpriseAuthService.changePassword(username, current, newPass, isFirst);
};
AuthService.prototype.getCurrentUser = function() {
return EnterpriseAuthService.getCurrentUser();
};
AuthService.prototype.hasPermission = function(permission) {
return EnterpriseAuthService.hasPermission(permission);
};
AuthService.prototype.hasRole = function(roles) {
return EnterpriseAuthService.hasRole(roles);
};
AuthService.prototype.isValidEmail = function(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};
AuthService.prototype.isValidPassword = function(password) {
return password && password.length >= AUTH_ENTERPRISE_CONFIG.PASSWORD.MIN_LENGTH;
};
return AuthService;
})();
// ============================================================================
// DECORATORS & UTILITIES
// ============================================================================
/**
* Decorator para funções que requerem autenticação
* @param {Function} fn
* @return {Function}
*/
function withAuth(fn) {
return function() {
const auth = EnterpriseAuthService.getCurrentUser();
if (!auth.success) {
return { success: false, error: 'Não autenticado', code: 'UNAUTHORIZED' };
}
return fn.apply(this, [auth.user].concat(Array.prototype.slice.call(arguments)));
};
}
/**
* Decorator para funções que requerem permissão
* @param {Function} fn
* @param {string} permission
* @return {Function}
*/
function withPermission(fn, permission) {
return function() {
EnterpriseAuthService.requirePermission(permission);
return fn.apply(this, arguments);
};
}
/**
* Decorator para funções que requerem role
* @param {Function} fn
* @param {string} role
* @return {Function}
*/
function withRole(fn, role) {
return function() {
EnterpriseAuthService.requireRole(role);
return fn.apply(this, arguments);
};
}
/**
* Obtém instância do serviço enterprise
* @return {Object}
*/
function getAuthService() {
return EnterpriseAuthService;
}
// ============================================================================
// AUDIT TRAIL - FUNÇÕES PÚBLICAS
// ============================================================================
/**
* Registra sucesso de autenticação no CircuitBreaker
* @private
*/
function _recordAuthSuccess() {
if (typeof CircuitBreaker !== 'undefined' && CircuitBreaker.recordSuccess) {
CircuitBreaker.recordSuccess('auth_main');
CircuitBreaker.recordSuccess('auth_authenticate');
}
}
/**
* Obtém logs de auditoria de segurança
* @param {Object} filters - Filtros opcionais {startDate, endDate, type, user, limit}
* @return {Object} {success, data, count}
*/
function getAuditLogs(filters) {
try {
// Verifica permissão
if (!hasPermission('audit:read')) {
return { success: false, error: 'Sem permissão para visualizar logs de auditoria' };
}
filters = filters || {};
var limit = filters.limit || 100;
// Tenta buscar da planilha de auditoria
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Auditoria') || ss.getSheetByName('AuditLog') || ss.getSheetByName('SecurityLog');
if (!sheet || sheet.getLastRow() <= 1) {
// Fallback: busca do cache de eventos de segurança
var cache = CacheService.getScriptCache();
var cachedLogs = cache.get('security_events_log');
if (cachedLogs) {
try {
var logs = JSON.parse(cachedLogs);
return { success: true, data: logs.slice(-limit), count: logs.length, source: 'cache' };
} catch (e) {}
}
return { success: true, data: [], count: 0, message: 'Nenhum log encontrado' };
}
var data = sheet.getDataRange().getValues();
var headers = data[0];
var logs = [];
// Mapeamento de colunas
var colMap = {};
headers.forEach(function(h, i) { colMap[h] = i; });
var timestampCol = colMap['Timestamp'] !== undefined ? colMap['Timestamp'] : 0;
var eventCol = colMap['Event'] !== undefined ? colMap['Event'] : (colMap['Tipo'] !== undefined ? colMap['Tipo'] : 1);
var userCol = colMap['User'] !== undefined ? colMap['User'] : (colMap['Usuario'] !== undefined ? colMap['Usuario'] : 2);
var detailsCol = colMap['Details'] !== undefined ? colMap['Details'] : (colMap['Detalhes'] !== undefined ? colMap['Detalhes'] : 3);
for (var i = 1; i < data.length; i++) {
var row = data[i];
var timestamp = row[timestampCol];
// Aplica filtros
if (filters.startDate && new Date(timestamp) < new Date(filters.startDate)) continue;
if (filters.endDate && new Date(timestamp) > new Date(filters.endDate)) continue;
if (filters.type && row[eventCol] !== filters.type) continue;
if (filters.user && row[userCol] !== filters.user) continue;
logs.push({
timestamp: timestamp,
event: row[eventCol],
user: row[userCol],
details: row[detailsCol],
ip: row[colMap['IP']] || null
});
}
// Ordena por timestamp decrescente e limita
logs.sort(function(a, b) { return new Date(b.timestamp) - new Date(a.timestamp); });
return {
success: true,
data: logs.slice(0, limit),
count: logs.length,
source: 'sheet'
};
} catch (error) {
Logger.log('[getAuditLogs] Erro: ' + error.message);
return { success: false, error: error.message, data: [] };
}
}
// ============================================================================
// TESTING & DIAGNOSTICS
// ============================================================================
/**
* Testa o sistema de autenticação enterprise
*/
function testEnterpriseAuthSystem() {
Logger.log('🔐 Testando Enterprise Auth Service v5.0.0\n');
Logger.log('='.repeat(70));
const tests = [];
// Teste 1: Health Check
Logger.log('\n📌 Teste 1: Health Check');
const health = EnterpriseAuthService.healthCheck();
Logger.log(' Status: ' + health.status);
Logger.log(' Cache: ' + health.checks.cache);
Logger.log(' Database: ' + health.checks.database);
Logger.log(' Config: ' + health.checks.config);
tests.push({ name: 'Health Check', passed: health.status === 'healthy' });
// Teste 2: getCurrentUser (Google OAuth)
Logger.log('\n📌 Teste 2: getCurrentUser()');
const result1 = EnterpriseAuthService.getCurrentUser();
Logger.log(' Sucesso: ' + result1.success);
if (result1.success) {
Logger.log(' Email: ' + result1.user.email);
Logger.log(' Role: ' + result1.user.role);
Logger.log(' Permissions: ' + JSON.stringify(result1.user.permissions));
} else {
Logger.log(' Mensagem: ' + result1.message);
}
tests.push({ name: 'getCurrentUser', passed: result1.success });
// Teste 3: Password Policy Validation
Logger.log('\n📌 Teste 3: Password Policy');
const weakPassword = 'abc';
const strongPassword = 'SecurePass123';
Logger.log(' Senha fraca ("abc"): ' + (EnterpriseAuthService.CONFIG.PASSWORD.MIN_LENGTH > 3 ? 'Rejeitada ✓' : 'Aceita ✗'));
Logger.log(' Senha forte ("SecurePass123"): Aceita ✓');
tests.push({ name: 'Password Policy', passed: true });
// Teste 4: hasPermission
Logger.log('\n📌 Teste 4: hasPermission("dashboard:read")');
const hasPerm = EnterpriseAuthService.hasPermission('dashboard:read');
Logger.log(' Resultado: ' + hasPerm);
tests.push({ name: 'hasPermission', passed: typeof hasPerm === 'boolean' });
// Teste 5: hasRole
Logger.log('\n📌 Teste 5: hasRole("Administrador")');
const hasRoleResult = EnterpriseAuthService.hasRole('Administrador');
Logger.log(' Resultado: ' + hasRoleResult);
tests.push({ name: 'hasRole', passed: typeof hasRoleResult === 'boolean' });
// Teste 6: Metrics
Logger.log('\n📌 Teste 6: Auth Metrics');
const metrics = EnterpriseAuthService.getAuthMetrics();
Logger.log(' Total Logins: ' + metrics.metrics.totalLogins);
Logger.log(' Success Rate: ' + metrics.metrics.successRate);
tests.push({ name: 'Metrics', passed: !!metrics.metrics });
// Teste 7: Config
Logger.log('\n📌 Teste 7: Enterprise Config');
Logger.log(' Password Min Length: ' + AUTH_ENTERPRISE_CONFIG.PASSWORD.MIN_LENGTH);
Logger.log(' Max Login Attempts: ' + AUTH_ENTERPRISE_CONFIG.BRUTE_FORCE.MAX_ATTEMPTS);
Logger.log(' Session Timeout: ' + AUTH_ENTERPRISE_CONFIG.SESSION.TIMEOUT_HOURS + 'h');
Logger.log(' Token TTL: ' + AUTH_ENTERPRISE_CONFIG.TOKEN.ACCESS_TTL_SECONDS + 's');
tests.push({ name: 'Config', passed: true });
// Resumo
Logger.log('\n' + '='.repeat(70));
Logger.log('📊 RESUMO DOS TESTES:');
let passed = 0;
tests.forEach(function(t) {
Logger.log(' ' + (t.passed ? '✅' : '❌') + ' ' + t.name);
if (t.passed) passed++;
});
Logger.log('\n Total: ' + passed + '/' + tests.length + ' testes passaram');
Logger.log('='.repeat(70));
return {
success: passed === tests.length,
passed: passed,
total: tests.length,
tests: tests
};
}
/**
* Lista todos os usuários cadastrados
*/
function listAllUsers() {
const usuarios = EnterpriseAuthService.getCurrentUser().success
? _getUsuariosData()
: [];
Logger.log('📋 Usuários Cadastrados:\n');
usuarios.forEach(function(u, i) {
const username = u.Username || u.username;
const email = u.Email || u.email;
const role = u.Role || u.role;
const status = u.Status || u.status;
Logger.log((i + 1) + '. ' + username + ' (' + email + ') - ' + role + ' - ' + status);
});
return usuarios.length;
}
/**
* Diagnóstico completo do sistema de autenticação
*/
function diagnoseAuthSystem() {
Logger.log('🔍 DIAGNÓSTICO DO SISTEMA DE AUTENTICAÇÃO\n');
Logger.log('='.repeat(70));
// 1. Verificar planilha
Logger.log('\n📋 1. Verificando Planilha Usuarios...');
try {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('Usuarios');
if (sheet) {
const data = sheet.getDataRange().getValues();
Logger.log(' ✅ Planilha encontrada');
Logger.log(' Colunas: ' + data[0].join(', '));
Logger.log(' Registros: ' + (data.length - 1));
} else {
Logger.log(' ❌ Planilha não encontrada');
}
} catch (e) {
Logger.log(' ❌ Erro: ' + e.message);
}
// 2. Verificar Google Session
Logger.log('\n🔑 2. Verificando Google Session...');
try {
const email = Session.getActiveUser().getEmail();
Logger.log(' Email: ' + (email || 'Não disponível'));
Logger.log(' Temp Key: ' + Session.getTemporaryActiveUserKey());
} catch (e) {
Logger.log(' ❌ Erro: ' + e.message);
}
// 3. Verificar Cache
Logger.log('\n💾 3. Verificando Cache...');
try {
const testKey = 'diag_' + Date.now();
CacheService.getUserCache().put(testKey, 'test', 10);
const cached = CacheService.getUserCache().get(testKey);
Logger.log(' User Cache: ' + (cached === 'test' ? '✅ OK' : '❌ Falha'));
CacheService.getUserCache().remove(testKey);
CacheService.getScriptCache().put(testKey, 'test', 10);
const scriptCached = CacheService.getScriptCache().get(testKey);
Logger.log(' Script Cache: ' + (scriptCached === 'test' ? '✅ OK' : '❌ Falha'));
CacheService.getScriptCache().remove(testKey);
} catch (e) {
Logger.log(' ❌ Erro: ' + e.message);
}
// 4. Verificar Config
Logger.log('\n⚙️ 4. Verificando Configuração...');
Logger.log(' AUTH_ENTERPRISE_CONFIG: ' + (typeof AUTH_ENTERPRISE_CONFIG !== 'undefined' ? '✅ Definido' : '❌ Não definido'));
Logger.log(' EnterpriseAuthService: ' + (typeof EnterpriseAuthService !== 'undefined' ? '✅ Definido' : '❌ Não definido'));
Logger.log(' AuthService (legacy): ' + (typeof AuthService !== 'undefined' ? '✅ Definido' : '❌ Não definido'));
// 5. Health Check
Logger.log('\n🏥 5. Health Check...');
const health = EnterpriseAuthService.healthCheck();
Logger.log(' Status: ' + health.status);
Logger.log(' Version: ' + health.version);
Logger.log('\n' + '='.repeat(70));
Logger.log('✅ Diagnóstico concluído');
return health;
}
// ============================================================================
// ALIASES PARA COMPATIBILIDADE
// ============================================================================
/**
* Alias para getAuditLogs (compatibilidade com frontend)
* @param {Object} [filters] - Filtros opcionais
* @return {Object} { success, data, count }
*/
function getLogs(filters) {
return getAuditLogs(filters);
}
/**
* Alias para getAuditLogs
* @param {Object} [filters] - Filtros opcionais
* @return {Object} { success, data, count }
*/
function getSystemLogs(filters) {
return getAuditLogs(filters);
}
You can’t perform that action at this time.