Compare commits

...

2 Commits

Author SHA1 Message Date
0bca35d015 up 2026-04-18 13:34:20 +03:00
7cc1ff9555 up 2026-04-18 13:32:57 +03:00
7 changed files with 133 additions and 19 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -146,4 +146,9 @@ onMounted(async () => {
const userInitials = computed(() => { const userInitials = computed(() => {
return (userName.value[0] || 'U').toUpperCase() return (userName.value[0] || 'U').toUpperCase()
}) })
async function logout() {
await fetch('/api/logout', { method: 'POST' })
router.push('/login')
}
</script> </script>

View File

@@ -24,15 +24,26 @@
<td class="px-6 py-4 whitespace-nowrap text-sm">{{ user.login }}</td> <td class="px-6 py-4 whitespace-nowrap text-sm">{{ user.login }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm">{{ user.email }}</td> <td class="px-6 py-4 whitespace-nowrap text-sm">{{ user.email }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm"> <td class="px-6 py-4 whitespace-nowrap text-sm">
<button @click="toggleActive(user)" :class="user.active ? 'text-green-600' : 'text-red-600'"> <button
v-if="user.id !== currentUserId"
@click="toggleActive(user)"
:class="user.active ? 'text-green-600' : 'text-red-600'"
>
{{ user.active ? 'Active' : 'Inactive' }} {{ user.active ? 'Active' : 'Inactive' }}
</button> </button>
<span v-else class="text-gray-400 text-sm">(You)</span>
</td> </td>
<td class="px-6 py-4 whitespace-nowrap text-sm">{{ user.ip || '-' }}</td> <td class="px-6 py-4 whitespace-nowrap text-sm">{{ user.ip || '-' }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm">{{ formatDate(user.created) }}</td> <td class="px-6 py-4 whitespace-nowrap text-sm">{{ formatDate(user.created) }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm space-x-2"> <td class="px-6 py-4 whitespace-nowrap text-sm space-x-2">
<button @click="openModal('edit', user)" class="text-blue-600">Edit</button> <button @click="openModal('edit', user)" class="text-blue-600">Edit</button>
<button @click="deleteUser(user.id)" class="text-red-600">Delete</button> <button
v-if="user.id !== currentUserId"
@click="deleteUser(user.id)"
class="text-red-600"
>
Delete
</button>
</td> </td>
</tr> </tr>
</tbody> </tbody>
@@ -71,10 +82,24 @@
import { ref, onMounted } from 'vue'; import { ref, onMounted } from 'vue';
import AppLayout from '../components/Layout/AppLayout.vue'; import AppLayout from '../components/Layout/AppLayout.vue';
const currentUserId = ref<number | null>(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 users = ref([]);
const modalOpen = ref(false); const modalOpen = ref(false);
const modalMode = ref<'create' | 'edit'>('create'); const modalMode = ref<'create' | 'edit'>('create');
const form = ref({ id: null, login: '', password: '' }); const form = ref({ id: null, login: '', email: '', password: '' });
const modalTitle = ref(''); const modalTitle = ref('');
async function loadUsers() { async function loadUsers() {
@@ -95,10 +120,10 @@ async function toggleActive(user: any) {
function openModal(mode: 'create' | 'edit', user: any = null) { function openModal(mode: 'create' | 'edit', user: any = null) {
modalMode.value = mode; modalMode.value = mode;
if (mode === 'create') { if (mode === 'create') {
form.value = { id: null, login: '', password: '' }; form.value = { id: null, login: '', email: '', password: '' };
modalTitle.value = 'Create User'; modalTitle.value = 'Create User';
} else { } 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'; modalTitle.value = 'Edit User';
} }
modalOpen.value = true; modalOpen.value = true;
@@ -110,23 +135,36 @@ function closeModal() {
async function submitUser() { async function submitUser() {
try { 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') { 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', method: 'POST',
headers: { 'Content-Type': 'application/json' }, 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 { } else {
await fetch(`/api/admin/users/${form.value.id}`, { const res = await fetch(`/api/admin/users/${form.value.id}`, {
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, 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(); await loadUsers();
closeModal(); closeModal();
} catch (e) { } 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();
});
</script> </script>

View File

@@ -16,7 +16,7 @@
<div class="bg-white rounded-2xl shadow-xl p-8"> <div class="bg-white rounded-2xl shadow-xl p-8">
<form @submit.prevent="handleLogin" class="space-y-6"> <form @submit.prevent="handleLogin" class="space-y-6">
<div> <div>
<label class="block text-sm font-medium text-gray-700 mb-2">Username</label> <label class="block text-sm font-medium text-gray-700 mb-2">Username or Email</label>
<div class="relative"> <div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"> <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -28,7 +28,7 @@
type="text" type="text"
required required
class="input-field pl-10" class="input-field pl-10"
placeholder="Enter your username" placeholder="Enter your username or email"
/> />
</div> </div>
</div> </div>
@@ -119,9 +119,15 @@ async function handleLogin() {
if (res.ok) { if (res.ok) {
router.push('/dashboard') router.push('/dashboard')
} else {
// Пытаемся получить текст ошибки от сервера
const text = await res.text()
if (text && text.trim()) {
error.value = text
} else { } else {
error.value = 'Invalid username or password' error.value = 'Invalid username or password'
} }
}
} catch (e) { } catch (e) {
error.value = 'Network error. Please try again.' error.value = 'Network error. Please try again.'
} finally { } finally {

View File

@@ -21,10 +21,26 @@ public class AuthHandler {
return; return;
} }
userService.findByLogin(login).onComplete(ar -> { userService.findByLoginOrEmail(login).onComplete(ar -> {
if (ar.succeeded() && ar.result() != null) { if (ar.succeeded() && ar.result() != null) {
JsonObject user = ar.result(); JsonObject user = ar.result();
if (userService.checkPassword(password, user.getString("password"))) {
boolean passwordOk = userService.checkPassword(password, user.getString("password"));
if (passwordOk) {
// Надёжное получение флага активности
Boolean active = user.getBoolean("active");
if (active == null) {
// Если поле отсутствует, пробуем получить как Integer (на случай TINYINT)
Integer activeInt = user.getInteger("active");
active = activeInt != null && activeInt == 1;
}
if (!active) {
ctx.response().setStatusCode(401).end("Account not activated");
return;
}
Session session = ctx.session(); Session session = ctx.session();
session.put("userId", user.getInteger("id")); session.put("userId", user.getInteger("id"));
session.put("login", user.getString("login")); session.put("login", user.getString("login"));
@@ -39,7 +55,12 @@ public class AuthHandler {
} }
public void handleLogout(RoutingContext ctx) { 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()); ctx.response().end(new JsonObject().put("success", true).encode());
} }
@@ -50,5 +71,5 @@ public class AuthHandler {
} else { } else {
ctx.next(); ctx.next();
} }
}; }
} }

View File

@@ -186,6 +186,7 @@ public class MainVerticle extends AbstractVerticle {
rc.response().setStatusCode(400).end("Missing login, email or password"); rc.response().setStatusCode(400).end("Missing login, email or password");
return; return;
} }
// Создаём активного пользователя (active = true)
userService.createUser(login, email, password, ip, true) userService.createUser(login, email, password, ip, true)
.onSuccess(v -> rc.response().setStatusCode(201).end()) .onSuccess(v -> rc.response().setStatusCode(201).end())
.onFailure(err -> rc.response().setStatusCode(500).end(err.getMessage())); .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 -> { router.delete("/api/admin/users/:id").handler(rc -> {
int id = Integer.parseInt(rc.pathParam("id")); 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) userService.deleteUser(id)
.onSuccess(v -> rc.response().end()) .onSuccess(v -> rc.response().end())
.onFailure(err -> rc.response().setStatusCode(500).end(err.getMessage())); .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 -> { router.put("/api/admin/users/:id/activate").handler(rc -> {
int id = Integer.parseInt(rc.pathParam("id")); int id = Integer.parseInt(rc.pathParam("id"));
boolean active = Boolean.parseBoolean(rc.queryParam("active").get(0)); 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) userService.setActive(id, active)
.onSuccess(v -> rc.response().end()) .onSuccess(v -> rc.response().end())
.onFailure(err -> rc.response().setStatusCode(500).end(err.getMessage())); .onFailure(err -> rc.response().setStatusCode(500).end(err.getMessage()));

View File

@@ -5,6 +5,7 @@ import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonObject;
import io.vertx.sqlclient.Pool; import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.Row; import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.Tuple;
import io.vertx.sqlclient.templates.SqlTemplate; import io.vertx.sqlclient.templates.SqlTemplate;
import org.mindrot.jbcrypt.BCrypt; import org.mindrot.jbcrypt.BCrypt;
@@ -66,6 +67,19 @@ public class UserService {
.execute(Map.of("id", id, "active", active)).mapEmpty(); .execute(Map.of("id", id, "active", active)).mapEmpty();
} }
public Future<JsonObject> 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) {
return null;
}
Row row = rows.iterator().next();
return toJson(row);
});
}
public Future<JsonObject> findByEmail(String email) { public Future<JsonObject> findByEmail(String email) {
return SqlTemplate.forQuery(pool, "SELECT id, login, email, password, active, ip, created, updated FROM users WHERE email = #{email}") return SqlTemplate.forQuery(pool, "SELECT id, login, email, password, active, ip, created, updated FROM users WHERE email = #{email}")
.mapTo(this::toJson) .mapTo(this::toJson)
@@ -94,7 +108,16 @@ public class UserService {
.execute() .execute()
.map(rows -> { .map(rows -> {
JsonArray array = new JsonArray(); 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; return array;
}); });
} }
@@ -135,6 +158,7 @@ public class UserService {
.put("id", row.getInteger("id")) .put("id", row.getInteger("id"))
.put("login", row.getString("login")) .put("login", row.getString("login"))
.put("email", row.getString("email")) .put("email", row.getString("email"))
.put("password", row.getString("password")) // ← ДОБАВИТЬ ЭТУ СТРОКУ
.put("active", row.getBoolean("active")) .put("active", row.getBoolean("active"))
.put("ip", row.getString("ip")) .put("ip", row.getString("ip"))
.put("created", row.getLocalDateTime("created") != null ? row.getLocalDateTime("created").toString() : null) .put("created", row.getLocalDateTime("created") != null ? row.getLocalDateTime("created").toString() : null)