-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapply_patch_default.py
More file actions
282 lines (250 loc) · 17.2 KB
/
apply_patch_default.py
File metadata and controls
282 lines (250 loc) · 17.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
#!/usr/bin/env python3
"""Aplica as 4 alterações necessárias no default.html para integração do módulo de login.
Uso:
python apply_patch_default.py [caminho/para/default.html]
Se nenhum caminho for informado, assume app/static/default.html
"""
import sys
from pathlib import Path
def main():
target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("app/static/default.html")
if not target.exists():
print(f"ERRO: arquivo não encontrado: {target}")
sys.exit(1)
html = target.read_text(encoding="utf-8")
original_len = len(html)
applied = 0
# ── PATCH 1: Header — user info + logout button ──
old1 = ' <div class="hidden sm:flex items-center gap-2">\n <div class="pulse-dot w-2 h-2 rounded-full bg-emerald-400"></div>\n <span class="text-xs font-mono text-gray-500" id="status-text">online</span>\n </div>'
new1 = ''' <div class="hidden sm:flex items-center gap-3">
<div class="flex items-center gap-2">
<div class="pulse-dot w-2 h-2 rounded-full bg-emerald-400"></div>
<span class="text-xs font-mono text-gray-500" id="status-text">online</span>
</div>
<div class="h-4 w-px bg-gray-700"></div>
<div class="flex items-center gap-2">
<span class="text-xs font-mono text-gray-400" id="header-user-info"></span>
<button onclick="doLogout()" class="text-xs font-mono text-red-400/60 hover:text-red-400 transition-colors px-2 py-1 rounded-lg hover:bg-red-500/10" title="Sair">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>
</button>
</div>
</div>'''
if old1 in html:
html = html.replace(old1, new1, 1)
applied += 1
print(" [1/4] Header: user info + logout ✓")
else:
print(" [1/4] Header: FALHOU — padrão não encontrado")
# ── PATCH 2: Nav — add Users tab ──
old2 = ''' <button onclick="showView('api')" id="tab-api" class="tab-btn px-4 py-2 rounded-lg text-sm font-medium transition-all">API</button>\n </nav>'''
new2 = ''' <button onclick="showView('api')" id="tab-api" class="tab-btn px-4 py-2 rounded-lg text-sm font-medium transition-all">API</button>
<button onclick="showView('users')" id="tab-users" class="tab-btn px-4 py-2 rounded-lg text-sm font-medium transition-all" style="display:none">Usuarios</button>
</nav>'''
if old2 in html:
html = html.replace(old2, new2, 1)
applied += 1
print(" [2/4] Nav: tab Usuarios ✓")
else:
print(" [2/4] Nav: FALHOU — padrão não encontrado")
# ── PATCH 3: Users management section (before </main>) ──
users_html = '''
<!-- USERS VIEW (admin only) -->
<section id="view-users" class="view-section hidden">
<div class="max-w-3xl mx-auto space-y-6">
<div class="flex items-center justify-between mb-4">
<div>
<h2 class="font-display font-bold text-2xl text-white">Gestao de Usuarios</h2>
<p class="text-sm text-gray-500 mt-1">Cadastro, edicao e controle de acesso</p>
</div>
<button onclick="showCreateUser()" class="bg-brand-600 hover:bg-brand-500 text-white rounded-xl px-4 py-2 text-sm font-medium transition-colors glow-border flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/></svg>
Novo Usuario
</button>
</div>
<div id="user-form-panel" class="hidden glow-border rounded-2xl bg-surface-800/50 p-6 space-y-4 fade-in">
<h3 id="user-form-title" class="font-display font-semibold text-white">Novo Usuario</h3>
<form id="user-form" class="space-y-4">
<input type="hidden" id="user-form-mode" value="create">
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-xs font-mono text-gray-500 mb-1">Login</label>
<input type="text" id="user-form-login" required class="w-full bg-surface-700 text-sm text-gray-300 rounded-lg px-3 py-2 border border-brand-500/10 focus:outline-none focus:border-brand-500/30" placeholder="nome.usuario">
</div>
<div>
<label class="block text-xs font-mono text-gray-500 mb-1">Tipo</label>
<select id="user-form-type" class="w-full bg-surface-700 text-sm text-gray-300 rounded-lg px-3 py-2 border border-brand-500/10 focus:outline-none focus:border-brand-500/30">
<option value="user">Usuario Comum</option>
<option value="admin">Administrador</option>
</select>
</div>
</div>
<div>
<label class="block text-xs font-mono text-gray-500 mb-1" id="user-form-pass-label">Senha</label>
<input type="password" id="user-form-password" class="w-full bg-surface-700 text-sm text-gray-300 rounded-lg px-3 py-2 border border-brand-500/10 focus:outline-none focus:border-brand-500/30" placeholder="••••••••">
</div>
<div>
<label class="block text-xs font-mono text-gray-500 mb-1">Descricao do Perfil</label>
<textarea id="user-form-profile" rows="2" class="w-full bg-surface-700 text-sm text-gray-300 rounded-lg px-3 py-2 border border-brand-500/10 focus:outline-none focus:border-brand-500/30 resize-y" placeholder="Ex: Analista financeiro, equipe de RI"></textarea>
</div>
<div class="flex items-center gap-3">
<button type="submit" id="user-form-submit" class="bg-gradient-to-r from-brand-600 to-brand-700 hover:from-brand-500 hover:to-brand-600 text-white rounded-xl px-6 py-2.5 text-sm font-medium transition-all">Criar Usuario</button>
<button type="button" onclick="hideUserForm()" class="text-gray-500 hover:text-gray-300 text-sm px-4 py-2.5 rounded-xl hover:bg-surface-700 transition-colors">Cancelar</button>
<span id="user-form-status" class="ml-auto text-xs font-mono text-gray-600"></span>
</div>
</form>
</div>
<div id="users-list" class="space-y-3">
<p class="text-sm text-gray-600 font-mono text-center py-8">Carregando...</p>
</div>
</div>
</section>
'''
if ' </main>' in html:
html = html.replace(' </main>', users_html + ' </main>', 1)
applied += 1
print(" [3/4] Section: gestão de usuários ✓")
else:
print(" [3/4] Section: FALHOU — </main> não encontrado")
# ── PATCH 4: JavaScript — session check + user CRUD ──
old4 = ' // ── Init ──\n refreshChatNamespaces();\n </script>'
new4 = r''' // ── Session & User Management ──
let _currentUser = null;
async function checkSession() {
try {
const res = await fetch('/auth/check');
const data = await res.json();
if (!data.authenticated) { window.location.href = '/login'; return; }
_currentUser = data.user;
const el = document.getElementById('header-user-info');
if (el) {
const badge = _currentUser.user_type === 'admin' ? ' [admin]' : '';
el.textContent = _currentUser.login + badge;
}
if (_currentUser.user_type === 'admin') {
const tab = document.getElementById('tab-users');
if (tab) tab.style.display = '';
}
} catch (_) {}
}
async function doLogout() {
try { await fetch('/auth/logout', { method: 'POST' }); } catch (_) {}
window.location.href = '/login';
}
async function loadUsers() {
const list = document.getElementById('users-list');
if (!list) return;
list.innerHTML = '<p class="text-sm text-gray-600 font-mono text-center py-4">Carregando...</p>';
try {
const res = await fetch('/auth/users');
if (res.status === 403) { list.innerHTML = '<p class="text-sm text-red-400 text-center py-4">Acesso restrito a administradores</p>'; return; }
if (res.status === 401) { window.location.href = '/login'; return; }
const data = await res.json();
const users = data.users || [];
if (!users.length) { list.innerHTML = '<p class="text-sm text-gray-500 text-center py-8">Nenhum usuario cadastrado</p>'; return; }
list.innerHTML = users.map(u => {
const isAdmin = u.user_type === 'admin';
const isSelf = _currentUser && u.login === _currentUser.login;
const typeBadge = isAdmin
? '<span class="text-[0.6rem] font-mono font-bold text-cyan-400 border border-cyan-400/30 rounded px-1.5 py-0.5">ADMIN</span>'
: '<span class="text-[0.6rem] font-mono text-gray-500 border border-gray-600/30 rounded px-1.5 py-0.5">USUARIO</span>';
const selfBadge = isSelf ? '<span class="text-[0.6rem] font-mono text-emerald-400/60">(voce)</span>' : '';
const delBtn = !isSelf ? `<button onclick="removeUser('${u.login}')" class="text-red-400/60 hover:text-red-400 text-sm px-3 py-1 rounded-lg hover:bg-red-500/10 transition-colors">Excluir</button>` : '';
return `<div class="glow-border rounded-xl bg-surface-800/50 p-4 fade-in"><div class="flex items-center justify-between"><div class="flex items-center gap-3"><div class="w-9 h-9 rounded-lg bg-surface-600 flex items-center justify-center"><span class="font-display font-bold text-sm text-brand-400">${u.login.charAt(0).toUpperCase()}</span></div><div><div class="flex items-center gap-2"><p class="font-display font-semibold text-white">${u.login}</p>${typeBadge} ${selfBadge}</div><p class="text-xs text-gray-500 mt-0.5">${u.profile_description || '<em class="text-gray-600">sem descricao</em>'}</p></div></div><div class="flex items-center gap-2"><button onclick="editUser('${u.login}')" class="text-brand-400/60 hover:text-brand-400 text-sm px-3 py-1 rounded-lg hover:bg-brand-500/10 transition-colors">Editar</button>${delBtn}</div></div></div>`;
}).join('');
} catch (err) { list.innerHTML = `<p class="text-sm text-red-400 text-center py-4">${err.message}</p>`; }
}
function showCreateUser() {
document.getElementById('user-form-panel').classList.remove('hidden');
document.getElementById('user-form-title').textContent = 'Novo Usuario';
document.getElementById('user-form-mode').value = 'create';
document.getElementById('user-form-login').value = '';
document.getElementById('user-form-login').disabled = false;
document.getElementById('user-form-type').value = 'user';
document.getElementById('user-form-password').value = '';
document.getElementById('user-form-password').required = true;
document.getElementById('user-form-pass-label').textContent = 'Senha';
document.getElementById('user-form-profile').value = '';
document.getElementById('user-form-submit').textContent = 'Criar Usuario';
document.getElementById('user-form-status').textContent = '';
}
async function editUser(login) {
try {
const res = await fetch('/auth/users');
const data = await res.json();
const user = (data.users || []).find(u => u.login === login);
if (!user) return;
document.getElementById('user-form-panel').classList.remove('hidden');
document.getElementById('user-form-title').textContent = 'Editar: ' + login;
document.getElementById('user-form-mode').value = 'edit';
document.getElementById('user-form-login').value = login;
document.getElementById('user-form-login').disabled = true;
document.getElementById('user-form-type').value = user.user_type;
document.getElementById('user-form-password').value = '';
document.getElementById('user-form-password').required = false;
document.getElementById('user-form-pass-label').textContent = 'Nova Senha (deixe vazio para manter)';
document.getElementById('user-form-profile').value = user.profile_description || '';
document.getElementById('user-form-submit').textContent = 'Salvar Alteracoes';
document.getElementById('user-form-status').textContent = '';
} catch (err) { alert(err.message); }
}
function hideUserForm() { document.getElementById('user-form-panel').classList.add('hidden'); }
document.getElementById('user-form').addEventListener('submit', async (e) => {
e.preventDefault();
const mode = document.getElementById('user-form-mode').value;
const login = document.getElementById('user-form-login').value.trim();
const password = document.getElementById('user-form-password').value;
const userType = document.getElementById('user-form-type').value;
const profile = document.getElementById('user-form-profile').value;
const statusEl = document.getElementById('user-form-status');
const submitBtn = document.getElementById('user-form-submit');
if (!login) { statusEl.textContent = 'Login obrigatorio'; statusEl.className = 'ml-auto text-xs font-mono text-red-400'; return; }
if (mode === 'create' && !password) { statusEl.textContent = 'Senha obrigatoria'; statusEl.className = 'ml-auto text-xs font-mono text-red-400'; return; }
submitBtn.disabled = true;
try {
let res;
if (mode === 'create') {
res = await fetch('/auth/users', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({login, password, user_type: userType, profile_description: profile}) });
} else {
const body = { user_type: userType, profile_description: profile };
if (password) body.password = password;
res = await fetch('/auth/users/' + encodeURIComponent(login), { method: 'PUT', headers: {'Content-Type':'application/json'}, body: JSON.stringify(body) });
}
if (res.ok) { hideUserForm(); loadUsers(); }
else { const err = await res.json(); statusEl.textContent = err.detail || 'Erro'; statusEl.className = 'ml-auto text-xs font-mono text-red-400'; }
} catch (err) { statusEl.textContent = err.message; statusEl.className = 'ml-auto text-xs font-mono text-red-400'; }
finally { submitBtn.disabled = false; }
});
async function removeUser(login) {
if (!confirm('Excluir usuario "' + login + '"?')) return;
try {
const res = await fetch('/auth/users/' + encodeURIComponent(login), { method: 'DELETE' });
if (res.ok) { loadUsers(); } else { const err = await res.json(); alert(err.detail || 'Erro'); }
} catch (err) { alert(err.message); }
}
const _origShowView = showView;
showView = function(name) { _origShowView(name); if (name === 'users') loadUsers(); };
// ── Init ──
checkSession();
refreshChatNamespaces();
</script>'''
if old4 in html:
html = html.replace(old4, new4, 1)
applied += 1
print(" [4/4] JavaScript: session + user CRUD ✓")
else:
print(" [4/4] JavaScript: FALHOU — padrão não encontrado")
# ── Write result ──
if applied == 4:
target.write_text(html, encoding="utf-8")
print(f"\nSUCESSO: {applied}/4 patches aplicados ({original_len} → {len(html)} chars)")
print(f"Arquivo salvo: {target}")
else:
print(f"\nATENÇÃO: apenas {applied}/4 patches aplicados.")
if applied > 0:
target.write_text(html, encoding="utf-8")
print(f"Arquivo salvo com patches parciais: {target}")
else:
print("Nenhuma modificação feita.")
sys.exit(1)
if __name__ == "__main__":
main()