Search in sources :

Example 1 with BasicApiConnection

use of org.wikidata.wdtk.wikibaseapi.BasicApiConnection in project OpenRefine by OpenRefine.

the class ConnectionManager method login.

/**
 * Logs in to the Wikibase instance, using username/password.
 * <p>
 * If failed to login, the connection will be set to null.
 *
 * @param mediaWikiApiEndpoint the api endpoint of the target Wikibase instance
 * @param username the username to log in with
 * @param password the password to log in with
 * @return true if logged in successfully, false otherwise
 */
public boolean login(String mediaWikiApiEndpoint, String username, String password) {
    BasicApiConnection connection = new BasicApiConnection(mediaWikiApiEndpoint);
    setupConnection(connection);
    try {
        connection.login(username, password);
        endpointToConnection.put(mediaWikiApiEndpoint, connection);
        return true;
    } catch (LoginFailedException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}
Also used : LoginFailedException(org.wikidata.wdtk.wikibaseapi.LoginFailedException) BasicApiConnection(org.wikidata.wdtk.wikibaseapi.BasicApiConnection)

Example 2 with BasicApiConnection

use of org.wikidata.wdtk.wikibaseapi.BasicApiConnection in project OpenRefine by OpenRefine.

the class LoginCommandTest method testUsernamePasswordLoginRememberCredentials.

@Test
public void testUsernamePasswordLoginRememberCredentials() throws Exception {
    when(request.getParameter("csrf_token")).thenReturn(Command.csrfFactory.getFreshToken());
    when(request.getParameter("remember-credentials")).thenReturn("on");
    when(request.getParameter(API_ENDPOINT)).thenReturn(apiEndpoint);
    when(request.getParameter(USERNAME)).thenReturn(username);
    when(request.getParameter(PASSWORD)).thenReturn(password);
    when(connectionManager.login(apiEndpoint, username, password)).thenReturn(true);
    when(connectionManager.isLoggedIn(apiEndpoint)).thenReturn(true);
    when(connectionManager.getUsername(apiEndpoint)).thenReturn(username);
    BasicApiConnection connection = mock(BasicApiConnection.class);
    when(connectionManager.getConnection(apiEndpoint)).thenReturn(connection);
    when(connection.getCookies()).thenReturn(makeResponseCookies());
    when(connection.getCurrentUser()).thenReturn(username);
    command.doPost(request, response);
    verify(connectionManager, times(1)).login(apiEndpoint, username, password);
    assertLogin();
    Map<String, Cookie> cookies = getCookieMap(cookieCaptor.getAllValues());
    cookieMap.forEach((key, value) -> assertCookieEquals(cookies.get(apiEndpointPrefix + WIKIBASE_COOKIE_PREFIX + key), value, ONE_YEAR));
    assertCookieEquals(cookies.get(apiEndpointPrefix + USERNAME), username, ONE_YEAR);
    assertCookieEquals(cookies.get(apiEndpointPrefix + CONSUMER_TOKEN), "", 0);
    assertCookieEquals(cookies.get(apiEndpointPrefix + CONSUMER_SECRET), "", 0);
    assertCookieEquals(cookies.get(apiEndpointPrefix + ACCESS_TOKEN), "", 0);
    assertCookieEquals(cookies.get(apiEndpointPrefix + ACCESS_SECRET), "", 0);
}
Also used : HttpCookie(java.net.HttpCookie) Cookie(javax.servlet.http.Cookie) BasicApiConnection(org.wikidata.wdtk.wikibaseapi.BasicApiConnection) Test(org.testng.annotations.Test)

Example 3 with BasicApiConnection

use of org.wikidata.wdtk.wikibaseapi.BasicApiConnection in project OpenRefine by OpenRefine.

the class LoginCommandTest method testUsernamePasswordLoginWithCookies.

@Test
public void testUsernamePasswordLoginWithCookies() throws Exception {
    when(request.getParameter("csrf_token")).thenReturn(Command.csrfFactory.getFreshToken());
    when(request.getParameter(API_ENDPOINT)).thenReturn(apiEndpoint);
    when(request.getCookies()).thenReturn(makeRequestCookies());
    when(connectionManager.login(eq(apiEndpoint), eq(username), Mockito.<List<Cookie>>any())).thenReturn(true);
    when(connectionManager.isLoggedIn(apiEndpoint)).thenReturn(true);
    when(connectionManager.getUsername(apiEndpoint)).thenReturn(username);
    BasicApiConnection connection = mock(BasicApiConnection.class);
    when(connectionManager.getConnection(apiEndpoint)).thenReturn(connection);
    when(connection.getCookies()).thenReturn(makeResponseCookies());
    when(connection.getCurrentUser()).thenReturn(username);
    command.doPost(request, response);
    verify(connectionManager, times(1)).login(eq(apiEndpoint), eq(username), Mockito.<List<Cookie>>any());
    assertLogin();
    Map<String, Cookie> cookies = getCookieMap(cookieCaptor.getAllValues());
    assertEquals(cookies.size(), 4);
    assertCookieEquals(cookies.get(apiEndpointPrefix + CONSUMER_TOKEN), "", 0);
    assertCookieEquals(cookies.get(apiEndpointPrefix + CONSUMER_SECRET), "", 0);
    assertCookieEquals(cookies.get(apiEndpointPrefix + ACCESS_TOKEN), "", 0);
    assertCookieEquals(cookies.get(apiEndpointPrefix + ACCESS_SECRET), "", 0);
}
Also used : HttpCookie(java.net.HttpCookie) Cookie(javax.servlet.http.Cookie) BasicApiConnection(org.wikidata.wdtk.wikibaseapi.BasicApiConnection) Test(org.testng.annotations.Test)

Example 4 with BasicApiConnection

use of org.wikidata.wdtk.wikibaseapi.BasicApiConnection in project OpenRefine by OpenRefine.

the class LoginCommand method doPost.

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (!hasValidCSRFToken(request)) {
        respondCSRFError(response);
        return;
    }
    if (manager == null) {
        manager = ConnectionManager.getInstance();
    }
    String mediawikiApiEndpoint = removeCRLF(request.getParameter(API_ENDPOINT));
    if (isBlank(mediawikiApiEndpoint)) {
        CommandUtilities.respondError(response, "missing parameter '" + API_ENDPOINT + "'");
        return;
    }
    String mediawikiApiEndpointPrefix = sanitizeCookieKey(mediawikiApiEndpoint + '-');
    if ("true".equals(request.getParameter("logout"))) {
        manager.logout(mediawikiApiEndpoint);
        removeUsernamePasswordCookies(mediawikiApiEndpointPrefix, request, response);
        removeOwnerOnlyConsumerCookies(mediawikiApiEndpointPrefix, request, response);
        respond(request, response);
        // return directly
        return;
    }
    boolean remember = "on".equals(request.getParameter("remember-credentials"));
    // Credentials from parameters have higher priority than those from cookies.
    String username = request.getParameter(USERNAME);
    String password = request.getParameter(PASSWORD);
    String consumerToken = request.getParameter(CONSUMER_TOKEN);
    String consumerSecret = request.getParameter(CONSUMER_SECRET);
    String accessToken = request.getParameter(ACCESS_TOKEN);
    String accessSecret = request.getParameter(ACCESS_SECRET);
    if (isBlank(username) && isBlank(password) && isBlank(consumerToken) && isBlank(consumerSecret) && isBlank(accessToken) && isBlank(accessSecret)) {
        // In this case, we use cookies to login, and we will always remember the credentials in cookies.
        remember = true;
        Map<String, String> cookieMap = processCookiesWithPrefix(mediawikiApiEndpointPrefix, request.getCookies());
        username = cookieMap.get(USERNAME);
        consumerToken = cookieMap.get(CONSUMER_TOKEN);
        consumerSecret = cookieMap.get(CONSUMER_SECRET);
        accessToken = cookieMap.get(ACCESS_TOKEN);
        accessSecret = cookieMap.get(ACCESS_SECRET);
        if (isBlank(consumerToken) && isBlank(consumerSecret) && isBlank(accessToken) && isBlank(accessSecret)) {
            // Try logging in with the cookies of a password-based connection.
            List<Cookie> cookieList = new ArrayList<>();
            for (Map.Entry<String, String> entry : cookieMap.entrySet()) {
                if (entry.getKey().startsWith(WIKIBASE_COOKIE_PREFIX)) {
                    String name = entry.getKey().substring(WIKIBASE_COOKIE_PREFIX.length());
                    Cookie newCookie = new Cookie(name, entry.getValue());
                    cookieList.add(newCookie);
                }
            }
            if (cookieList.size() > 0 && isNotBlank(username)) {
                removeOwnerOnlyConsumerCookies(mediawikiApiEndpointPrefix, request, response);
                if (manager.login(mediawikiApiEndpoint, username, cookieList)) {
                    respond(request, response);
                    return;
                } else {
                    removeUsernamePasswordCookies(mediawikiApiEndpointPrefix, request, response);
                }
            }
        }
    }
    if (isNotBlank(username) && isNotBlank(password)) {
        // the old credentials in cookies should be cleared.
        if (manager.login(mediawikiApiEndpoint, username, password) && remember) {
            ApiConnection connection = manager.getConnection(mediawikiApiEndpoint);
            List<HttpCookie> cookies = ((BasicApiConnection) connection).getCookies();
            String prefix = mediawikiApiEndpointPrefix + WIKIBASE_COOKIE_PREFIX;
            for (HttpCookie cookie : cookies) {
                setCookie(response, prefix + cookie.getName(), cookie.getValue());
            }
            // Though the cookies from the connection contain some cookies of username,
            // we cannot make sure that all Wikibase instances use the same cookie key
            // to retrieve the username. So we choose to set the username cookie with our own cookie key.
            setCookie(response, mediawikiApiEndpointPrefix + USERNAME, connection.getCurrentUser());
        } else {
            removeUsernamePasswordCookies(mediawikiApiEndpointPrefix, request, response);
        }
        removeOwnerOnlyConsumerCookies(mediawikiApiEndpointPrefix, request, response);
    } else if (isNotBlank(consumerToken) && isNotBlank(consumerSecret) && isNotBlank(accessToken) && isNotBlank(accessSecret)) {
        if (manager.login(mediawikiApiEndpoint, consumerToken, consumerSecret, accessToken, accessSecret) && remember) {
            setCookie(response, mediawikiApiEndpointPrefix + CONSUMER_TOKEN, consumerToken);
            setCookie(response, mediawikiApiEndpointPrefix + CONSUMER_SECRET, consumerSecret);
            setCookie(response, mediawikiApiEndpointPrefix + ACCESS_TOKEN, accessToken);
            setCookie(response, mediawikiApiEndpointPrefix + ACCESS_SECRET, accessSecret);
        } else {
            removeOwnerOnlyConsumerCookies(mediawikiApiEndpointPrefix, request, response);
        }
        removeUsernamePasswordCookies(mediawikiApiEndpointPrefix, request, response);
    }
    respond(request, response);
}
Also used : HttpCookie(java.net.HttpCookie) Cookie(javax.servlet.http.Cookie) ArrayList(java.util.ArrayList) BasicApiConnection(org.wikidata.wdtk.wikibaseapi.BasicApiConnection) ApiConnection(org.wikidata.wdtk.wikibaseapi.ApiConnection) HashMap(java.util.HashMap) Map(java.util.Map) HttpCookie(java.net.HttpCookie) BasicApiConnection(org.wikidata.wdtk.wikibaseapi.BasicApiConnection)

Example 5 with BasicApiConnection

use of org.wikidata.wdtk.wikibaseapi.BasicApiConnection in project OpenRefine by OpenRefine.

the class ConnectionManager method login.

/**
 * Logs in to the Wikibase instance, using cookies.
 * <p>
 * If failed to login, the connection will be set to null.
 *
 * @param mediaWikiApiEndpoint the api endpoint of the target Wikibase instance
 * @param username the username
 * @param cookies  the cookies used to login
 * @return true if logged in successfully, false otherwise
 */
public boolean login(String mediaWikiApiEndpoint, String username, List<Cookie> cookies) {
    cookies.forEach(cookie -> cookie.setPath("/"));
    Map<String, Object> map = new HashMap<>();
    map.put("baseUrl", mediaWikiApiEndpoint);
    map.put("cookies", cookies);
    map.put("username", username);
    map.put("loggedIn", true);
    map.put("tokens", Collections.emptyMap());
    map.put("connectTimeout", CONNECT_TIMEOUT);
    map.put("readTimeout", READ_TIMEOUT);
    try {
        BasicApiConnection connection = convertToBasicApiConnection(map);
        connection.checkCredentials();
        endpointToConnection.put(mediaWikiApiEndpoint, connection);
        return true;
    } catch (IOException | MediaWikiApiErrorException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) MediaWikiApiErrorException(org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException) BasicApiConnection(org.wikidata.wdtk.wikibaseapi.BasicApiConnection)

Aggregations

BasicApiConnection (org.wikidata.wdtk.wikibaseapi.BasicApiConnection)5 HttpCookie (java.net.HttpCookie)3 Cookie (javax.servlet.http.Cookie)3 HashMap (java.util.HashMap)2 Test (org.testng.annotations.Test)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Map (java.util.Map)1 ApiConnection (org.wikidata.wdtk.wikibaseapi.ApiConnection)1 LoginFailedException (org.wikidata.wdtk.wikibaseapi.LoginFailedException)1 MediaWikiApiErrorException (org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException)1