source: josm/trunk/src/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUI.java@ 12620

Last change on this file since 12620 was 12620, checked in by Don-vip, 7 years ago

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

  • Property svn:eol-style set to native
File size: 19.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.oauth;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.BorderLayout;
7import java.awt.Component;
8import java.awt.FlowLayout;
9import java.awt.Font;
10import java.awt.GridBagConstraints;
11import java.awt.GridBagLayout;
12import java.awt.Insets;
13import java.awt.event.ActionEvent;
14import java.io.IOException;
15import java.net.Authenticator.RequestorType;
16import java.net.PasswordAuthentication;
17import java.util.concurrent.Executor;
18
19import javax.swing.AbstractAction;
20import javax.swing.BorderFactory;
21import javax.swing.JButton;
22import javax.swing.JLabel;
23import javax.swing.JOptionPane;
24import javax.swing.JPanel;
25import javax.swing.JTabbedPane;
26import javax.swing.event.DocumentEvent;
27import javax.swing.event.DocumentListener;
28import javax.swing.text.JTextComponent;
29import javax.swing.text.html.HTMLEditorKit;
30
31import org.openstreetmap.josm.data.Preferences;
32import org.openstreetmap.josm.data.oauth.OAuthToken;
33import org.openstreetmap.josm.gui.HelpAwareOptionPane;
34import org.openstreetmap.josm.gui.PleaseWaitRunnable;
35import org.openstreetmap.josm.gui.help.HelpUtil;
36import org.openstreetmap.josm.gui.preferences.server.UserNameValidator;
37import org.openstreetmap.josm.gui.util.GuiHelper;
38import org.openstreetmap.josm.gui.widgets.DefaultTextComponentValidator;
39import org.openstreetmap.josm.gui.widgets.HtmlPanel;
40import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
41import org.openstreetmap.josm.gui.widgets.JosmPasswordField;
42import org.openstreetmap.josm.gui.widgets.JosmTextField;
43import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator;
44import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
45import org.openstreetmap.josm.io.OsmApi;
46import org.openstreetmap.josm.io.OsmTransferException;
47import org.openstreetmap.josm.io.auth.CredentialsAgent;
48import org.openstreetmap.josm.io.auth.CredentialsAgentException;
49import org.openstreetmap.josm.io.auth.CredentialsManager;
50import org.openstreetmap.josm.tools.ImageProvider;
51import org.openstreetmap.josm.tools.Logging;
52import org.openstreetmap.josm.tools.Utils;
53import org.xml.sax.SAXException;
54
55/**
56 * This is an UI which supports a JOSM user to get an OAuth Access Token in a fully
57 * automatic process.
58 *
59 * @since 2746
60 */
61public class FullyAutomaticAuthorizationUI extends AbstractAuthorizationUI {
62
63 private final JosmTextField tfUserName = new JosmTextField();
64 private final JosmPasswordField tfPassword = new JosmPasswordField();
65 private transient UserNameValidator valUserName;
66 private transient PasswordValidator valPassword;
67 private final AccessTokenInfoPanel pnlAccessTokenInfo = new AccessTokenInfoPanel();
68 private OsmPrivilegesPanel pnlOsmPrivileges;
69 private JPanel pnlPropertiesPanel;
70 private JPanel pnlActionButtonsPanel;
71 private JPanel pnlResult;
72 private final transient Executor executor;
73
74 /**
75 * Builds the panel with the three privileges the user can grant JOSM
76 *
77 * @return constructed panel for the privileges
78 */
79 protected VerticallyScrollablePanel buildGrantsPanel() {
80 pnlOsmPrivileges = new OsmPrivilegesPanel();
81 return pnlOsmPrivileges;
82 }
83
84 /**
85 * Builds the panel for entering the username and password
86 *
87 * @return constructed panel for the creditentials
88 */
89 protected VerticallyScrollablePanel buildUserNamePasswordPanel() {
90 VerticallyScrollablePanel pnl = new VerticallyScrollablePanel(new GridBagLayout());
91 GridBagConstraints gc = new GridBagConstraints();
92 pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
93
94 gc.anchor = GridBagConstraints.NORTHWEST;
95 gc.fill = GridBagConstraints.HORIZONTAL;
96 gc.weightx = 1.0;
97 gc.gridwidth = 2;
98 HtmlPanel pnlMessage = new HtmlPanel();
99 HTMLEditorKit kit = (HTMLEditorKit) pnlMessage.getEditorPane().getEditorKit();
100 kit.getStyleSheet().addRule(
101 ".warning-body {background-color:#DDFFDD; padding: 10pt; " +
102 "border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}");
103 kit.getStyleSheet().addRule("ol {margin-left: 1cm}");
104 pnlMessage.setText("<html><body><p class=\"warning-body\">"
105 + tr("Please enter your OSM user name and password. The password will <strong>not</strong> be saved "
106 + "in clear text in the JOSM preferences and it will be submitted to the OSM server <strong>only once</strong>. "
107 + "Subsequent data upload requests don''t use your password any more.")
108 + "</p>"
109 + "</body></html>");
110 pnl.add(pnlMessage, gc);
111
112 // the user name input field
113 gc.gridy = 1;
114 gc.gridwidth = 1;
115 gc.anchor = GridBagConstraints.NORTHWEST;
116 gc.fill = GridBagConstraints.HORIZONTAL;
117 gc.weightx = 0.0;
118 gc.insets = new Insets(0, 0, 3, 3);
119 pnl.add(new JLabel(tr("Username: ")), gc);
120
121 gc.gridx = 1;
122 gc.weightx = 1.0;
123 pnl.add(tfUserName, gc);
124 SelectAllOnFocusGainedDecorator.decorate(tfUserName);
125 valUserName = new UserNameValidator(tfUserName);
126 valUserName.validate();
127
128 // the password input field
129 gc.anchor = GridBagConstraints.NORTHWEST;
130 gc.fill = GridBagConstraints.HORIZONTAL;
131 gc.gridy = 2;
132 gc.gridx = 0;
133 gc.weightx = 0.0;
134 pnl.add(new JLabel(tr("Password: ")), gc);
135
136 gc.gridx = 1;
137 gc.weightx = 1.0;
138 pnl.add(tfPassword, gc);
139 SelectAllOnFocusGainedDecorator.decorate(tfPassword);
140 valPassword = new PasswordValidator(tfPassword);
141 valPassword.validate();
142
143 // filler - grab remaining space
144 gc.gridy = 4;
145 gc.gridwidth = 2;
146 gc.fill = GridBagConstraints.BOTH;
147 gc.weightx = 1.0;
148 gc.weighty = 1.0;
149 pnl.add(new JPanel(), gc);
150
151 return pnl;
152 }
153
154 protected JPanel buildPropertiesPanel() {
155 JPanel pnl = new JPanel(new BorderLayout());
156
157 JTabbedPane tpProperties = new JTabbedPane();
158 tpProperties.add(buildUserNamePasswordPanel().getVerticalScrollPane());
159 tpProperties.add(buildGrantsPanel().getVerticalScrollPane());
160 tpProperties.add(getAdvancedPropertiesPanel().getVerticalScrollPane());
161 tpProperties.setTitleAt(0, tr("Basic"));
162 tpProperties.setTitleAt(1, tr("Granted rights"));
163 tpProperties.setTitleAt(2, tr("Advanced OAuth properties"));
164
165 pnl.add(tpProperties, BorderLayout.CENTER);
166 return pnl;
167 }
168
169 /**
170 * Initializes the panel with values from the preferences
171 * @param pref Preferences structure
172 */
173 @Override
174 public void initFromPreferences(Preferences pref) {
175 super.initFromPreferences(pref);
176 CredentialsAgent cm = CredentialsManager.getInstance();
177 try {
178 PasswordAuthentication pa = cm.lookup(RequestorType.SERVER, OsmApi.getOsmApi().getHost());
179 if (pa == null) {
180 tfUserName.setText("");
181 tfPassword.setText("");
182 } else {
183 tfUserName.setText(pa.getUserName() == null ? "" : pa.getUserName());
184 tfPassword.setText(pa.getPassword() == null ? "" : String.valueOf(pa.getPassword()));
185 }
186 } catch (CredentialsAgentException e) {
187 Logging.error(e);
188 tfUserName.setText("");
189 tfPassword.setText("");
190 }
191 }
192
193 /**
194 * Builds the panel with the action button for starting the authorisation
195 *
196 * @return constructed button panel
197 */
198 protected JPanel buildActionButtonPanel() {
199 JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
200
201 RunAuthorisationAction runAuthorisationAction = new RunAuthorisationAction();
202 tfPassword.getDocument().addDocumentListener(runAuthorisationAction);
203 tfUserName.getDocument().addDocumentListener(runAuthorisationAction);
204 pnl.add(new JButton(runAuthorisationAction));
205 return pnl;
206 }
207
208 /**
209 * Builds the panel which displays the generated Access Token.
210 *
211 * @return constructed panel for the results
212 */
213 protected JPanel buildResultsPanel() {
214 JPanel pnl = new JPanel(new GridBagLayout());
215 GridBagConstraints gc = new GridBagConstraints();
216 pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
217
218 // the message panel
219 gc.anchor = GridBagConstraints.NORTHWEST;
220 gc.fill = GridBagConstraints.HORIZONTAL;
221 gc.weightx = 1.0;
222 JMultilineLabel msg = new JMultilineLabel("");
223 msg.setFont(msg.getFont().deriveFont(Font.PLAIN));
224 String lbl = tr("Accept Access Token");
225 msg.setText(tr("<html>"
226 + "You have successfully retrieved an OAuth Access Token from the OSM website. "
227 + "Click on <strong>{0}</strong> to accept the token. JOSM will use it in "
228 + "subsequent requests to gain access to the OSM API."
229 + "</html>", lbl));
230 pnl.add(msg, gc);
231
232 // infos about the access token
233 gc.gridy = 1;
234 gc.insets = new Insets(5, 0, 0, 0);
235 pnl.add(pnlAccessTokenInfo, gc);
236
237 // the actions
238 JPanel pnl1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
239 pnl1.add(new JButton(new BackAction()));
240 pnl1.add(new JButton(new TestAccessTokenAction()));
241 gc.gridy = 2;
242 pnl.add(pnl1, gc);
243
244 // filler - grab the remaining space
245 gc.gridy = 3;
246 gc.fill = GridBagConstraints.BOTH;
247 gc.weightx = 1.0;
248 gc.weighty = 1.0;
249 pnl.add(new JPanel(), gc);
250
251 return pnl;
252 }
253
254 protected final void build() {
255 setLayout(new BorderLayout());
256 pnlPropertiesPanel = buildPropertiesPanel();
257 pnlActionButtonsPanel = buildActionButtonPanel();
258 pnlResult = buildResultsPanel();
259
260 prepareUIForEnteringRequest();
261 }
262
263 /**
264 * Prepares the UI for the first step in the automatic process: entering the authentication
265 * and authorisation parameters.
266 *
267 */
268 protected void prepareUIForEnteringRequest() {
269 removeAll();
270 add(pnlPropertiesPanel, BorderLayout.CENTER);
271 add(pnlActionButtonsPanel, BorderLayout.SOUTH);
272 pnlPropertiesPanel.revalidate();
273 pnlActionButtonsPanel.revalidate();
274 validate();
275 repaint();
276
277 setAccessToken(null);
278 }
279
280 /**
281 * Prepares the UI for the second step in the automatic process: displaying the access token
282 *
283 */
284 protected void prepareUIForResultDisplay() {
285 removeAll();
286 add(pnlResult, BorderLayout.CENTER);
287 validate();
288 repaint();
289 }
290
291 protected String getOsmUserName() {
292 return tfUserName.getText();
293 }
294
295 protected String getOsmPassword() {
296 return String.valueOf(tfPassword.getPassword());
297 }
298
299 /**
300 * Constructs a new {@code FullyAutomaticAuthorizationUI} for the given API URL.
301 * @param apiUrl The OSM API URL
302 * @param executor the executor used for running the HTTP requests for the authorization
303 * @since 5422
304 */
305 public FullyAutomaticAuthorizationUI(String apiUrl, Executor executor) {
306 super(apiUrl);
307 this.executor = executor;
308 build();
309 }
310
311 @Override
312 public boolean isSaveAccessTokenToPreferences() {
313 return pnlAccessTokenInfo.isSaveToPreferences();
314 }
315
316 @Override
317 protected void setAccessToken(OAuthToken accessToken) {
318 super.setAccessToken(accessToken);
319 pnlAccessTokenInfo.setAccessToken(accessToken);
320 }
321
322 /**
323 * Starts the authorisation process
324 */
325 class RunAuthorisationAction extends AbstractAction implements DocumentListener {
326 RunAuthorisationAction() {
327 putValue(NAME, tr("Authorize now"));
328 new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
329 putValue(SHORT_DESCRIPTION, tr("Click to redirect you to the authorization form on the JOSM web site"));
330 updateEnabledState();
331 }
332
333 @Override
334 public void actionPerformed(ActionEvent evt) {
335 executor.execute(new FullyAutomaticAuthorisationTask(FullyAutomaticAuthorizationUI.this));
336 }
337
338 protected final void updateEnabledState() {
339 setEnabled(valPassword.isValid() && valUserName.isValid());
340 }
341
342 @Override
343 public void changedUpdate(DocumentEvent e) {
344 updateEnabledState();
345 }
346
347 @Override
348 public void insertUpdate(DocumentEvent e) {
349 updateEnabledState();
350 }
351
352 @Override
353 public void removeUpdate(DocumentEvent e) {
354 updateEnabledState();
355 }
356 }
357
358 /**
359 * Action to go back to step 1 in the process
360 */
361 class BackAction extends AbstractAction {
362 BackAction() {
363 putValue(NAME, tr("Back"));
364 putValue(SHORT_DESCRIPTION, tr("Run the automatic authorization steps again"));
365 new ImageProvider("dialogs", "previous").getResource().attachImageIcon(this);
366 }
367
368 @Override
369 public void actionPerformed(ActionEvent arg0) {
370 prepareUIForEnteringRequest();
371 }
372 }
373
374 /**
375 * Action to test an access token.
376 */
377 class TestAccessTokenAction extends AbstractAction {
378 TestAccessTokenAction() {
379 putValue(NAME, tr("Test Access Token"));
380 new ImageProvider("logo").getResource().attachImageIcon(this);
381 }
382
383 @Override
384 public void actionPerformed(ActionEvent arg0) {
385 executor.execute(new TestAccessTokenTask(
386 FullyAutomaticAuthorizationUI.this,
387 getApiUrl(),
388 getAdvancedPropertiesPanel().getAdvancedParameters(),
389 getAccessToken()
390 ));
391 }
392 }
393
394 static class PasswordValidator extends DefaultTextComponentValidator {
395 PasswordValidator(JTextComponent tc) {
396 super(tc, tr("Please enter your OSM password"), tr("The password cannot be empty. Please enter your OSM password"));
397 }
398 }
399
400 class FullyAutomaticAuthorisationTask extends PleaseWaitRunnable {
401 private boolean canceled;
402
403 FullyAutomaticAuthorisationTask(Component parent) {
404 super(parent, tr("Authorize JOSM to access the OSM API"), false /* don't ignore exceptions */);
405 }
406
407 @Override
408 protected void cancel() {
409 canceled = true;
410 }
411
412 @Override
413 protected void finish() {
414 // Do nothing
415 }
416
417 protected void alertAuthorisationFailed() {
418 HelpAwareOptionPane.showOptionDialog(
419 FullyAutomaticAuthorizationUI.this,
420 tr("<html>"
421 + "The automatic process for retrieving an OAuth Access Token<br>"
422 + "from the OSM server failed.<br><br>"
423 + "Please try again or choose another kind of authorization process,<br>"
424 + "i.e. semi-automatic or manual authorization."
425 +"</html>"),
426 tr("OAuth authorization failed"),
427 JOptionPane.ERROR_MESSAGE,
428 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#FullyAutomaticProcessFailed")
429 );
430 }
431
432 protected void alertInvalidLoginUrl() {
433 HelpAwareOptionPane.showOptionDialog(
434 FullyAutomaticAuthorizationUI.this,
435 tr("<html>"
436 + "The automatic process for retrieving an OAuth Access Token<br>"
437 + "from the OSM server failed because JOSM was not able to build<br>"
438 + "a valid login URL from the OAuth Authorize Endpoint URL ''{0}''.<br><br>"
439 + "Please check your advanced setting and try again."
440 + "</html>",
441 getAdvancedPropertiesPanel().getAdvancedParameters().getAuthoriseUrl()),
442 tr("OAuth authorization failed"),
443 JOptionPane.ERROR_MESSAGE,
444 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#FullyAutomaticProcessFailed")
445 );
446 }
447
448 protected void alertLoginFailed() {
449 final String loginUrl = getAdvancedPropertiesPanel().getAdvancedParameters().getOsmLoginUrl();
450 HelpAwareOptionPane.showOptionDialog(
451 FullyAutomaticAuthorizationUI.this,
452 tr("<html>"
453 + "The automatic process for retrieving an OAuth Access Token<br>"
454 + "from the OSM server failed. JOSM failed to log into {0}<br>"
455 + "for user {1}.<br><br>"
456 + "Please check username and password and try again."
457 +"</html>",
458 loginUrl,
459 Utils.escapeReservedCharactersHTML(getOsmUserName())),
460 tr("OAuth authorization failed"),
461 JOptionPane.ERROR_MESSAGE,
462 HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#FullyAutomaticProcessFailed")
463 );
464 }
465
466 protected void handleException(final OsmOAuthAuthorizationException e) {
467 Runnable r = () -> {
468 if (e instanceof OsmLoginFailedException) {
469 alertLoginFailed();
470 } else {
471 alertAuthorisationFailed();
472 }
473 };
474 Logging.error(e);
475 GuiHelper.runInEDT(r);
476 }
477
478 @Override
479 protected void realRun() throws SAXException, IOException, OsmTransferException {
480 try {
481 getProgressMonitor().setTicksCount(3);
482 OsmOAuthAuthorizationClient authClient = new OsmOAuthAuthorizationClient(
483 getAdvancedPropertiesPanel().getAdvancedParameters()
484 );
485 OAuthToken requestToken = authClient.getRequestToken(
486 getProgressMonitor().createSubTaskMonitor(1, false)
487 );
488 getProgressMonitor().worked(1);
489 if (canceled) return;
490 authClient.authorise(
491 requestToken,
492 getOsmUserName(),
493 getOsmPassword(),
494 pnlOsmPrivileges.getPrivileges(),
495 getProgressMonitor().createSubTaskMonitor(1, false)
496 );
497 getProgressMonitor().worked(1);
498 if (canceled) return;
499 final OAuthToken accessToken = authClient.getAccessToken(
500 getProgressMonitor().createSubTaskMonitor(1, false)
501 );
502 getProgressMonitor().worked(1);
503 if (canceled) return;
504 GuiHelper.runInEDT(() -> {
505 prepareUIForResultDisplay();
506 setAccessToken(accessToken);
507 });
508 } catch (final OsmOAuthAuthorizationException e) {
509 handleException(e);
510 }
511 }
512 }
513}
Note: See TracBrowser for help on using the repository browser.