Added redirect for '/login' when authenticated

This commit is contained in:
Andrey Terentev 2024-03-25 23:49:18 +07:00 committed by Andrey Terentev
parent b48b375e4e
commit c5d6e8d0dc
2 changed files with 51 additions and 7 deletions

View File

@ -1,23 +1,32 @@
package ru.dragonestia.picker.cp.page;
import com.vaadin.flow.component.Html;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.login.LoginI18n;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import com.vaadin.flow.router.*;
import jakarta.annotation.security.PermitAll;
import lombok.extern.log4j.Log4j2;
import ru.dragonestia.picker.cp.service.SecurityService;
@Log4j2
@AnonymousAllowed
@PermitAll
@Route("/login")
public class LoginPage extends VerticalLayout implements BeforeEnterObserver {
public class LoginPage extends VerticalLayout implements BeforeEnterObserver, AfterNavigationObserver {
private final LoginForm formLogin;
private final boolean authenticated;
public LoginPage(SecurityService securityService) {
if (securityService.getAuthenticatedAccount() != null) {
formLogin = null;
authenticated = true;
return;
}
authenticated = false;
public LoginPage() {
setAlignItems(Alignment.CENTER);
add(new Html("<h1><u>RoomPicker!</u></h1>"));
@ -47,4 +56,11 @@ public class LoginPage extends VerticalLayout implements BeforeEnterObserver {
formLogin.setError(true);
}
}
@Override
public void afterNavigation(AfterNavigationEvent afterNavigationEvent) {
if (!authenticated) return;
getUI().ifPresent(ui -> ui.navigate("/nodes"));
}
}

View File

@ -0,0 +1,28 @@
package ru.dragonestia.picker.cp.service;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.server.VaadinServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Service;
import ru.dragonestia.picker.cp.model.Account;
@Service
@RequiredArgsConstructor
public class SecurityService {
public Account getAuthenticatedAccount() {
var context = SecurityContextHolder.getContext();
if (context != null && context.getAuthentication().getPrincipal() instanceof Account account) {
return account;
}
return null;
}
public void logout() {
UI.getCurrent().getPage().setLocation("/login");
var logoutHandler = new SecurityContextLogoutHandler();
logoutHandler.logout(VaadinServletRequest.getCurrent().getHttpServletRequest(), null, null);
}
}