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.Color;
008import java.awt.Component;
009import java.awt.FlowLayout;
010import java.awt.Font;
011import java.awt.GridBagConstraints;
012import java.awt.GridBagLayout;
013import java.awt.Insets;
014import java.awt.event.ActionEvent;
015import java.beans.PropertyChangeEvent;
016import java.beans.PropertyChangeListener;
017import java.net.URI;
018import java.net.URISyntaxException;
019import java.util.Arrays;
020
021import javax.swing.AbstractAction;
022import javax.swing.BorderFactory;
023import javax.swing.JButton;
024import javax.swing.JCheckBox;
025import javax.swing.JOptionPane;
026import javax.swing.JPanel;
027
028import org.openstreetmap.josm.data.oauth.IOAuthParameters;
029import org.openstreetmap.josm.data.oauth.IOAuthToken;
030import org.openstreetmap.josm.data.oauth.OAuth20Authorization;
031import org.openstreetmap.josm.data.oauth.OAuth20Token;
032import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
033import org.openstreetmap.josm.data.oauth.OAuthParameters;
034import org.openstreetmap.josm.data.oauth.OAuthVersion;
035import org.openstreetmap.josm.data.oauth.osm.OsmScopes;
036import org.openstreetmap.josm.data.validation.routines.DomainValidator;
037import org.openstreetmap.josm.gui.MainApplication;
038import org.openstreetmap.josm.gui.oauth.AdvancedOAuthPropertiesPanel;
039import org.openstreetmap.josm.gui.oauth.TestAccessTokenTask;
040import org.openstreetmap.josm.gui.util.GuiHelper;
041import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
042import org.openstreetmap.josm.io.OsmApi;
043import org.openstreetmap.josm.io.auth.CredentialsManager;
044import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
045import org.openstreetmap.josm.tools.GBC;
046import org.openstreetmap.josm.tools.ImageProvider;
047import org.openstreetmap.josm.tools.Logging;
048import org.openstreetmap.josm.tools.Utils;
049
050/**
051 * The preferences panel for OAuth 2.0: whether JOSM has an Access Token for the server, a button to authorize JOSM
052 * in the web browser, and the advanced OAuth parameters, which include the Access Token itself so that a token
053 * obtained outside JOSM can be pasted instead.
054 * @since 2745
055 */
056public class OAuthAuthenticationPreferencesPanel extends JPanel implements PropertyChangeListener {
057    private final JCheckBox cbUseForAllRequests = new JCheckBox();
058    private final JCheckBox cbSaveToPreferences = new JCheckBox(tr("Save to preferences"));
059    private final JPanel pnlAuthorisationMessage = new JPanel(new BorderLayout());
060    private final NotYetAuthorisedPanel pnlNotYetAuthorised;
061    private final AdvancedOAuthPropertiesPanel pnlAdvancedProperties;
062    private final AlreadyAuthorisedPanel pnlAlreadyAuthorised;
063    private final OAuthVersion oAuthVersion;
064    private String apiUrl;
065
066    /**
067     * Create the panel.
068     * @param oAuthVersion The OAuth version to use
069     */
070    public OAuthAuthenticationPreferencesPanel(OAuthVersion oAuthVersion) {
071        this.oAuthVersion = oAuthVersion;
072        // These must come after we set the oauth version
073        this.pnlAdvancedProperties = new AdvancedOAuthPropertiesPanel(this.oAuthVersion);
074        this.pnlNotYetAuthorised = new NotYetAuthorisedPanel();
075        this.pnlAlreadyAuthorised = new AlreadyAuthorisedPanel();
076        build();
077    }
078
079    /**
080     * Builds the panel for entering the advanced OAuth parameters
081     *
082     * @return panel with advanced settings
083     */
084    protected JPanel buildAdvancedPropertiesPanel() {
085        JPanel pnl = new JPanel(new GridBagLayout());
086
087        cbUseForAllRequests.setText(tr("Use OAuth for all requests to {0}", OsmApi.getOsmApi().getServerUrl()));
088        cbUseForAllRequests.setToolTipText(tr("For user-based bandwidth limit instead of IP-based one"));
089        pnl.add(cbUseForAllRequests, GBC.eol().fill(GBC.HORIZONTAL));
090
091        pnl.add(pnlAdvancedProperties, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 3, 0, 0));
092        pnlAdvancedProperties.initialize(OsmApi.getOsmApi().getServerUrl());
093        pnlAdvancedProperties.setBorder(
094                BorderFactory.createCompoundBorder(
095                        BorderFactory.createLineBorder(Color.GRAY, 1),
096                        BorderFactory.createEmptyBorder(3, 3, 3, 3)
097                )
098        );
099        pnlAdvancedProperties.addPropertyChangeListener(this);
100        return pnl;
101    }
102
103    /**
104     * Re-evaluate whether the "Authorize now" buttons can be enabled, after the API URL or the
105     * advanced OAuth parameters changed.
106     */
107    private void updateAuthoriseNowActions() {
108        for (JPanel panel : Arrays.asList(this.pnlNotYetAuthorised, this.pnlAlreadyAuthorised.pnlButtons)) {
109            for (Component component : panel.getComponents()) {
110                if (component instanceof JButton && ((JButton) component).getAction() instanceof AuthoriseNowAction) {
111                    ((AuthoriseNowAction) ((JButton) component).getAction()).updateEnabledState();
112                }
113            }
114        }
115    }
116
117    /**
118     * builds the UI
119     */
120    protected final void build() {
121        setLayout(new GridBagLayout());
122        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
123        // the panel for the OAuth parameters. pnlAuthorisationMessage is an
124        // empty panel. It is going to be filled later, depending on the
125        // current OAuth state in JOSM.
126        add(pnlAuthorisationMessage, GBC.eol().fill(GridBagConstraints.BOTH).anchor(GridBagConstraints.NORTHWEST)
127                .weight(1, 1).insets(0, 10, 0, 0));
128        // the panel with the advanced options
129        add(buildAdvancedPropertiesPanel(), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
130    }
131
132    protected void refreshView() {
133        pnlAuthorisationMessage.removeAll();
134        pnlAdvancedProperties.setAccessToken(getBearerToken());
135        if (OAuthAccessTokenHolder.getInstance().getAccessToken(this.apiUrl, this.oAuthVersion) != null) {
136            pnlAuthorisationMessage.add(pnlAlreadyAuthorised, BorderLayout.CENTER);
137            pnlAlreadyAuthorised.refreshView();
138            pnlAlreadyAuthorised.revalidate();
139        } else {
140            pnlAuthorisationMessage.add(pnlNotYetAuthorised, BorderLayout.CENTER);
141            pnlNotYetAuthorised.revalidate();
142        }
143        repaint();
144    }
145
146    /**
147     * Get the bearer token JOSM currently has for the API.
148     * @return the bearer token, or {@code null} if there is none
149     */
150    private String getBearerToken() {
151        if (apiUrl == null) {
152            return null;
153        }
154        final IOAuthToken token = OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, oAuthVersion);
155        return token instanceof OAuth20Token ? ((OAuth20Token) token).getBearerToken() : null;
156    }
157
158    /**
159     * Determines whether the user changed the access token in the advanced OAuth parameters.
160     * @return {@code true} if the access token entered differs from the one JOSM has
161     */
162    private boolean isAccessTokenEdited() {
163        final String current = getBearerToken();
164        return apiUrl != null && !pnlAdvancedProperties.getAccessToken().equals(current == null ? "" : current);
165    }
166
167    /**
168     * Get the access token entered in the advanced OAuth parameters: a token issued outside JOSM, pasted instead of
169     * authorizing JOSM. It works with nothing else, so it is a way to authenticate when authorizing JOSM is not
170     * possible.
171     * @return the token, or {@code null} if none is entered
172     */
173    private IOAuthToken getEnteredAccessToken() {
174        final String entered = pnlAdvancedProperties.getAccessToken();
175        return entered.isEmpty() ? null : OAuth20Token.fromAccessToken(pnlAdvancedProperties.getDisplayedParameters(), entered);
176    }
177
178    /**
179     * Takes over the access token entered in the advanced OAuth parameters, or removes the token if the field was
180     * cleared. This is done when the preferences are saved, so that cancelling them leaves the token as it was. A
181     * token which was not changed is left as it is, so that for example its refresh token is kept.
182     */
183    private void applyEnteredAccessToken() {
184        if (isAccessTokenEdited()) {
185            OAuthAccessTokenHolder.getInstance().setAccessToken(apiUrl, getEnteredAccessToken());
186        }
187    }
188
189    /**
190     * Sets the URL of the OSM API for which this panel is currently displaying OAuth properties.
191     *
192     * @param apiUrl the api URL
193     */
194    public void setApiUrl(String apiUrl) {
195        this.apiUrl = apiUrl;
196        pnlAdvancedProperties.setApiUrl(apiUrl);
197        updateAuthoriseNowActions();
198    }
199
200    /**
201     * Initializes the panel from preferences
202     */
203    public void initFromPreferences() {
204        setApiUrl(OsmApi.getOsmApi().getServerUrl().trim());
205        cbUseForAllRequests.setSelected(OsmApi.USE_OAUTH_FOR_ALL_REQUESTS.get());
206        refreshView();
207    }
208
209    /**
210     * Saves the current values to preferences
211     */
212    public void saveToPreferences() {
213        applyEnteredAccessToken();
214        OAuthAccessTokenHolder.getInstance().setSaveToPreferences(cbSaveToPreferences.isSelected());
215        OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
216        OsmApi.USE_OAUTH_FOR_ALL_REQUESTS.put(cbUseForAllRequests.isSelected());
217        pnlAdvancedProperties.rememberPreferences();
218    }
219
220    /**
221     * The preferences panel displayed if there is currently no Access Token available.
222     * This means that the user didn't run through the OAuth authorisation procedure yet.
223     *
224     */
225    private class NotYetAuthorisedPanel extends JPanel {
226        /**
227         * Constructs a new {@code NotYetAuthorisedPanel}.
228         */
229        NotYetAuthorisedPanel() {
230            build();
231        }
232
233        protected void build() {
234            setLayout(new GridBagLayout());
235
236            // A message explaining that the user isn't authorised yet
237            JMultilineLabel lbl = new JMultilineLabel(
238                    tr("You do not have an Access Token yet to access the OSM server using OAuth. Please authorize first."));
239            add(lbl, GBC.eol().anchor(GBC.NORTHWEST).fill(GBC.HORIZONTAL));
240            lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
241
242            // Action for authorising now
243            add(new JButton(new AuthoriseNowAction()), GBC.eol());
244
245            // filler - grab remaining space
246            add(new JPanel(), GBC.std().fill(GBC.BOTH));
247        }
248    }
249
250    /**
251     * The preferences panel displayed if there is currently an AccessToken available.
252     *
253     */
254    private class AlreadyAuthorisedPanel extends JPanel {
255        private final JPanel pnlButtons = new JPanel(new FlowLayout(FlowLayout.LEFT));
256
257        /**
258         * Constructs a new {@code AlreadyAuthorisedPanel}.
259         */
260        AlreadyAuthorisedPanel() {
261            build();
262            refreshView();
263        }
264
265        protected void build() {
266            setLayout(new GridBagLayout());
267            GridBagConstraints gc = new GridBagConstraints();
268            gc.anchor = GridBagConstraints.NORTHWEST;
269            gc.insets = new Insets(0, 0, 3, 3);
270            gc.fill = GridBagConstraints.HORIZONTAL;
271            gc.weightx = 1.0;
272            gc.gridwidth = 2;
273            JMultilineLabel lbl = new JMultilineLabel(tr("You already have an Access Token to access the OSM server using OAuth."));
274            add(lbl, gc);
275            lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
276
277            // -- save to preferences; the Access Token itself is shown with the advanced OAuth parameters
278            gc.gridy = 1;
279            gc.gridx = 0;
280            gc.gridwidth = 2;
281            gc.weightx = 1.0;
282            add(cbSaveToPreferences, gc);
283            cbSaveToPreferences.setSelected(OAuthAccessTokenHolder.getInstance().isSaveToPreferences());
284
285            // -- action buttons
286            pnlButtons.add(new JButton(new RenewAuthorisationAction()));
287            pnlButtons.add(new JButton(new TestAuthorisationAction()));
288            pnlButtons.add(new JButton(new RemoveAuthorisationAction()));
289            gc.gridy = 2;
290            gc.gridx = 0;
291            gc.gridwidth = 2;
292            gc.weightx = 1.0;
293            add(pnlButtons, gc);
294
295            // filler - grab the remaining space
296            gc.gridy = 3;
297            gc.fill = GridBagConstraints.BOTH;
298            gc.weightx = 1.0;
299            gc.weighty = 1.0;
300            add(new JPanel(), gc);
301        }
302
303        protected final void refreshView() {
304            cbSaveToPreferences.setSelected(OAuthAccessTokenHolder.getInstance().isSaveToPreferences());
305        }
306    }
307
308    /**
309     * Action to authorise the current user: JOSM is authorized in the web browser, with the OAuth parameters
310     * currently shown, and receives an Access Token by remote control.
311     */
312    private class AuthoriseNowAction extends AbstractAction {
313        /** Counts the updates of the enabled state, so that the result of an earlier one cannot override a later one */
314        private int updates;
315
316        AuthoriseNowAction() {
317            putValue(NAME, tr("Authorize now"));
318            putValue(SHORT_DESCRIPTION, tr("Authorize JOSM in the web browser to access the OSM server on your behalf, "
319                    + "and get an Access Token"));
320            new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
321            updateEnabledState();
322        }
323
324        void updateEnabledState() {
325            final int update = ++updates;
326            if (!pnlAdvancedProperties.isUseDefaultSettings()) {
327                // The user supplied the parameters - the client id of an OAuth application they
328                // registered on the server themselves. Authorization uses exactly these parameters
329                // when the button is pressed, so they decide whether it can be pressed.
330                this.setEnabled(!Utils.isEmpty(pnlAdvancedProperties.getEnteredClientId()));
331            } else if (Utils.isValidUrl(apiUrl)) {
332                final URI apiURI;
333                try {
334                    apiURI = new URI(apiUrl);
335                } catch (URISyntaxException e) {
336                    Logging.trace(e);
337                    return;
338                }
339                if (DomainValidator.getInstance().isValid(apiURI.getHost())) {
340                    // We want to avoid trying to make connection with an invalid URL. These are the parameters
341                    // authorization uses, see AdvancedOAuthPropertiesPanel.getAdvancedParameters().
342                    final String currentApiUrl = apiUrl;
343                    MainApplication.worker.execute(() -> {
344                        final String clientId = OAuthParameters.createDefault(currentApiUrl, oAuthVersion).getClientId();
345                        GuiHelper.runInEDT(() -> {
346                            if (update == updates) {
347                                this.setEnabled(!Utils.isEmpty(clientId));
348                            }
349                        });
350                    });
351                }
352            }
353        }
354
355        @Override
356        public void actionPerformed(ActionEvent arg0) {
357            final String currentApiUrl = apiUrl;
358            final IOAuthParameters parameters = pnlAdvancedProperties.getAdvancedParameters();
359            // the token is received by remote control, which is started for the time it takes if it is not running
360            final boolean remoteControlIsRunning = Boolean.TRUE.equals(RemoteControl.PROP_REMOTECONTROL_ENABLED.get());
361            if (!remoteControlIsRunning) {
362                RemoteControl.start();
363            }
364            new OAuth20Authorization().authorize(parameters, token -> {
365                if (!remoteControlIsRunning) {
366                    RemoteControl.stop();
367                }
368                // a failed attempt, e.g. at a new token, leaves the token JOSM has as it is
369                token.ifPresent(t -> {
370                    OAuthAccessTokenHolder.getInstance().setAccessToken(currentApiUrl, t);
371                    OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
372                });
373                GuiHelper.runInEDT(() -> {
374                    if (!token.isPresent()) {
375                        JOptionPane.showMessageDialog(OAuthAuthenticationPreferencesPanel.this,
376                                tr("Authentication failed, please check browser for details."),
377                                tr("OAuth Authentication Failed"),
378                                JOptionPane.ERROR_MESSAGE);
379                    }
380                    refreshView();
381                });
382            }, OsmScopes.getJosmScopes());
383        }
384    }
385
386    /**
387     * Remove the OAuth authorization token
388     */
389    private class RemoveAuthorisationAction extends AbstractAction {
390        RemoveAuthorisationAction() {
391            putValue(NAME, tr("Remove token"));
392            putValue(SHORT_DESCRIPTION, tr("Remove token from JOSM. This does not revoke the token."));
393            new ImageProvider("cancel").getResource().attachImageIcon(this);
394        }
395
396        @Override
397        public void actionPerformed(ActionEvent e) {
398            OAuthAccessTokenHolder.getInstance().setAccessToken(apiUrl, null);
399            OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
400            refreshView();
401        }
402    }
403
404    /**
405     * Authorizes JOSM again, to generate a new Access Token
406     */
407    private class RenewAuthorisationAction extends AuthoriseNowAction {
408        /**
409         * Constructs a new {@code RenewAuthorisationAction}.
410         */
411        RenewAuthorisationAction() {
412            putValue(NAME, tr("New Access Token"));
413            putValue(SHORT_DESCRIPTION, tr("Click to step through the OAuth authorization process and generate a new Access Token"));
414        }
415    }
416
417    /**
418     * Runs a test whether we can access the OSM server with the current Access Token
419     */
420    private class TestAuthorisationAction extends AbstractAction {
421        /**
422         * Constructs a new {@code TestAuthorisationAction}.
423         */
424        TestAuthorisationAction() {
425            putValue(NAME, tr("Test Access Token"));
426            putValue(SHORT_DESCRIPTION, tr("Click test access to the OSM server with the current access token"));
427            new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
428        }
429
430        @Override
431        public void actionPerformed(ActionEvent evt) {
432            // a token pasted but not saved yet is what the user wants to know about, and none if the field was cleared
433            final IOAuthToken token = isAccessTokenEdited() ? getEnteredAccessToken()
434                    : OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, oAuthVersion);
435            if (token == null) {
436                JOptionPane.showMessageDialog(OAuthAuthenticationPreferencesPanel.this,
437                        tr("There is no Access Token to test."), tr("Test Access Token"), JOptionPane.INFORMATION_MESSAGE);
438                return;
439            }
440            TestAccessTokenTask task = new TestAccessTokenTask(
441                    OAuthAuthenticationPreferencesPanel.this,
442                    apiUrl,
443                    token
444            );
445            MainApplication.worker.submit(task);
446        }
447    }
448
449    @Override
450    public void propertyChange(PropertyChangeEvent evt) {
451        if (AdvancedOAuthPropertiesPanel.PARAMETERS_CHANGED_PROP.equals(evt.getPropertyName())) {
452            updateAuthoriseNowActions();
453
454        } else if (OsmApiUrlInputPanel.API_URL_PROP.equals(evt.getPropertyName())) {
455            setApiUrl((String) evt.getNewValue());
456            refreshView();
457        }
458    }
459}