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