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