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.BorderLayout;
007import java.awt.Component;
008import java.awt.FlowLayout;
009import java.awt.Font;
010import java.awt.GridBagConstraints;
011import java.awt.GridBagLayout;
012import java.awt.Insets;
013import java.awt.event.ActionEvent;
014import java.io.IOException;
015import java.util.concurrent.Executor;
016
017import javax.swing.AbstractAction;
018import javax.swing.BorderFactory;
019import javax.swing.JButton;
020import javax.swing.JLabel;
021import javax.swing.JOptionPane;
022import javax.swing.JPanel;
023import javax.swing.JTabbedPane;
024import javax.swing.text.html.HTMLEditorKit;
025
026import org.openstreetmap.josm.data.oauth.IOAuthToken;
027import org.openstreetmap.josm.data.oauth.OAuthVersion;
028import org.openstreetmap.josm.gui.HelpAwareOptionPane;
029import org.openstreetmap.josm.gui.PleaseWaitRunnable;
030import org.openstreetmap.josm.gui.help.HelpUtil;
031import org.openstreetmap.josm.gui.util.GuiHelper;
032import org.openstreetmap.josm.gui.widgets.HtmlPanel;
033import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
034import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
035import org.openstreetmap.josm.io.OsmTransferException;
036import org.openstreetmap.josm.tools.ImageProvider;
037import org.openstreetmap.josm.tools.Logging;
038import org.xml.sax.SAXException;
039
040/**
041 * This is a UI which supports a JOSM user to get an OAuth Access Token in a fully
042 * automatic process.
043 *
044 * @since 2746
045 */
046public class FullyAutomaticAuthorizationUI extends AbstractAuthorizationUI {
047    private final AccessTokenInfoPanel pnlAccessTokenInfo = new AccessTokenInfoPanel();
048    private OsmPrivilegesPanel pnlOsmPrivileges;
049    private JPanel pnlPropertiesPanel;
050    private JPanel pnlActionButtonsPanel;
051    private JPanel pnlResult;
052    private final transient Executor executor;
053
054    /**
055     * Builds the panel with the three privileges the user can grant JOSM
056     *
057     * @return constructed panel for the privileges
058     */
059    protected VerticallyScrollablePanel buildGrantsPanel() {
060        pnlOsmPrivileges = new OsmPrivilegesPanel();
061        return pnlOsmPrivileges;
062    }
063
064    /**
065     * Builds the panel for entering the username and password
066     *
067     * @return constructed panel for the credentials
068     */
069    protected VerticallyScrollablePanel buildUserNamePasswordPanel() {
070        VerticallyScrollablePanel pnl = new VerticallyScrollablePanel(new GridBagLayout());
071        GridBagConstraints gc = new GridBagConstraints();
072        pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
073
074        gc.anchor = GridBagConstraints.NORTHWEST;
075        gc.fill = GridBagConstraints.HORIZONTAL;
076        gc.weightx = 1.0;
077        gc.gridwidth = 2;
078        HtmlPanel pnlMessage = new HtmlPanel();
079        HTMLEditorKit kit = (HTMLEditorKit) pnlMessage.getEditorPane().getEditorKit();
080        kit.getStyleSheet().addRule(
081                ".warning-body {background-color:#DDFFDD; padding: 10pt; " +
082                "border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}");
083        kit.getStyleSheet().addRule("ol {margin-left: 1cm}");
084        pnlMessage.setText("<html><body><p class=\"warning-body\">"
085                + tr("Please enter your OSM user name and password. The password will <strong>not</strong> be saved "
086                        + "in clear text in the JOSM preferences and it will be submitted to the OSM server <strong>only once</strong>. "
087                        + "Subsequent data upload requests don''t use your password any more.").replace(". ", ".<br>")
088                        + "</p>"
089                        + "</body></html>");
090        pnl.add(pnlMessage, gc);
091
092        // the user name input field
093        gc.gridy = 1;
094        gc.gridwidth = 1;
095        gc.anchor = GridBagConstraints.NORTHWEST;
096        gc.fill = GridBagConstraints.HORIZONTAL;
097        gc.weightx = 0.0;
098        gc.insets = new Insets(0, 0, 3, 3);
099        pnl.add(new JLabel(tr("Username: ")), gc);
100
101        // the password input field
102        gc.anchor = GridBagConstraints.NORTHWEST;
103        gc.fill = GridBagConstraints.HORIZONTAL;
104        gc.gridy = 2;
105        gc.gridx = 0;
106        gc.weightx = 0.0;
107        pnl.add(new JLabel(tr("Password:")), gc);
108
109        // filler - grab remaining space
110        gc.gridx = 1;
111        gc.gridy = 4;
112        gc.gridwidth = 2;
113        gc.fill = GridBagConstraints.BOTH;
114        gc.weightx = 1.0;
115        gc.weighty = 1.0;
116        pnl.add(new JPanel(), gc);
117
118        return pnl;
119    }
120
121    protected JPanel buildPropertiesPanel() {
122        JPanel pnl = new JPanel(new BorderLayout());
123
124        JTabbedPane tpProperties = new JTabbedPane();
125        tpProperties.add(buildUserNamePasswordPanel().getVerticalScrollPane());
126        tpProperties.add(buildGrantsPanel().getVerticalScrollPane());
127        tpProperties.add(getAdvancedPropertiesPanel().getVerticalScrollPane());
128        tpProperties.setTitleAt(0, tr("Basic"));
129        tpProperties.setTitleAt(1, tr("Granted rights"));
130        tpProperties.setTitleAt(2, tr("Advanced OAuth properties"));
131
132        pnl.add(tpProperties, BorderLayout.CENTER);
133        return pnl;
134    }
135
136    /**
137     * Builds the panel with the action button  for starting the authorisation
138     *
139     * @return constructed button panel
140     */
141    protected JPanel buildActionButtonPanel() {
142        JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
143
144        RunAuthorisationAction runAuthorisationAction = new RunAuthorisationAction();
145        pnl.add(new JButton(runAuthorisationAction));
146        return pnl;
147    }
148
149    /**
150     * Builds the panel which displays the generated Access Token.
151     *
152     * @return constructed panel for the results
153     */
154    protected JPanel buildResultsPanel() {
155        JPanel pnl = new JPanel(new GridBagLayout());
156        GridBagConstraints gc = new GridBagConstraints();
157        pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
158
159        // the message panel
160        gc.anchor = GridBagConstraints.NORTHWEST;
161        gc.fill = GridBagConstraints.HORIZONTAL;
162        gc.weightx = 1.0;
163        JMultilineLabel msg = new JMultilineLabel("");
164        msg.setFont(msg.getFont().deriveFont(Font.PLAIN));
165        String lbl = tr("Accept Access Token");
166        msg.setText(tr("<html>"
167                + "You have successfully retrieved an OAuth Access Token from the OSM website. "
168                + "Click on <strong>{0}</strong> to accept the token. JOSM will use it in "
169                + "subsequent requests to gain access to the OSM API."
170                + "</html>", lbl));
171        pnl.add(msg, gc);
172
173        // infos about the access token
174        gc.gridy = 1;
175        gc.insets = new Insets(5, 0, 0, 0);
176        pnl.add(pnlAccessTokenInfo, gc);
177
178        // the actions
179        JPanel pnl1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
180        pnl1.add(new JButton(new BackAction()));
181        pnl1.add(new JButton(new TestAccessTokenAction()));
182        gc.gridy = 2;
183        pnl.add(pnl1, gc);
184
185        // filler - grab the remaining space
186        gc.gridy = 3;
187        gc.fill = GridBagConstraints.BOTH;
188        gc.weightx = 1.0;
189        gc.weighty = 1.0;
190        pnl.add(new JPanel(), gc);
191
192        return pnl;
193    }
194
195    protected final void build() {
196        setLayout(new BorderLayout());
197        pnlPropertiesPanel = buildPropertiesPanel();
198        pnlActionButtonsPanel = buildActionButtonPanel();
199        pnlResult = buildResultsPanel();
200
201        prepareUIForEnteringRequest();
202    }
203
204    /**
205     * Prepares the UI for the first step in the automatic process: entering the authentication
206     * and authorisation parameters.
207     *
208     */
209    protected void prepareUIForEnteringRequest() {
210        removeAll();
211        add(pnlPropertiesPanel, BorderLayout.CENTER);
212        add(pnlActionButtonsPanel, BorderLayout.SOUTH);
213        pnlPropertiesPanel.revalidate();
214        pnlActionButtonsPanel.revalidate();
215        validate();
216        repaint();
217
218        setAccessToken(null);
219    }
220
221    /**
222     * Prepares the UI for the second step in the automatic process: displaying the access token
223     *
224     */
225    protected void prepareUIForResultDisplay() {
226        removeAll();
227        add(pnlResult, BorderLayout.CENTER);
228        validate();
229        repaint();
230    }
231
232    /**
233     * Constructs a new {@code FullyAutomaticAuthorizationUI} for the given API URL.
234     * @param apiUrl The OSM API URL
235     * @param executor the executor used for running the HTTP requests for the authorization
236     * @param oAuthVersion The OAuth version to use for this UI
237     * @since 18991
238     */
239    public FullyAutomaticAuthorizationUI(String apiUrl, Executor executor, OAuthVersion oAuthVersion) {
240        super(apiUrl, oAuthVersion);
241        this.executor = executor;
242        build();
243    }
244
245    @Override
246    public boolean isSaveAccessTokenToPreferences() {
247        return pnlAccessTokenInfo.isSaveToPreferences();
248    }
249
250    @Override
251    protected void setAccessToken(IOAuthToken accessToken) {
252        super.setAccessToken(accessToken);
253        pnlAccessTokenInfo.setAccessToken(accessToken);
254    }
255
256    /**
257     * Starts the authorisation process
258     */
259    class RunAuthorisationAction extends AbstractAction {
260        RunAuthorisationAction() {
261            putValue(NAME, tr("Authorize now"));
262            new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
263            putValue(SHORT_DESCRIPTION, tr("Click to redirect you to the authorization form on the JOSM web site"));
264        }
265
266        @Override
267        public void actionPerformed(ActionEvent evt) {
268            executor.execute(new FullyAutomaticAuthorisationTask(FullyAutomaticAuthorizationUI.this));
269        }
270    }
271
272    /**
273     * Action to go back to step 1 in the process
274     */
275    class BackAction extends AbstractAction {
276        BackAction() {
277            putValue(NAME, tr("Back"));
278            putValue(SHORT_DESCRIPTION, tr("Run the automatic authorization steps again"));
279            new ImageProvider("dialogs", "previous").getResource().attachImageIcon(this);
280        }
281
282        @Override
283        public void actionPerformed(ActionEvent arg0) {
284            prepareUIForEnteringRequest();
285        }
286    }
287
288    /**
289     * Action to test an access token.
290     */
291    class TestAccessTokenAction extends AbstractAction {
292        TestAccessTokenAction() {
293            putValue(NAME, tr("Test Access Token"));
294            new ImageProvider("logo").getResource().attachImageIcon(this);
295        }
296
297        @Override
298        public void actionPerformed(ActionEvent arg0) {
299            executor.execute(new TestAccessTokenTask(
300                    FullyAutomaticAuthorizationUI.this,
301                    getApiUrl(),
302                    getAccessToken()
303            ));
304        }
305    }
306
307    class FullyAutomaticAuthorisationTask extends PleaseWaitRunnable {
308        private boolean canceled;
309
310        FullyAutomaticAuthorisationTask(Component parent) {
311            super(parent, tr("Authorize JOSM to access the OSM API"), false /* don't ignore exceptions */);
312        }
313
314        @Override
315        protected void cancel() {
316            canceled = true;
317        }
318
319        @Override
320        protected void finish() {
321            // Do nothing
322        }
323
324        protected void alertAuthorisationFailed() {
325            HelpAwareOptionPane.showOptionDialog(
326                    FullyAutomaticAuthorizationUI.this,
327                    tr("<html>"
328                            + "The automatic process for retrieving an OAuth Access Token<br>"
329                            + "from the OSM server failed.<br><br>"
330                            + "Please try again or choose another kind of authorization process,<br>"
331                            + "i.e. semi-automatic or manual authorization."
332                            +"</html>"),
333                    tr("OAuth authorization failed"),
334                    JOptionPane.ERROR_MESSAGE,
335                    HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#FullyAutomaticProcessFailed")
336            );
337        }
338
339        protected void alertInvalidLoginUrl() {
340            HelpAwareOptionPane.showOptionDialog(
341                    FullyAutomaticAuthorizationUI.this,
342                    tr("<html>"
343                            + "The automatic process for retrieving an OAuth Access Token<br>"
344                            + "from the OSM server failed because JOSM was not able to build<br>"
345                            + "a valid login URL from the OAuth Authorize Endpoint URL ''{0}''.<br><br>"
346                            + "Please check your advanced setting and try again."
347                            + "</html>",
348                            getAdvancedPropertiesPanel().getAdvancedParameters().getAuthorizationUrl()),
349                    tr("OAuth authorization failed"),
350                    JOptionPane.ERROR_MESSAGE,
351                    HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#FullyAutomaticProcessFailed")
352            );
353        }
354
355        protected void handleException(final OsmOAuthAuthorizationException e) {
356            Logging.error(e);
357            GuiHelper.runInEDT(this::alertAuthorisationFailed);
358        }
359
360        @Override
361        protected void realRun() throws SAXException, IOException, OsmTransferException {
362            getProgressMonitor().setTicksCount(2);
363            OAuthAuthorizationWizard.authorize(true, token -> {
364                if (!canceled) {
365                    getProgressMonitor().worked(1);
366                    GuiHelper.runInEDT(() -> {
367                        prepareUIForResultDisplay();
368                        setAccessToken(token.orElse(null));
369                    });
370                }
371            }, getApiUrl(), getOAuthVersion(), getOAuthParameters());
372            getProgressMonitor().worked(1);
373        }
374    }
375}