001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.auth;
003
004import java.net.Authenticator.RequestorType;
005import java.net.PasswordAuthentication;
006import java.util.HashMap;
007import java.util.Map;
008import java.util.Objects;
009
010import org.openstreetmap.josm.tools.Logging;
011import org.openstreetmap.josm.tools.Pair;
012
013/**
014 * Partial implementation of the {@link CredentialsAgent} interface.
015 * <p>
016 * Provides a memory cache for the credentials and means to query the information from the user.
017 * @since 4246
018 */
019public abstract class AbstractCredentialsAgent implements CredentialsAgent {
020
021    /**
022     * Synchronous credentials provider. Called if no credentials are cached. Can be used for user login prompt.
023     * @since 12821
024     */
025    @FunctionalInterface
026    public interface CredentialsProvider {
027        /**
028         * Fills the given response with appropriate user credentials.
029         * @param requestorType type of the entity requesting authentication
030         * @param agent the credentials agent requesting credentials
031         * @param response authentication response to fill
032         * @param username the known username, if any. Likely to be empty
033         * @param password the known password, if any. Likely to be empty
034         * @param host the host against authentication will be performed
035         */
036        void provideCredentials(RequestorType requestorType, AbstractCredentialsAgent agent, CredentialsAgentResponse response,
037                String username, String password, String host);
038    }
039
040    private static volatile CredentialsProvider credentialsProvider =
041            (a, b, c, d, e, f) -> Logging.error("Credentials provider has not been set");
042
043    /**
044     * Sets the global credentials provider.
045     * @param provider credentials provider. Called if no credentials are cached. Can be used for user login prompt
046     */
047    public static void setCredentialsProvider(CredentialsProvider provider) {
048        credentialsProvider = Objects.requireNonNull(provider, "provider");
049    }
050
051    protected Map<Pair<RequestorType, String>, PasswordAuthentication> memoryCredentialsCache = new HashMap<>();
052
053    @Override
054    public CredentialsAgentResponse getCredentials(final RequestorType requestorType, final String host, boolean noSuccessWithLastResponse)
055            throws CredentialsAgentException {
056        if (requestorType == null)
057            return null;
058        PasswordAuthentication credentials = lookup(requestorType, host);
059        final String username = (credentials == null || credentials.getUserName() == null) ? "" : credentials.getUserName();
060        final String password = (credentials == null || credentials.getPassword() == null) ? "" : String.valueOf(credentials.getPassword());
061
062        final CredentialsAgentResponse response = new CredentialsAgentResponse();
063
064        /*
065         * Last request was successful and there was no credentials stored in file (or only the username is stored).
066         * -> Try to recall credentials that have been entered manually in this session.
067         */
068        Pair<RequestorType, String> mccKey = Pair.create(requestorType, host);
069        if (!noSuccessWithLastResponse && memoryCredentialsCache.containsKey(mccKey) &&
070                (credentials == null || credentials.getPassword() == null || credentials.getPassword().length == 0)) {
071            PasswordAuthentication pa = memoryCredentialsCache.get(mccKey);
072            response.setUsername(pa.getUserName());
073            response.setPassword(pa.getPassword());
074            response.setCanceled(false);
075        /*
076         * Prompt the user for credentials. This happens the first time each
077         * josm start if the user does not save the credentials to preference
078         * file (username=="") and each time after authentication failed
079         * (noSuccessWithLastResponse == true).
080         */
081        } else if (noSuccessWithLastResponse || username.isEmpty() || password.isEmpty()) {
082            credentialsProvider.provideCredentials(requestorType, this, response, username, password, host);
083            if (response.isCanceled() || response.getUsername() == null || response.getPassword() == null) {
084                return response;
085            }
086            if (response.isSaveCredentials()) {
087                store(requestorType, host, new PasswordAuthentication(
088                        response.getUsername(),
089                        response.getPassword()
090                ));
091            } else {
092                // User decides not to save credentials to file. Keep it in memory so we don't have to ask over and over again.
093                memoryCredentialsCache.put(mccKey, new PasswordAuthentication(response.getUsername(), response.getPassword()));
094            }
095        } else {
096            // We got it from file.
097            response.setUsername(username);
098            response.setPassword(password.toCharArray());
099            response.setCanceled(false);
100        }
101        return response;
102    }
103
104    @Override
105    public final void purgeCredentialsCache(RequestorType requestorType) {
106        memoryCredentialsCache.keySet().removeIf(pair -> pair.a == requestorType);
107    }
108
109    @Override
110    public void purgeCredentialsCache(RequestorType requestorType, String host) {
111        memoryCredentialsCache.remove(Pair.create(requestorType, host));
112    }
113
114    /**
115     * Provide the text for a checkbox that offers to save the
116     * username and password that has been entered by the user.
117     * @return checkbox text
118     */
119    public abstract String getSaveUsernameAndPasswordCheckboxText();
120}