feat(shared-sqs): remove auth from UI, add public /ui/api/ routes (v0.1.5)
- Public routes /ui/api/* without bearer token for demo - UI loads dashboard immediately, no login required - Admin API /admin/* still requires bearer token - For demo purposes only — auth will be restored later
This commit is contained in:
@@ -39,6 +39,18 @@ func (h *Handler) RegisterRoutes(r *mux.Router) {
|
||||
adminRouter.HandleFunc("/health", h.detailedHealth).Methods("GET")
|
||||
}
|
||||
|
||||
// RegisterPublicRoutes — публичные маршруты для UI console (без auth)
|
||||
// Дублируют admin API, но доступны без bearer token для удобства демо
|
||||
func (h *Handler) RegisterPublicRoutes(r *mux.Router) {
|
||||
ui := r.PathPrefix("/ui/api").Subrouter()
|
||||
ui.HandleFunc("/health", h.detailedHealth).Methods("GET")
|
||||
ui.HandleFunc("/tenants", h.listTenants).Methods("GET")
|
||||
ui.HandleFunc("/tenants", h.createTenant).Methods("POST")
|
||||
ui.HandleFunc("/tenants/{id}", h.getTenant).Methods("GET")
|
||||
ui.HandleFunc("/tenants/{id}", h.deleteTenant).Methods("DELETE")
|
||||
ui.HandleFunc("/tenants/{id}/queues", h.listTenantQueues).Methods("GET")
|
||||
}
|
||||
|
||||
// bearerAuthMiddleware — проверяет Bearer token для admin API (Trap #12)
|
||||
func (h *Handler) bearerAuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -13,8 +13,8 @@ import (
|
||||
|
||||
"shared-sqs/app/admin"
|
||||
"shared-sqs/app/auth"
|
||||
"shared-sqs/app/interfaces"
|
||||
sqs "shared-sqs/app/gosqs"
|
||||
"shared-sqs/app/interfaces"
|
||||
"shared-sqs/app/tenant"
|
||||
"shared-sqs/app/ui"
|
||||
|
||||
@@ -33,6 +33,9 @@ r.HandleFunc("/health", health).Methods("GET")
|
||||
adminHandler := admin.NewHandler(tenantStore, adminToken)
|
||||
adminHandler.RegisterRoutes(r)
|
||||
|
||||
// UI public API — без auth, для встроенной console
|
||||
adminHandler.RegisterPublicRoutes(r)
|
||||
|
||||
// UI console — встроенный SPA, публичный доступ
|
||||
r.PathPrefix("/ui").Handler(http.StripPrefix("/ui", ui.Handler()))
|
||||
|
||||
|
||||
@@ -317,22 +317,8 @@ tbody tr { cursor: pointer; }
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- ===== LOGIN ===== -->
|
||||
<div id="login-page" class="login-page">
|
||||
<div class="login-box">
|
||||
<img src="https://terra.k8c.ru/docs/nubes/nubes/2.0.2/30_registry/assets/logo.svg" alt="Nubes">
|
||||
<h1>SQS CONSOLE</h1>
|
||||
<div id="login-error" class="login-error"></div>
|
||||
<div class="form-group">
|
||||
<label for="token-input">Admin Token</label>
|
||||
<input type="password" id="token-input" placeholder="sqs-admin-..." autocomplete="off">
|
||||
</div>
|
||||
<button class="btn btn-primary" style="width:100%" onclick="doLogin()">Войти</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== APP SHELL ===== -->
|
||||
<div id="app" class="hidden">
|
||||
<!-- ===== APP SHELL (всегда видим, без логина) ===== -->
|
||||
<div id="app">
|
||||
<nav class="navbar">
|
||||
<div class="navbar-brand">
|
||||
<img src="https://terra.k8c.ru/docs/nubes/nubes/2.0.2/30_registry/assets/logo.svg" alt="Nubes">
|
||||
@@ -340,7 +326,6 @@ tbody tr { cursor: pointer; }
|
||||
</div>
|
||||
<div class="navbar-user">
|
||||
<span>admin</span>
|
||||
<button class="btn-logout" onclick="doLogout()">Выход</button>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="container">
|
||||
@@ -394,61 +379,23 @@ tbody tr { cursor: pointer; }
|
||||
|
||||
<script>
|
||||
// ===== STATE =====
|
||||
let TOKEN = '';
|
||||
let BASE = '';
|
||||
let refreshTimer = null;
|
||||
let currentTenantId = null;
|
||||
|
||||
// ===== AUTH =====
|
||||
// doLogin — проверяет токен через /admin/health и сохраняет в sessionStorage
|
||||
function doLogin() {
|
||||
const token = document.getElementById('token-input').value.trim();
|
||||
if (!token) return;
|
||||
// Определяем base URL — тот же origin что и UI
|
||||
// ===== INIT =====
|
||||
// Запуск — сразу показываем dashboard без логина
|
||||
(function init() {
|
||||
BASE = window.location.origin;
|
||||
TOKEN = token;
|
||||
api('/admin/health').then(data => {
|
||||
sessionStorage.setItem('sqs_token', token);
|
||||
document.getElementById('login-page').classList.add('hidden');
|
||||
document.getElementById('app').classList.remove('hidden');
|
||||
showDashboard();
|
||||
}).catch(err => {
|
||||
document.getElementById('login-error').textContent = 'Неверный токен';
|
||||
TOKEN = '';
|
||||
});
|
||||
}
|
||||
|
||||
// doLogout — очищает сессию и возвращает на логин
|
||||
function doLogout() {
|
||||
TOKEN = '';
|
||||
sessionStorage.removeItem('sqs_token');
|
||||
if (refreshTimer) clearInterval(refreshTimer);
|
||||
document.getElementById('app').classList.add('hidden');
|
||||
document.getElementById('login-page').classList.remove('hidden');
|
||||
document.getElementById('token-input').value = '';
|
||||
document.getElementById('login-error').textContent = '';
|
||||
}
|
||||
|
||||
// Авто-логин из sessionStorage
|
||||
(function autoLogin() {
|
||||
const saved = sessionStorage.getItem('sqs_token');
|
||||
if (saved) {
|
||||
document.getElementById('token-input').value = saved;
|
||||
doLogin();
|
||||
}
|
||||
// Enter на поле токена
|
||||
document.getElementById('token-input').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') doLogin();
|
||||
});
|
||||
})();
|
||||
|
||||
// ===== API HELPER =====
|
||||
// api — выполняет запрос к admin API с bearer token
|
||||
// api — выполняет запрос к публичному UI API (без auth)
|
||||
function api(path, opts = {}) {
|
||||
return fetch(BASE + path, {
|
||||
return fetch(BASE + '/ui/api' + path, {
|
||||
...opts,
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
...(opts.headers || {})
|
||||
}
|
||||
@@ -472,7 +419,7 @@ function showDashboard() {
|
||||
|
||||
// loadDashboard — загружает данные и обновляет DOM
|
||||
function loadDashboard() {
|
||||
Promise.all([api('/admin/health'), api('/admin/tenants')])
|
||||
Promise.all([api('/health'), api('/tenants')])
|
||||
.then(([health, tenants]) => renderDashboard(health, tenants))
|
||||
.catch(err => console.error('Dashboard load error:', err));
|
||||
}
|
||||
@@ -557,7 +504,7 @@ function showTenant(id) {
|
||||
|
||||
// loadTenant — загружает тенанта и его очереди
|
||||
function loadTenant(id) {
|
||||
Promise.all([api('/admin/tenants/' + id), api('/admin/tenants/' + id + '/queues')])
|
||||
Promise.all([api('/tenants/' + id), api('/tenants/' + id + '/queues')])
|
||||
.then(([tenant, queues]) => renderTenant(tenant, queues))
|
||||
.catch(err => {
|
||||
console.error('Tenant load error:', err);
|
||||
@@ -643,7 +590,7 @@ function closeModal() {
|
||||
document.getElementById('modal-create').classList.add('hidden');
|
||||
}
|
||||
|
||||
// createTenant — POST /admin/tenants, показывает credentials
|
||||
// createTenant — POST /tenants, показывает credentials
|
||||
function createTenant() {
|
||||
const name = document.getElementById('ct-name').value.trim();
|
||||
const maxQ = parseInt(document.getElementById('ct-queues').value) || 10;
|
||||
@@ -651,7 +598,7 @@ function createTenant() {
|
||||
document.getElementById('ct-error').textContent = 'Укажите имя';
|
||||
return;
|
||||
}
|
||||
api('/admin/tenants', {
|
||||
api('/tenants', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name: name, max_queues: maxQ })
|
||||
}).then(data => {
|
||||
@@ -670,10 +617,10 @@ function closeCredsModal() {
|
||||
document.getElementById('modal-creds').classList.add('hidden');
|
||||
}
|
||||
|
||||
// deleteTenant — DELETE /admin/tenants/{id} с подтверждением
|
||||
// deleteTenant — DELETE /tenants/{id} с подтверждением
|
||||
function deleteTenant(id, name) {
|
||||
if (!confirm('Удалить тенанта "' + name + '"?\nВсе его очереди будут удалены.')) return;
|
||||
api('/admin/tenants/' + id, { method: 'DELETE' })
|
||||
api('/tenants/' + id, { method: 'DELETE' })
|
||||
.then(() => loadDashboard())
|
||||
.catch(err => alert('Ошибка удаления: ' + err.message));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user