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