
com.xlrit.gears.engine.security.AuthManagerImpl Maven / Gradle / Ivy
package com.xlrit.gears.engine.security;
import java.util.Set;
import java.util.stream.Collectors;
import jakarta.annotation.Nullable;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import com.google.common.collect.Sets;
import com.xlrit.gears.base.model.User;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component
public class AuthManagerImpl implements AuthManagerSession {
@PersistenceContext
private EntityManager em;
@Override
@Nullable
public User getCurrentUser() {
String currentUserId = getCurrentUserId();
if (currentUserId == null) return null;
return em.getReference(User.class, currentUserId);
}
@Override
@Nullable
public String getCurrentUserId() {
var authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication == null ? null : authentication.getName();
}
@Override
@Nullable // or return empty list when there's no user? (probably consistent with anonymous authentication)
public Set getCurrentUserRoleNames() {
var authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) return null;
return authentication.getAuthorities().stream()
.filter(authority -> authority instanceof RoleAuthority)
.map(authority -> ((RoleAuthority) authority).getName())
.collect(Collectors.toSet());
}
@Override
public boolean hasRole(String roleName) {
var authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) return false;
String auth = "ROLE_" + roleName;
return authentication.getAuthorities().stream()
.anyMatch(authority -> auth.equals(authority.getAuthority()));
}
@Override
public boolean hasAnyRole(Set requiredRoleNames) {
if (requiredRoleNames.isEmpty()) return false;
Set actualRoleNames = getCurrentUserRoleNames();
if (actualRoleNames == null || actualRoleNames.isEmpty()) return false;
Sets.SetView intersection = Sets.intersection(requiredRoleNames, actualRoleNames);
return !intersection.isEmpty();
}
@Override
public boolean isAdmin() {
return hasRole(ADMIN);
}
@Override
public void flush() {
// nothing to do
}
@Override
public void close() {
// nothing to do
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy