Files
iiko-connector/src/main/java/su/xserver/iikocon/handler/AuthHandler.java
2026-04-20 15:57:50 +03:00

85 lines
2.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package su.xserver.iikocon.handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import su.xserver.iikocon.service.UserService;
public class AuthHandler {
private final UserService userService;
public AuthHandler(UserService userService) {
this.userService = userService;
}
public void handleLogin(RoutingContext ctx) {
JsonObject body = ctx.body().asJsonObject();
String login = body.getString("login");
String password = body.getString("password");
if (login == null || password == null) {
ctx.response().setStatusCode(400).end("Missing credentials");
return;
}
userService.findByLoginOrEmail(login).onComplete(ar -> {
if (ar.succeeded() && ar.result() != null) {
JsonObject user = ar.result();
boolean passwordOk = userService.checkPassword(password, user.getString("password"));
if (passwordOk) {
Boolean active = user.getBoolean("active");
if (active == null) {
Integer activeInt = user.getInteger("active");
active = activeInt != null && activeInt == 1;
}
if (!active) {
ctx.response().setStatusCode(401).end("Account not activated");
return;
}
// Получаем реальный IP клиента (с учётом прокси, если настроен)
String clientIp = ctx.get("realClientIp");
if (clientIp == null) {
clientIp = ctx.request().remoteAddress().host();
}
// Обновляем IP в БД (асинхронно, не дожидаемся ответа)
userService.updateUserIp(user.getInteger("id"), clientIp)
.onFailure(err -> System.err.println("Failed to update IP for user " + user.getInteger("id") + ": " + err.getMessage()));
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 {
ctx.response().setStatusCode(401).end("Invalid credentials");
}
} else {
ctx.response().setStatusCode(401).end("Invalid credentials");
}
});
}
public void handleLogout(RoutingContext ctx) {
Session session = ctx.session();
if (session != null) {
session.destroy();
}
// Явное удаление cookie сессии
ctx.response().removeCookie("admin.session");
ctx.response().end(new JsonObject().put("success", true).encode());
}
public void requireAuth(RoutingContext ctx) {
Session session = ctx.session();
if (session == null || session.get("userId") == null) {
ctx.response().setStatusCode(401).end("Unauthorized");
} else {
ctx.next();
}
}
}