001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.preferences.server;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.BorderLayout;
007import java.awt.FlowLayout;
008import java.awt.GridBagConstraints;
009import java.awt.GridBagLayout;
010import java.awt.Insets;
011import java.awt.event.ItemEvent;
012import java.awt.event.ItemListener;
013import java.beans.PropertyChangeEvent;
014import java.beans.PropertyChangeListener;
015
016import javax.swing.ButtonGroup;
017import javax.swing.JPanel;
018import javax.swing.JRadioButton;
019
020import org.openstreetmap.josm.data.UserIdentityManager;
021import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
022import org.openstreetmap.josm.data.oauth.OAuthVersion;
023import org.openstreetmap.josm.data.preferences.JosmUrls;
024import org.openstreetmap.josm.gui.help.HelpUtil;
025import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
026import org.openstreetmap.josm.io.OsmApi;
027import org.openstreetmap.josm.io.auth.CredentialsManager;
028import org.openstreetmap.josm.spi.preferences.Config;
029import org.openstreetmap.josm.tools.GBC;
030import org.openstreetmap.josm.tools.Logging;
031
032/**
033 * This is the preference panel for the authentication method and the authentication parameters.
034 * @since 2745
035 */
036public class AuthenticationPreferencesPanel extends VerticallyScrollablePanel implements PropertyChangeListener {
037
038    /** indicates whether we use basic authentication */
039    private final JRadioButton rbBasicAuthentication = new JRadioButton();
040    /** indicates whether we use OAuth 2.0 as authentication scheme */
041    private final JRadioButton rbOAuth20 = new JRadioButton();
042    /** the panel which contains the authentication parameters for the respective authentication scheme */
043    private final JPanel pnlAuthenticationParameters = new JPanel(new BorderLayout());
044    /** the panel for the basic authentication parameters */
045    private BasicAuthenticationPreferencesPanel pnlBasicAuthPreferences;
046    /** the panel for the OAuth 2.0 authentication parameters */
047    private OAuthAuthenticationPreferencesPanel pnlOAuth20Preferences;
048
049    /**
050     * Constructs a new {@code AuthenticationPreferencesPanel}.
051     */
052    public AuthenticationPreferencesPanel() {
053        build();
054        initFromPreferences();
055        HelpUtil.setHelpContext(this, HelpUtil.ht("/Preferences/Connection#AuthenticationSettings"));
056    }
057
058    /**
059     * builds the UI
060     */
061    protected final void build() {
062        setLayout(new GridBagLayout());
063
064        AuthenticationMethodChangeListener authChangeListener = new AuthenticationMethodChangeListener();
065
066        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
067        // -- radio button for basic authentication
068        buttonPanel.add(rbBasicAuthentication);
069        rbBasicAuthentication.setText(tr("Use Basic Authentication"));
070        rbBasicAuthentication.setToolTipText(tr("Select to use HTTP basic authentication with your OSM username and password"));
071        rbBasicAuthentication.addItemListener(authChangeListener);
072        //-- radio button for OAuth 2.0
073        buttonPanel.add(rbOAuth20);
074        rbOAuth20.setSelected(true); // This must before adding the listener; otherwise, saveToPreferences is called prior to initFromPreferences
075        rbOAuth20.setText(tr("Use OAuth {0}", "2.0"));
076        rbOAuth20.setToolTipText(tr("Select to use OAuth {0} as authentication mechanism", "2.0"));
077        rbOAuth20.addItemListener(authChangeListener);
078
079        add(buttonPanel, GBC.eol());
080        //-- radio button for OAuth
081        ButtonGroup bg = new ButtonGroup();
082        bg.add(rbBasicAuthentication);
083        bg.add(rbOAuth20);
084
085        //-- add the panel which will hold the authentication parameters
086        GridBagConstraints gc = new GridBagConstraints();
087        gc.anchor = GridBagConstraints.NORTHWEST;
088        gc.insets = new Insets(0, 0, 0, 3);
089        gc.gridx = 0;
090        gc.gridy = 1;
091        gc.gridwidth = 2;
092        gc.fill = GridBagConstraints.BOTH;
093        gc.weightx = 1.0;
094        gc.weighty = 1.0;
095        add(pnlAuthenticationParameters, gc);
096
097        //-- the two panels for authentication parameters
098        pnlBasicAuthPreferences = new BasicAuthenticationPreferencesPanel();
099        pnlOAuth20Preferences = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
100
101        pnlAuthenticationParameters.add(pnlOAuth20Preferences, BorderLayout.CENTER);
102        this.updateAcceptableAuthenticationMethods(OsmApi.getOsmApi().getServerUrl());
103    }
104
105    /**
106     * Initializes the panel from preferences
107     */
108    public final void initFromPreferences() {
109        final String authMethod = OsmApi.getAuthMethod();
110        if ("basic".equals(authMethod)) {
111            rbBasicAuthentication.setSelected(true);
112        } else if ("oauth20".equals(authMethod)) {
113            rbOAuth20.setSelected(true);
114        } else {
115            Logging.warn(
116                    tr("Unsupported value in preference ''{0}'', got ''{1}''. Using authentication method ''OAuth 2.0 Authentication''.",
117                            "osm-server.auth-method", authMethod));
118            rbOAuth20.setSelected(true);
119        }
120        pnlBasicAuthPreferences.initFromPreferences();
121        pnlOAuth20Preferences.initFromPreferences();
122    }
123
124    /**
125     * Saves the current values to the preferences
126     */
127    public final void saveToPreferences() {
128        // save the authentication method
129        String authMethod;
130        if (rbBasicAuthentication.isSelected()) {
131            authMethod = "basic";
132        } else if (rbOAuth20.isSelected()) {
133            authMethod = "oauth20";
134        } else {
135            throw new IllegalStateException("One of OAuth 2.0, OAuth 1.0a, or Basic authentication must be checked");
136        }
137        final boolean initUser = Config.getPref().put("osm-server.auth-method", authMethod);
138        if ("basic".equals(authMethod)) {
139            // save username and password and clear the OAuth token
140            pnlBasicAuthPreferences.saveToPreferences();
141            OAuthAccessTokenHolder.getInstance().clear();
142            OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
143        } else if ("oauth20".equals(authMethod)) {
144            // oauth20
145            // clear the password in the preferences
146            pnlBasicAuthPreferences.clearPassword();
147            pnlOAuth20Preferences.saveToPreferences();
148        }
149        if (initUser) {
150            if ("basic".equals(authMethod)) {
151                UserIdentityManager.getInstance().initFromPreferences();
152            } else if (OsmApi.isUsingOAuthAndOAuthSetUp(OsmApi.getOsmApi())) {
153                UserIdentityManager.getInstance().initFromOAuth();
154            } else {
155                UserIdentityManager.getInstance().setAnonymous();
156            }
157        }
158    }
159
160    /**
161     * Listens to changes in the authentication method
162     */
163    class AuthenticationMethodChangeListener implements ItemListener {
164        @Override
165        public void itemStateChanged(ItemEvent e) {
166            pnlAuthenticationParameters.removeAll();
167            if (rbBasicAuthentication.isSelected()) {
168                pnlAuthenticationParameters.add(pnlBasicAuthPreferences, BorderLayout.CENTER);
169                pnlBasicAuthPreferences.revalidate();
170            } else if (rbOAuth20.isSelected()) {
171                pnlAuthenticationParameters.add(pnlOAuth20Preferences, BorderLayout.CENTER);
172                pnlOAuth20Preferences.saveToPreferences();
173                pnlOAuth20Preferences.initFromPreferences();
174                pnlOAuth20Preferences.revalidate();
175            }
176            repaint();
177        }
178    }
179
180    @Override
181    public void propertyChange(PropertyChangeEvent evt) {
182        if (pnlOAuth20Preferences != null) {
183            pnlOAuth20Preferences.propertyChange(evt);
184        }
185        if (OsmApiUrlInputPanel.API_URL_PROP.equals(evt.getPropertyName())) {
186            this.updateAcceptableAuthenticationMethods((String) evt.getNewValue());
187        }
188    }
189
190    /**
191     * Update the acceptable authentications methods
192     * @param apiUrl The API url to check
193     */
194    private void updateAcceptableAuthenticationMethods(String apiUrl) {
195        final String authMethod = OsmApi.getAuthMethod();
196        final boolean defaultApi = JosmUrls.getInstance().getDefaultOsmApiUrl().equals(apiUrl);
197        rbBasicAuthentication.setEnabled(rbBasicAuthentication.isSelected() || "basic".equals(authMethod) || !defaultApi);
198    }
199
200}