From 7cc1ff9555d05346d7d15cf1c8f9d618841fe65c Mon Sep 17 00:00:00 2001 From: Danil-Bodry Date: Sat, 18 Apr 2026 13:32:57 +0300 Subject: [PATCH] up --- frontend/public/favicon.ico | Bin 4286 -> 16958 bytes frontend/src/components/Layout/AppLayout.vue | 5 ++ frontend/src/views/Users.vue | 63 +++++++++++++++--- frontend/src/views/auth/Login.vue | 12 +++- .../java/su/xserver/iikocon/AuthHandler.java | 35 ++++++++-- .../java/su/xserver/iikocon/MainVerticle.java | 17 +++++ .../java/su/xserver/iikocon/UserService.java | 28 +++++++- 7 files changed, 141 insertions(+), 19 deletions(-) diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico index df36fcfb72584e00488330b560ebcf34a41c64c2..0302a8108f565e1aac19500b2828c2cd4b4741ef 100644 GIT binary patch literal 16958 zcmeI4drVVT9LKLQi&^%Ee=OO*f&(lYRTM<0$<|eaj%7w0i#;fSL-?Ou2h_tx-9`0>zO<>l+SlqOt8t_6TFcCiLqGMV5%$UqKot_!!TRJu_4|uD#?7j{W9e5TRblo7cVI_z zfpO#NKe4k?uGXKGtMnj<1DoqWO(Sza*sJw`Dv0C&^9TE^Mt9A^vxHqN2R84S!+E|> z%K`C|i00t7r4W?&-UPRa@?#GoIl${gPt!`uFQ9|#MS2*mT?C`1MZ!8D`~o`|twa5f z`2}_0smlbB9e8$Rg2)aCzrYS6{DM00)T8l_*;xd8KTzrygUAk)hQ%PV1H#YAfxJ5x zbY!uk?ZWdF?a#c4h$&2ma&J z`FS`X{4sK%w7mwtLnRaWxCFf6sOOKc?uYSnhe0_|9Esmq!QdJxO?fxjsmV&Op9pZ}=Xk)Ox>vHEPp{IPQ2X}*8NsklwLPX{xt58`z#4&xWq!Pp+!|I7og zxxi~2jPF?nB0Cu0y9`8jK==iAFy4y#AM*?9fba|KKy6(PB0Es`EeDYusQXugs1BU9 zIS}kDp!@=k19xj4-0d=f+J@!;<`>L?a;O6C4V}ylw!JhcpaYwF`J@4zgq1Kqif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/frontend/src/components/Layout/AppLayout.vue b/frontend/src/components/Layout/AppLayout.vue index 963a37f..6d250bb 100644 --- a/frontend/src/components/Layout/AppLayout.vue +++ b/frontend/src/components/Layout/AppLayout.vue @@ -146,4 +146,9 @@ onMounted(async () => { const userInitials = computed(() => { return (userName.value[0] || 'U').toUpperCase() }) + +async function logout() { + await fetch('/api/logout', { method: 'POST' }) + router.push('/login') +} diff --git a/frontend/src/views/Users.vue b/frontend/src/views/Users.vue index df3d728..c643ff0 100644 --- a/frontend/src/views/Users.vue +++ b/frontend/src/views/Users.vue @@ -24,15 +24,26 @@ {{ user.login }} {{ user.email }} - + (You) {{ user.ip || '-' }} {{ formatDate(user.created) }} - + @@ -71,10 +82,24 @@ import { ref, onMounted } from 'vue'; import AppLayout from '../components/Layout/AppLayout.vue'; +const currentUserId = ref(null); + +async function loadCurrentUser() { + try { + const res = await fetch('/api/admin/me'); + if (res.ok) { + const data = await res.json(); + currentUserId.value = data.id; + } + } catch (e) { + console.error('Failed to load current user', e); + } +} + const users = ref([]); const modalOpen = ref(false); const modalMode = ref<'create' | 'edit'>('create'); -const form = ref({ id: null, login: '', password: '' }); +const form = ref({ id: null, login: '', email: '', password: '' }); const modalTitle = ref(''); async function loadUsers() { @@ -95,10 +120,10 @@ async function toggleActive(user: any) { function openModal(mode: 'create' | 'edit', user: any = null) { modalMode.value = mode; if (mode === 'create') { - form.value = { id: null, login: '', password: '' }; + form.value = { id: null, login: '', email: '', password: '' }; modalTitle.value = 'Create User'; } else { - form.value = { id: user.id, login: user.login, password: '' }; + form.value = { id: user.id, login: user.login, email: user.email, password: '' }; // добавлен email modalTitle.value = 'Edit User'; } modalOpen.value = true; @@ -110,23 +135,36 @@ function closeModal() { async function submitUser() { try { + const payload: any = { + login: form.value.login, + email: form.value.email, + }; + if (form.value.password) { + payload.password = form.value.password; + } if (modalMode.value === 'create') { - await fetch('/api/admin/users', { + if (!form.value.password) { + alert('Password is required'); + return; + } + const res = await fetch('/api/admin/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ login: form.value.login, password: form.value.password }) + body: JSON.stringify(payload), }); + if (!res.ok) throw new Error('Create failed'); } else { - await fetch(`/api/admin/users/${form.value.id}`, { + const res = await fetch(`/api/admin/users/${form.value.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ login: form.value.login, password: form.value.password || undefined }) + body: JSON.stringify(payload), }); + if (!res.ok) throw new Error('Update failed'); } await loadUsers(); closeModal(); } catch (e) { - alert('Operation failed'); + alert('Operation failed: ' + e.message); } } @@ -137,5 +175,8 @@ async function deleteUser(id: number) { } } -onMounted(loadUsers); +onMounted(async () => { + await loadCurrentUser(); + await loadUsers(); +}); diff --git a/frontend/src/views/auth/Login.vue b/frontend/src/views/auth/Login.vue index bb40360..77567a2 100644 --- a/frontend/src/views/auth/Login.vue +++ b/frontend/src/views/auth/Login.vue @@ -16,7 +16,7 @@
- +
@@ -28,7 +28,7 @@ type="text" required class="input-field pl-10" - placeholder="Enter your username" + placeholder="Enter your username or email" />
@@ -120,7 +120,13 @@ async function handleLogin() { if (res.ok) { router.push('/dashboard') } else { - error.value = 'Invalid username or password' + // Пытаемся получить текст ошибки от сервера + const text = await res.text() + if (text && text.trim()) { + error.value = text + } else { + error.value = 'Invalid username or password' + } } } catch (e) { error.value = 'Network error. Please try again.' diff --git a/src/main/java/su/xserver/iikocon/AuthHandler.java b/src/main/java/su/xserver/iikocon/AuthHandler.java index a0f40ed..50439b2 100644 --- a/src/main/java/su/xserver/iikocon/AuthHandler.java +++ b/src/main/java/su/xserver/iikocon/AuthHandler.java @@ -21,25 +21,52 @@ public class AuthHandler { return; } - userService.findByLogin(login).onComplete(ar -> { + userService.findByLoginOrEmail(login).onComplete(ar -> { if (ar.succeeded() && ar.result() != null) { JsonObject user = ar.result(); - if (userService.checkPassword(password, user.getString("password"))) { + System.out.println("User found: " + user.encode()); + + boolean passwordOk = userService.checkPassword(password, user.getString("password")); + System.out.println("Password OK: " + passwordOk); + + if (passwordOk) { + // Надёжное получение флага активности + Boolean active = user.getBoolean("active"); + if (active == null) { + // Если поле отсутствует, пробуем получить как Integer (на случай TINYINT) + Integer activeInt = user.getInteger("active"); + active = activeInt != null && activeInt == 1; + } + System.out.println("Active flag: " + active); + + if (!active) { + System.out.println("Sending: Account not activated"); + ctx.response().setStatusCode(401).end("Account not activated"); + return; + } + Session session = ctx.session(); session.put("userId", user.getInteger("id")); session.put("login", user.getString("login")); ctx.response().end(new JsonObject().put("success", true).put("login", user.getString("login")).encode()); } else { + System.out.println("Sending: Invalid credentials (password mismatch)"); ctx.response().setStatusCode(401).end("Invalid credentials"); } } else { + System.out.println("Sending: Invalid credentials (user not found or error)"); ctx.response().setStatusCode(401).end("Invalid credentials"); } }); } public void handleLogout(RoutingContext ctx) { - ctx.session().destroy(); + Session session = ctx.session(); + if (session != null) { + session.destroy(); + } + // Явное удаление cookie сессии + ctx.response().removeCookie("admin.session"); ctx.response().end(new JsonObject().put("success", true).encode()); } @@ -50,5 +77,5 @@ public class AuthHandler { } else { ctx.next(); } - }; + } } diff --git a/src/main/java/su/xserver/iikocon/MainVerticle.java b/src/main/java/su/xserver/iikocon/MainVerticle.java index 29aebd8..909cad4 100644 --- a/src/main/java/su/xserver/iikocon/MainVerticle.java +++ b/src/main/java/su/xserver/iikocon/MainVerticle.java @@ -186,6 +186,7 @@ public class MainVerticle extends AbstractVerticle { rc.response().setStatusCode(400).end("Missing login, email or password"); return; } + // Создаём активного пользователя (active = true) userService.createUser(login, email, password, ip, true) .onSuccess(v -> rc.response().setStatusCode(201).end()) .onFailure(err -> rc.response().setStatusCode(500).end(err.getMessage())); @@ -209,6 +210,15 @@ public class MainVerticle extends AbstractVerticle { router.delete("/api/admin/users/:id").handler(rc -> { int id = Integer.parseInt(rc.pathParam("id")); + Integer currentUserId = rc.session().get("userId"); + + if (currentUserId != null && currentUserId == id) { + rc.response().setStatusCode(403).end(new JsonObject() + .put("error", "You cannot delete your own account") + .encode()); + return; + } + userService.deleteUser(id) .onSuccess(v -> rc.response().end()) .onFailure(err -> rc.response().setStatusCode(500).end(err.getMessage())); @@ -217,6 +227,13 @@ public class MainVerticle extends AbstractVerticle { router.put("/api/admin/users/:id/activate").handler(rc -> { int id = Integer.parseInt(rc.pathParam("id")); boolean active = Boolean.parseBoolean(rc.queryParam("active").get(0)); + Integer currentUserId = rc.session().get("userId"); + + if (currentUserId != null && currentUserId == id) { + rc.response().setStatusCode(403).end(new JsonObject().put("error", "You cannot deactivate yourself").encode()); + return; + } + userService.setActive(id, active) .onSuccess(v -> rc.response().end()) .onFailure(err -> rc.response().setStatusCode(500).end(err.getMessage())); diff --git a/src/main/java/su/xserver/iikocon/UserService.java b/src/main/java/su/xserver/iikocon/UserService.java index 1e41a86..425a4f9 100644 --- a/src/main/java/su/xserver/iikocon/UserService.java +++ b/src/main/java/su/xserver/iikocon/UserService.java @@ -5,6 +5,7 @@ import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.sqlclient.Pool; import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.Tuple; import io.vertx.sqlclient.templates.SqlTemplate; import org.mindrot.jbcrypt.BCrypt; @@ -66,6 +67,21 @@ public class UserService { .execute(Map.of("id", id, "active", active)).mapEmpty(); } + public Future findByLoginOrEmail(String loginOrEmail) { + String sql = "SELECT id, login, email, password, active, ip, created, updated FROM users WHERE login = ? OR email = ?"; + return pool.preparedQuery(sql) + .execute(Tuple.of(loginOrEmail, loginOrEmail)) + .map(rows -> { + if (rows.size() == 0) { + System.out.println("User not found: " + loginOrEmail); + return null; + } + Row row = rows.iterator().next(); + System.out.println("User found, active=" + row.getBoolean("active")); + return toJson(row); + }); + } + public Future findByEmail(String email) { return SqlTemplate.forQuery(pool, "SELECT id, login, email, password, active, ip, created, updated FROM users WHERE email = #{email}") .mapTo(this::toJson) @@ -94,7 +110,16 @@ public class UserService { .execute() .map(rows -> { JsonArray array = new JsonArray(); - rows.forEach(row -> array.add(toJson(row))); + for (Row row : rows) { + array.add(new JsonObject() + .put("id", row.getInteger("id")) + .put("login", row.getString("login")) + .put("email", row.getString("email")) + .put("active", row.getBoolean("active")) + .put("ip", row.getString("ip")) + .put("created", row.getLocalDateTime("created") != null ? row.getLocalDateTime("created").toString() : null) + .put("updated", row.getLocalDateTime("updated") != null ? row.getLocalDateTime("updated").toString() : null)); + } return array; }); } @@ -135,6 +160,7 @@ public class UserService { .put("id", row.getInteger("id")) .put("login", row.getString("login")) .put("email", row.getString("email")) + .put("password", row.getString("password")) // ← ДОБАВИТЬ ЭТУ СТРОКУ .put("active", row.getBoolean("active")) .put("ip", row.getString("ip")) .put("created", row.getLocalDateTime("created") != null ? row.getLocalDateTime("created").toString() : null)