001/* 002 * The contents of this file are subject to the license and copyright 003 * detailed in the LICENSE and NOTICE files at the root of the source 004 * tree. 005 */ 006 007package org.fcrepo.kernel.impl.util; 008 009import static com.google.common.base.Strings.isNullOrEmpty; 010import static org.slf4j.LoggerFactory.getLogger; 011 012import static java.nio.charset.StandardCharsets.UTF_8; 013 014import java.net.URI; 015import java.net.URLEncoder; 016 017import com.google.common.annotations.VisibleForTesting; 018import org.slf4j.Logger; 019 020/** 021 * @author Daniel Bernstein 022 * @since Sep 25, 2017 023 */ 024public class UserUtil { 025 026 private static final Logger LOGGER = getLogger(UserUtil.class); 027 028 @VisibleForTesting 029 public static final String DEFAULT_USER_AGENT_BASE_URI = "info:fedora/local-user#"; 030 031 private UserUtil() { 032 } 033 034 /** 035 * Returns the user agent based on the session user id. 036 * @param sessionUserId the acting user's id for this session 037 * @param userAgentBaseUri the user agent base uri, optional 038 * @return the uri of the user agent 039 */ 040 public static URI getUserURI(final String sessionUserId, final String userAgentBaseUri) { 041 // user id could be in format <anonymous>, remove < at the beginning and the > at the end in this case. 042 final String userId = (sessionUserId == null ? "anonymous" : sessionUserId).replaceAll("^<|>$", ""); 043 try { 044 final URI uri = URI.create(userId); 045 // return useId if it's an absolute URI or an opaque URI 046 if (uri.isAbsolute() || uri.isOpaque()) { 047 return uri; 048 } else { 049 return buildDefaultURI(userId, userAgentBaseUri); 050 } 051 } catch (final IllegalArgumentException e) { 052 return buildDefaultURI(userId, userAgentBaseUri); 053 } 054 } 055 056 /** 057 * Build default URI with the configured base uri for agent 058 * @param userId of which a URI will be created 059 * @return URI 060 */ 061 private static URI buildDefaultURI(final String userId, final String userAgentBaseUri) { 062 var baseUri = userAgentBaseUri; 063 // Construct the default URI for the user ID that is not a URI. 064 if (isNullOrEmpty(userAgentBaseUri)) { 065 // use the default local user agent base uri 066 baseUri = DEFAULT_USER_AGENT_BASE_URI; 067 } 068 069 final String userAgentUri = baseUri + (userId.contains(" ") ? URLEncoder.encode(userId, UTF_8) : userId); 070 071 LOGGER.trace("Default URI is created for user {}: {}", userId, userAgentUri); 072 return URI.create(userAgentUri); 073 } 074 075}