/* * Copyright @ 2013 CurisTEC, S.A.S. All Rights Reserved. */ package net.curisit.securis.services.helpers; import jakarta.enterprise.context.ApplicationScoped; import jakarta.persistence.EntityManager; import jakarta.ws.rs.core.Response.Status; import net.curisit.securis.db.User; import net.curisit.securis.security.BasicSecurityContext; import net.curisit.securis.services.exception.SeCurisServiceException; /** * UserHelper *

* Small helper to resolve the current user (from security context) or by username. * Throws a typed {@link SeCurisServiceException} if the user cannot be found. * * Thread-safety: ApplicationScoped, stateless. * * @author JRA * Last reviewed by JRA on Oct 5, 2025. */ @ApplicationScoped public class UserHelper { /** * getUser *

* Resolve the current authenticated user from {@link BasicSecurityContext}. * * @param bsc Security context containing a principal. * @param em EntityManager to fetch the user. * @return Managed {@link User}. * @throws SeCurisServiceException if the principal is null or not found in DB. */ public User getUser(BasicSecurityContext bsc, EntityManager em) throws SeCurisServiceException { String username = bsc.getUserPrincipal().getName(); return getUser(username, em); } /** * getUser *

* Resolve a user by username. * * @param username Username to look up (nullable allowed; returns null). * @param em EntityManager to fetch the user. * @return Managed {@link User} or null if username is null. * @throws SeCurisServiceException if a non-null username does not exist. */ public User getUser(String username, EntityManager em) throws SeCurisServiceException { User user = null; if (username != null) { user = em.find(User.class, username); if (user == null) { throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "User not found with username: " + username); } } return user; } }