SecurityUtils.java

  1. package no.nav.data.common.security;

  2. import lombok.experimental.UtilityClass;
  3. import no.nav.data.common.exceptions.ForbiddenException;
  4. import no.nav.data.common.exceptions.ValidationException;
  5. import no.nav.data.common.security.dto.UserInfo;
  6. import org.springframework.security.core.Authentication;
  7. import org.springframework.security.core.context.SecurityContextHolder;

  8. import java.util.Optional;

  9. @UtilityClass
  10. public class SecurityUtils {

  11.     public static Optional<UserInfo> getCurrentUser() {
  12.         return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
  13.                 .filter(Authentication::isAuthenticated)
  14.                 .map(authentication -> authentication.getDetails() instanceof UserInfo ui ? ui : null);
  15.     }

  16.     public static Optional<String> lookupCurrentIdent() {
  17.         return getCurrentUser().map(UserInfo::getIdent);
  18.     }

  19.     public static String getCurrentIdent() {
  20.         return lookupCurrentIdent().orElseThrow(() -> new ValidationException("Invalid user, no ident found"));
  21.     }

  22.     public static boolean isAdmin() {
  23.         return getCurrentUser().map(UserInfo::isAdmin).orElse(false);
  24.     }

  25.     public static boolean isUserOrAdmin(String ident) {
  26.         return getCurrentIdent().equals(ident) || isAdmin();
  27.     }

  28.     public static void assertIsUserOrAdmin(String ident, String message) {
  29.         if (!isUserOrAdmin(ident)) {
  30.             throw new ForbiddenException(message);
  31.         }
  32.     }

  33. }