001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.oauth;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Component;
007import java.awt.GridBagConstraints;
008import java.awt.GridBagLayout;
009import java.awt.Insets;
010import java.awt.event.ItemEvent;
011import java.awt.event.ItemListener;
012import java.util.Objects;
013import java.util.stream.Collectors;
014import java.util.stream.Stream;
015
016import javax.swing.BorderFactory;
017import javax.swing.JCheckBox;
018import javax.swing.JComponent;
019import javax.swing.JLabel;
020import javax.swing.JOptionPane;
021import javax.swing.event.DocumentEvent;
022import javax.swing.event.DocumentListener;
023
024import org.openstreetmap.josm.data.oauth.IOAuthParameters;
025import org.openstreetmap.josm.data.oauth.OAuth20Parameters;
026import org.openstreetmap.josm.data.oauth.OAuthParameters;
027import org.openstreetmap.josm.data.oauth.OAuthVersion;
028import org.openstreetmap.josm.data.oauth.osm.OsmScopes;
029import org.openstreetmap.josm.gui.HelpAwareOptionPane;
030import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
031import org.openstreetmap.josm.gui.MainApplication;
032import org.openstreetmap.josm.gui.help.HelpUtil;
033import org.openstreetmap.josm.gui.util.GuiHelper;
034import org.openstreetmap.josm.gui.widgets.JosmTextField;
035import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator;
036import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
037import org.openstreetmap.josm.tools.CheckParameterUtil;
038import org.openstreetmap.josm.tools.ImageProvider;
039
040/**
041 * Panel allowing the user to setup advanced OAuth parameters:
042 * <ul>
043 * <li>Client ID</li>
044 * <li>Client secret</li>
045 * <li>Redirect URI</li>
046 * <li>Access token URL</li>
047 * <li>Authorize URL</li>
048 * <li>Access token, which can be pasted instead of authorizing JOSM</li>
049 * </ul>
050 *
051 * @see OAuthParameters
052 * @since 2746
053 */
054public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {
055    /**
056     * Property fired whenever the parameters this panel would return change: the client id was edited,
057     * or "use default settings" was toggled. Listeners re-read {@link #getAdvancedParameters()}.
058     * @since 19627
059     */
060    public static final String PARAMETERS_CHANGED_PROP = AdvancedOAuthPropertiesPanel.class.getName() + ".parametersChanged";
061
062    private final JCheckBox cbUseDefaults = new JCheckBox(tr("Use default settings"));
063    private final JosmTextField tfClientId = new JosmTextField();
064    private final JosmTextField tfClientSecret = new JosmTextField();
065    private final JosmTextField tfRedirectUri = new JosmTextField();
066    private final JosmTextField tfAccessTokenURL = new JosmTextField();
067    private final JosmTextField tfAuthoriseURL = new JosmTextField();
068    private final JLabel lblAccessToken = new JLabel(tr("Access Token:"));
069    private final JosmTextField tfAccessToken = new JosmTextField();
070    private final OAuthVersion oauthVersion;
071    private transient UseDefaultItemListener ilUseDefault;
072    private String apiUrl;
073
074    /**
075     * Constructs a new {@code AdvancedOAuthPropertiesPanel}.
076     * @param oauthVersion The OAuth version to make the panel for
077     */
078    public AdvancedOAuthPropertiesPanel(OAuthVersion oauthVersion) {
079        this.oauthVersion = oauthVersion;
080        build();
081    }
082
083    protected final void build() {
084        setLayout(new GridBagLayout());
085        setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
086        GridBagConstraints gc = new GridBagConstraints();
087
088        gc.anchor = GridBagConstraints.NORTHWEST;
089        gc.fill = GridBagConstraints.HORIZONTAL;
090        gc.weightx = 1.0;
091        gc.insets = new Insets(0, 0, 3, 3);
092        gc.gridwidth = 3;
093        add(cbUseDefaults, gc);
094
095        // -- client id
096        gc.gridy = 1;
097        gc.weightx = 0.0;
098        gc.gridwidth = 1;
099        add(label(tr("Client ID:"), tfClientId), gc);
100
101        gc.gridx = 1;
102        gc.weightx = 1.0;
103        add(tfClientId, gc);
104        SelectAllOnFocusGainedDecorator.decorate(tfClientId);
105
106        // -- client secret
107        gc.gridy++;
108        gc.gridx = 0;
109        gc.weightx = 0.0;
110        add(label(tr("Client Secret:"), tfClientSecret), gc);
111
112        gc.gridx = 1;
113        gc.weightx = 1.0;
114        add(tfClientSecret, gc);
115        SelectAllOnFocusGainedDecorator.decorate(tfClientSecret);
116
117        // -- redirect URI
118        gc.gridy++;
119        gc.gridx = 0;
120        gc.weightx = 0.0;
121        add(label(tr("Redirect URL:"), tfRedirectUri), gc);
122
123        gc.gridx = 1;
124        gc.weightx = 1.0;
125        add(tfRedirectUri, gc);
126        SelectAllOnFocusGainedDecorator.decorate(tfRedirectUri);
127
128        // -- access token URL
129        gc.gridy++;
130        gc.gridx = 0;
131        gc.weightx = 0.0;
132        add(label(tr("Access Token URL:"), tfAccessTokenURL), gc);
133
134        gc.gridx = 1;
135        gc.weightx = 1.0;
136        add(tfAccessTokenURL, gc);
137        SelectAllOnFocusGainedDecorator.decorate(tfAccessTokenURL);
138
139        // -- authorise URL
140        gc.gridy++;
141        gc.gridx = 0;
142        gc.weightx = 0.0;
143        add(label(tr("Authorize URL:"), tfAuthoriseURL), gc);
144
145        gc.gridx = 1;
146        gc.weightx = 1.0;
147        add(tfAuthoriseURL, gc);
148        SelectAllOnFocusGainedDecorator.decorate(tfAuthoriseURL);
149
150        // -- access token: not one of the settings, so it can be pasted whether or not they are the default ones
151        gc.gridy++;
152        gc.gridx = 0;
153        gc.weightx = 0.0;
154        lblAccessToken.setLabelFor(tfAccessToken);
155        add(lblAccessToken, gc);
156
157        gc.gridx = 1;
158        gc.weightx = 1.0;
159        add(tfAccessToken, gc);
160        SelectAllOnFocusGainedDecorator.decorate(tfAccessToken);
161
162        setToolTips();
163
164        ilUseDefault = new UseDefaultItemListener();
165        cbUseDefaults.addItemListener(ilUseDefault);
166        cbUseDefaults.setSelected(true);
167        setChildComponentsVisible(false);
168        cbUseDefaults.addItemListener(e -> fireParametersChanged());
169        tfClientId.getDocument().addDocumentListener(new DocumentListener() {
170            @Override
171            public void insertUpdate(DocumentEvent e) {
172                fireParametersChanged();
173            }
174
175            @Override
176            public void removeUpdate(DocumentEvent e) {
177                fireParametersChanged();
178            }
179
180            @Override
181            public void changedUpdate(DocumentEvent e) {
182                fireParametersChanged();
183            }
184        });
185    }
186
187    /**
188     * Creates the label of a field, which has the tool tip of the field.
189     * @param text the text of the label
190     * @param field the field
191     * @return the label
192     */
193    private static JLabel label(String text, JosmTextField field) {
194        final JLabel label = new JLabel(text);
195        label.setLabelFor(field);
196        return label;
197    }
198
199    /**
200     * Explains each field, for the fields and their labels.
201     */
202    private void setToolTips() {
203        final String scopes = Stream.of(OsmScopes.getJosmScopes()).map(Enum::name).collect(Collectors.joining(", "));
204        cbUseDefaults.setToolTipText(tr("<html>Use the OAuth settings JOSM has built in for this server, or which the server publishes.<br>"
205                + "Untick to enter the settings of an OAuth 2.0 application you registered on the server yourself.</html>"));
206        tfClientId.setToolTipText(tr("<html>The Client ID of an OAuth 2.0 application registered on this server.<br>"
207                + "On an openstreetmap-website server, register one under My Settings &gt; OAuth 2 applications,<br>"
208                + "with the redirect URL below and the permissions {0}.</html>", scopes));
209        tfClientSecret.setToolTipText(tr("<html>Only needed if the application is registered as confidential.<br>"
210                + "The applications JOSM has built in are public clients and have none.</html>"));
211        tfRedirectUri.setToolTipText(tr("<html>Must be exactly the redirect URL registered with the application.<br>"
212                + "JOSM receives the authorization at {0}, by remote control.</html>", "http://127.0.0.1:8111/oauth_authorization"));
213        tfAccessTokenURL.setToolTipText(tr("<html>Where JOSM gets the Access Token from.<br>"
214                + "Taken from the OAuth metadata of the server if it publishes any; on an openstreetmap-website server,<br>"
215                + "this is the address of the website followed by {0}, not the API URL.</html>", "/oauth2/token"));
216        tfAuthoriseURL.setToolTipText(tr("<html>Where the web browser is sent to authorize JOSM.<br>"
217                + "Taken from the OAuth metadata of the server if it publishes any; on an openstreetmap-website server,<br>"
218                + "this is the address of the website followed by {0}, not the API URL.</html>", "/oauth2/authorize"));
219        tfAccessToken.setToolTipText(tr("<html>The Access Token JOSM uses for this server.<br>"
220                + "A token issued outside JOSM can be pasted here instead of authorizing JOSM; it needs the permissions {0}.</html>",
221                scopes));
222        for (Component c : getComponents()) {
223            if (c instanceof JLabel && ((JLabel) c).getLabelFor() instanceof JComponent) {
224                ((JLabel) c).setToolTipText(((JComponent) ((JLabel) c).getLabelFor()).getToolTipText());
225            }
226        }
227    }
228
229    private void fireParametersChanged() {
230        firePropertyChange(PARAMETERS_CHANGED_PROP, null, null);
231    }
232
233    /**
234     * Get the access token as entered in the panel.
235     * @return the access token, without surrounding white space; empty if there is none
236     * @since 19707
237     */
238    public String getAccessToken() {
239        return tfAccessToken.getText().trim();
240    }
241
242    /**
243     * Sets the access token to be displayed.
244     * @param accessToken the access token, or {@code null} if there is none
245     * @since 19707
246     */
247    public void setAccessToken(String accessToken) {
248        tfAccessToken.setText(accessToken);
249    }
250
251    /**
252     * Determines if the panel is set to use the default parameters for the API URL rather than
253     * the values entered in its fields.
254     * @return {@code true} if "use default settings" is selected
255     * @since 19627
256     */
257    public boolean isUseDefaultSettings() {
258        return cbUseDefaults.isSelected();
259    }
260
261    /**
262     * Get the client id as entered in the panel, without falling back to the defaults.
263     * @return the client id field's text, without surrounding white space
264     * @since 19627
265     */
266    public String getEnteredClientId() {
267        return tfClientId.getText().trim();
268    }
269
270    protected boolean hasCustomSettings() {
271        IOAuthParameters params = OAuthParameters.createDefault(apiUrl, this.oauthVersion);
272        return !params.equals(getAdvancedParameters());
273    }
274
275    protected boolean confirmOverwriteCustomSettings() {
276        ButtonSpec[] buttons = {
277                new ButtonSpec(
278                        tr("Continue"),
279                        new ImageProvider("ok"),
280                        tr("Click to reset the OAuth settings to default values"),
281                        null /* no dedicated help topic */
282                ),
283                new ButtonSpec(
284                        tr("Cancel"),
285                        new ImageProvider("cancel"),
286                        tr("Click to abort resetting to the OAuth default values"),
287                        null /* no dedicated help topic */
288                )
289        };
290        return 0 == HelpAwareOptionPane.showOptionDialog(
291                this,
292                tr(
293                        "<html>JOSM is about to reset the OAuth settings to default values.<br>"
294                        + "The current custom settings are not saved.</html>"
295                ),
296                tr("Overwrite custom OAuth settings?"),
297                JOptionPane.WARNING_MESSAGE,
298                null, /* no dedicated icon */
299                buttons,
300                buttons[0],
301                HelpUtil.ht("/Dialog/OAuthAuthorisationWizard")
302        );
303    }
304
305    protected void resetToDefaultSettings() {
306        IOAuthParameters iParams = OAuthParameters.createDefault(apiUrl, this.oauthVersion);
307        GuiHelper.runInEDTAndWaitWithException(() -> {
308                    cbUseDefaults.setSelected(true);
309                    switch (this.oauthVersion) {
310                        case OAuth20:
311                        case OAuth21:
312                            OAuth20Parameters params20 = (OAuth20Parameters) iParams;
313                            tfClientId.setText(params20.getClientId());
314                            tfClientSecret.setText(params20.getClientSecret());
315                            tfAccessTokenURL.setText(params20.getAccessTokenUrl());
316                            tfAuthoriseURL.setText(params20.getAuthorizationUrl());
317                            tfRedirectUri.setText(params20.getRedirectUri());
318                            break;
319                        default:
320                            throw new UnsupportedOperationException("Unsupported OAuth version: " + this.oauthVersion);
321                    }
322                    setChildComponentsVisible(false);
323                });
324    }
325
326    /**
327     * Shows or hides the OAuth parameters: they are shown when the user enters them, that is when the default
328     * settings are not used. The access token is not one of them, and is always shown.
329     * @param visible {@code true} to show the parameters
330     * @since 19707
331     */
332    protected void setChildComponentsVisible(boolean visible) {
333        for (Component c: getComponents()) {
334            if (c == tfAccessToken || c == lblAccessToken) {
335                continue;
336            }
337            if (c instanceof JosmTextField || c instanceof JLabel) {
338                c.setVisible(visible);
339            }
340        }
341        revalidate();
342    }
343
344    /**
345     * Replies the OAuth parameters currently edited in this properties panel.
346     *
347     * @return the OAuth parameters
348     */
349    public IOAuthParameters getAdvancedParameters() {
350        if (cbUseDefaults.isSelected())
351            return OAuthParameters.createDefault(apiUrl, this.oauthVersion);
352        return getDisplayedParameters();
353    }
354
355    /**
356     * Replies the OAuth parameters as currently displayed in this properties panel: the default ones are shown when
357     * "use default settings" is ticked, as far as they are known yet. Unlike {@link #getAdvancedParameters()}, this
358     * never makes a network request, and some of the parameters may be empty. White space around the values, which
359     * is easily copied along with them, is left out: a client secret with a trailing space is refused by the server.
360     *
361     * @return the OAuth parameters
362     * @since 19707
363     */
364    public OAuth20Parameters getDisplayedParameters() {
365        return new OAuth20Parameters(
366                tfClientId.getText().trim(),
367                tfClientSecret.getText().trim(),
368                tfAccessTokenURL.getText().trim(),
369                tfAuthoriseURL.getText().trim(),
370                apiUrl,
371                tfRedirectUri.getText().trim()
372                );
373    }
374
375    /**
376     * Sets the advanced parameters to be displayed
377     *
378     * @param parameters the advanced parameters. Must not be null.
379     * @throws IllegalArgumentException if parameters is null.
380     */
381    public void setAdvancedParameters(IOAuthParameters parameters) {
382        CheckParameterUtil.ensureParameterNotNull(parameters, "parameters");
383        if (parameters.equals(OAuthParameters.createDefault(apiUrl, parameters.getOAuthVersion()))) {
384            cbUseDefaults.setSelected(true);
385            setChildComponentsVisible(false);
386        } else {
387            cbUseDefaults.setSelected(false);
388            setChildComponentsVisible(true);
389            if (parameters instanceof OAuth20Parameters) {
390                OAuth20Parameters parameters20 = (OAuth20Parameters) parameters;
391                tfClientId.setText(parameters20.getClientId());
392                tfClientSecret.setText(parameters20.getClientSecret());
393                tfAccessTokenURL.setText(parameters20.getAccessTokenUrl());
394                tfAuthoriseURL.setText(parameters20.getAuthorizationUrl());
395                tfRedirectUri.setText(parameters20.getRedirectUri());
396            }
397        }
398    }
399
400    /**
401     * Initializes the panel from the values in the preferences <code>preferences</code>.
402     *
403     * @param paramApiUrl the API URL. Must not be null.
404     * @throws IllegalArgumentException if paramApiUrl is null
405     */
406    public void initialize(String paramApiUrl) {
407        CheckParameterUtil.ensureParameterNotNull(paramApiUrl, "paramApiUrl");
408        this.apiUrl = paramApiUrl;
409        // "use default settings" is a setting of each server
410        boolean useDefault = OAuthParameters.isUseDefault(paramApiUrl);
411        ilUseDefault.setEnabled(false);
412        cbUseDefaults.setSelected(useDefault);
413        setChildComponentsVisible(!useDefault);
414        MainApplication.worker.execute(() -> {
415            if (useDefault) {
416                this.resetToDefaultSettings();
417            } else {
418                // createFromApiUrl may make a network request
419                final IOAuthParameters parameters = OAuthParameters.createFromApiUrl(paramApiUrl, this.oauthVersion);
420                GuiHelper.runInEDT(() -> setAdvancedParameters(parameters));
421            }
422            GuiHelper.runInEDT(() -> ilUseDefault.setEnabled(true));
423        });
424    }
425
426    /**
427     * Remembers the current values in the preferences <code>pref</code>: whether the server uses the default
428     * settings, and the settings entered if not. Settings entered earlier are kept when the default settings are
429     * used, so that they are there again when they are needed again.
430     */
431    public void rememberPreferences() {
432        if (apiUrl == null) {
433            return; // not initialized
434        }
435        OAuthParameters.setUseDefault(apiUrl, cbUseDefaults.isSelected());
436        if (!cbUseDefaults.isSelected()) {
437            getAdvancedParameters().rememberPreferences();
438        }
439    }
440
441    class UseDefaultItemListener implements ItemListener {
442        private boolean enabled;
443
444        @Override
445        public void itemStateChanged(ItemEvent e) {
446            if (!enabled) return;
447            switch (e.getStateChange()) {
448            case ItemEvent.SELECTED:
449                if (hasCustomSettings() && !confirmOverwriteCustomSettings()) {
450                    cbUseDefaults.setSelected(false);
451                    return;
452                }
453                MainApplication.worker.execute(AdvancedOAuthPropertiesPanel.this::resetToDefaultSettings);
454                break;
455            case ItemEvent.DESELECTED:
456                setChildComponentsVisible(true);
457                break;
458            default: // Do nothing
459            }
460        }
461
462        public void setEnabled(boolean enabled) {
463            this.enabled = enabled;
464        }
465    }
466
467    /**
468     * Sets the URL of the OSM API for which this panel is currently displaying OAuth properties.
469     *
470     * @param apiUrl the api URL
471     * @since 5422
472     */
473    public void setApiUrl(String apiUrl) {
474        if (this.apiUrl != null && apiUrl != null
475                && !Objects.equals(OAuthParameters.getHost(this.apiUrl), OAuthParameters.getHost(apiUrl))) {
476            // another server, with settings of its own
477            initialize(apiUrl);
478            return;
479        }
480        this.apiUrl = apiUrl;
481        if (cbUseDefaults.isSelected()) {
482            MainApplication.worker.execute(this::resetToDefaultSettings);
483        }
484    }
485}