Joaquín Reñé
2025-10-07 146a0fb8b0e90f9196e569152f649baf60d6cc8f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
 * 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
 * <p>
 * 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
     * <p>
     * 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
     * <p>
     * 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;
    }
}