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.io.IOException;
008import java.net.HttpURLConnection;
009import java.net.URI;
010import java.net.URL;
011
012import javax.swing.JOptionPane;
013import javax.xml.parsers.ParserConfigurationException;
014
015import org.openstreetmap.josm.data.oauth.IOAuthToken;
016import org.openstreetmap.josm.data.oauth.OAuth20Token;
017import org.openstreetmap.josm.data.oauth.OAuthException;
018import org.openstreetmap.josm.data.osm.UserInfo;
019import org.openstreetmap.josm.gui.HelpAwareOptionPane;
020import org.openstreetmap.josm.gui.PleaseWaitRunnable;
021import org.openstreetmap.josm.gui.help.HelpUtil;
022import org.openstreetmap.josm.io.OsmApi;
023import org.openstreetmap.josm.io.OsmApiException;
024import org.openstreetmap.josm.io.OsmServerUserInfoReader;
025import org.openstreetmap.josm.io.OsmTransferException;
026import org.openstreetmap.josm.io.auth.DefaultAuthenticator;
027import org.openstreetmap.josm.tools.CheckParameterUtil;
028import org.openstreetmap.josm.tools.HttpClient;
029import org.openstreetmap.josm.tools.Logging;
030import org.openstreetmap.josm.tools.Utils;
031import org.openstreetmap.josm.tools.XmlParsingException;
032import org.openstreetmap.josm.tools.XmlUtils;
033import org.w3c.dom.Document;
034import org.xml.sax.SAXException;
035
036/**
037 * Checks whether an OSM API server can be accessed with a specific Access Token.
038 * <p>
039 * It retrieves the user details for the user which is authorized to access the server with
040 * this token.
041 *
042 */
043public class TestAccessTokenTask extends PleaseWaitRunnable {
044    private final IOAuthToken tokenOAuth2;
045    private boolean canceled;
046    private final Component parent;
047    private final String apiUrl;
048    private HttpClient connection;
049
050    /**
051     * Create the task
052     *
053     * @param parent the parent component relative to which the  {@link PleaseWaitRunnable}-Dialog is displayed
054     * @param apiUrl the API URL. Must not be null.
055     * @param accessToken the Access Token. Must not be null.
056     * @since 18991
057     */
058    public TestAccessTokenTask(Component parent, String apiUrl, IOAuthToken accessToken) {
059        super(parent, tr("Testing OAuth Access Token"), false /* don't ignore exceptions */);
060        CheckParameterUtil.ensureParameterNotNull(apiUrl, "apiUrl");
061        CheckParameterUtil.ensureParameterNotNull(accessToken, "accessToken");
062        this.tokenOAuth2 = accessToken;
063        this.parent = parent;
064        this.apiUrl = OsmApi.normalizeApiUrl(apiUrl);
065    }
066
067    @Override
068    protected void cancel() {
069        canceled = true;
070        synchronized (this) {
071            if (connection != null) {
072                connection.disconnect();
073            }
074        }
075    }
076
077    @Override
078    protected void finish() {
079        // Do nothing
080    }
081
082    protected void sign(HttpClient con) throws OAuthException {
083        this.tokenOAuth2.sign(con);
084    }
085
086    protected UserInfo getUserDetails() throws OsmOAuthAuthorizationException, XmlParsingException, OsmTransferException {
087        boolean authenticatorEnabled = true;
088        try {
089            final URL url = URI.create(apiUrl + "/0.6/user/details").toURL();
090            authenticatorEnabled = DefaultAuthenticator.getInstance().isEnabled();
091            DefaultAuthenticator.getInstance().setEnabled(false);
092
093            final HttpClient client = HttpClient.create(url);
094            sign(client);
095            synchronized (this) {
096                connection = client;
097                connection.connect();
098            }
099
100            final String oauthKey = getAuthKey();
101            if (connection.getResponse().getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
102                throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED,
103                        tr("Retrieving user details with Access Token Key ''{0}'' was rejected.",
104                                oauthKey), null);
105            }
106
107            if (connection.getResponse().getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
108                throw new OsmApiException(HttpURLConnection.HTTP_FORBIDDEN,
109                        tr("Retrieving user details with Access Token Key ''{0}'' was forbidden.", oauthKey), null);
110            }
111
112            if (connection.getResponse().getResponseCode() != HttpURLConnection.HTTP_OK) {
113                throw new OsmApiException(connection.getResponse().getResponseCode(),
114                        connection.getResponse().getHeaderField("Error"), null);
115            }
116            final Document d = XmlUtils.parseSafeDOM(connection.getResponse().getContent());
117            return OsmServerUserInfoReader.buildFromXML(d);
118        } catch (SAXException | ParserConfigurationException e) {
119            throw new XmlParsingException(e);
120        } catch (IOException e) {
121            throw new OsmTransferException(e);
122        } catch (OAuthException e) {
123            throw new OsmOAuthAuthorizationException(e);
124        } finally {
125            DefaultAuthenticator.getInstance().setEnabled(authenticatorEnabled);
126        }
127    }
128
129    protected void notifySuccess(UserInfo userInfo) {
130        HelpAwareOptionPane.showMessageDialogInEDT(
131                parent,
132                tr("<html>"
133                        + "Successfully used the Access Token ''{0}'' to<br>"
134                        + "access the OSM server at ''{1}''.<br>"
135                        + "You are accessing the OSM server as user ''{2}'' with id ''{3}''."
136                        + "</html>",
137                        getAuthKey(),
138                        apiUrl,
139                        Utils.escapeReservedCharactersHTML(userInfo.getDisplayName()),
140                        userInfo.getId()
141                ),
142                tr("Success"),
143                JOptionPane.INFORMATION_MESSAGE,
144                HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenOK")
145        );
146    }
147
148    protected void alertFailedAuthentication() {
149        HelpAwareOptionPane.showMessageDialogInEDT(
150                parent,
151                tr("<html>"
152                        + "Failed to access the OSM server ''{0}''<br>"
153                        + "with the Access Token ''{1}''.<br>"
154                        + "The server rejected the Access Token as unauthorized. You will not<br>"
155                        + "be able to access any protected resource on this server using this token."
156                        +"</html>",
157                        apiUrl,
158                        getAuthKey()
159                ),
160                tr("Test failed"),
161                JOptionPane.ERROR_MESSAGE,
162                HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
163        );
164    }
165
166    protected void alertFailedAuthorisation() {
167        HelpAwareOptionPane.showMessageDialogInEDT(
168                parent,
169                tr("<html>"
170                        + "The Access Token ''{1}'' is known to the OSM server ''{0}''.<br>"
171                        + "The test to retrieve the user details for this token failed, though.<br>"
172                        + "Depending on what rights are granted to this token you may nevertheless use it<br>"
173                        + "to upload data, upload GPS traces, and/or access other protected resources."
174                        +"</html>",
175                        apiUrl,
176                        getAuthKey()
177                ),
178                tr("Token allows restricted access"),
179                JOptionPane.WARNING_MESSAGE,
180                HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
181        );
182    }
183
184    protected void alertFailedConnection() {
185        HelpAwareOptionPane.showMessageDialogInEDT(
186                parent,
187                tr("<html>"
188                        + "Failed to retrieve information about the current user"
189                        + " from the OSM server ''{0}''.<br>"
190                        + "This is probably not a problem caused by the tested Access Token, but<br>"
191                        + "rather a problem with the server configuration. Carefully check the server<br>"
192                        + "URL and your Internet connection."
193                        +"</html>",
194                        apiUrl,
195                        getAuthKey()
196                ),
197                tr("Test failed"),
198                JOptionPane.ERROR_MESSAGE,
199                HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
200        );
201    }
202
203    protected void alertFailedSigning() {
204        HelpAwareOptionPane.showMessageDialogInEDT(
205                parent,
206                tr("<html>"
207                        + "Failed to sign the request for the OSM server ''{0}'' with the "
208                        + "token ''{1}''.<br>"
209                        + "The token ist probably invalid."
210                        +"</html>",
211                        apiUrl,
212                        getAuthKey()
213                ),
214                tr("Test failed"),
215                JOptionPane.ERROR_MESSAGE,
216                HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
217        );
218    }
219
220    protected void alertInternalError() {
221        HelpAwareOptionPane.showMessageDialogInEDT(
222                parent,
223                tr("<html>"
224                        + "The test failed because the server responded with an internal error.<br>"
225                        + "JOSM could not decide whether the token is valid. Please try again later."
226                        + "</html>",
227                        apiUrl,
228                        getAuthKey()
229                ),
230                tr("Test failed"),
231                JOptionPane.WARNING_MESSAGE,
232                HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#AccessTokenFailed")
233        );
234    }
235
236    @Override
237    protected void realRun() throws SAXException, IOException, OsmTransferException {
238        try {
239            getProgressMonitor().indeterminateSubTask(tr("Retrieving user info..."));
240            final UserInfo userInfo = getUserDetails();
241            if (canceled) {
242                return;
243            }
244            notifySuccess(userInfo);
245        } catch (OsmOAuthAuthorizationException e) {
246            if (canceled) {
247                return;
248            }
249            Logging.error(e);
250            alertFailedSigning();
251        } catch (OsmApiException e) {
252            if (canceled) {
253                return;
254            }
255            Logging.error(e);
256            if (e.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
257                alertInternalError();
258                return;
259            } else if (e.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
260                alertFailedAuthentication();
261                return;
262            } else if (e.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
263                alertFailedAuthorisation();
264                return;
265            }
266            alertFailedConnection();
267        } catch (OsmTransferException e) {
268            if (canceled) {
269                return;
270            }
271            Logging.error(e);
272            alertFailedConnection();
273        }
274    }
275
276    private String getAuthKey() {
277        if (this.tokenOAuth2 instanceof OAuth20Token) {
278            return ((OAuth20Token) this.tokenOAuth2).getBearerToken();
279        }
280        throw new IllegalArgumentException("Only OAuth2 tokens are understood: " + this.tokenOAuth2);
281    }
282}