@Transactional
 public void addConnection(Connection<?> connection) {
   try {
     ConnectionData data = connection.createData();
     int rank =
         jdbcTemplate.queryForInt(
             "select coalesce(max(rank) + 1, 1) as rank from "
                 + tablePrefix
                 + "UserConnection where userId = ? and providerId = ?",
             userId,
             data.getProviderId());
     jdbcTemplate.update(
         "insert into "
             + tablePrefix
             + "UserConnection (userId, providerId, providerUserId, rank, displayName, profileUrl, imageUrl, accessToken, secret, refreshToken, expireTime) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
         userId,
         data.getProviderId(),
         data.getProviderUserId(),
         rank,
         data.getDisplayName(),
         data.getProfileUrl(),
         data.getImageUrl(),
         encrypt(data.getAccessToken()),
         encrypt(data.getSecret()),
         encrypt(data.getRefreshToken()),
         data.getExpireTime());
   } catch (DuplicateKeyException e) {
     throw new DuplicateConnectionException(connection.getKey());
   }
 }
 private void assertNewConnection(Connection<TestFacebookApi> connection) {
   assertEquals("facebook", connection.getKey().getProviderId());
   assertEquals("9", connection.getKey().getProviderUserId());
   assertEquals("Keith Donald", connection.getDisplayName());
   assertEquals("http://facebook.com/keith.donald", connection.getProfileUrl());
   assertEquals("http://facebook.com/keith.donald/picture", connection.getImageUrl());
   assertTrue(connection.test());
   TestFacebookApi api = connection.getApi();
   assertNotNull(api);
   assertEquals("123456789", api.getAccessToken());
   assertEquals("123456789", connection.createData().getAccessToken());
   assertEquals("987654321", connection.createData().getRefreshToken());
 }
 @Test
 public void updateConnectionAccessFields() {
   insertFacebookConnection();
   Connection<TestFacebookApi> facebook =
       connectionRepository.getPrimaryConnection(TestFacebookApi.class);
   assertEquals("234567890", facebook.getApi().getAccessToken());
   facebook.refresh();
   connectionRepository.updateConnection(facebook);
   Connection<TestFacebookApi> facebook2 =
       connectionRepository.getPrimaryConnection(TestFacebookApi.class);
   assertEquals("765432109", facebook2.getApi().getAccessToken());
   ConnectionData data = facebook.createData();
   assertEquals("654321098", data.getRefreshToken());
 }
  @SuppressWarnings("unchecked")
  @Test
  public void addConnection_authenticated() throws Exception {

    FilterTestEnv env = new FilterTestEnv("GET", "/auth", null);
    env.filter.setFilterProcessesUrl(env.req.getRequestURI());
    env.filter.setPostLoginUrl("/success");
    env.filter.setConnectionAddedRedirectUrl("/added");
    env.filter.setConnectionAddingFailureRedirectUrl("/add-failed");

    Connection<?> connection = env.auth.getConnection();
    ConnectionData data = connection.createData();
    String userId = "joe";

    ConnectionFactory<Object> factory = mock(MockConnectionFactory.class);
    when(factory.getProviderId()).thenReturn("mock");
    when(factory.createConnection(data)).thenReturn((Connection<Object>) connection);
    env.req.setRequestURI(env.req.getRequestURI() + "/" + factory.getProviderId());

    SocialAuthenticationService<Object> authService = mock(SocialAuthenticationService.class);
    when(authService.getConnectionCardinality()).thenReturn(ConnectionCardinality.ONE_TO_ONE);
    when(authService.getConnectionFactory()).thenReturn(factory);
    when(authService.getAuthToken(env.req, env.res)).thenReturn(env.auth);
    env.addAuthService(authService);

    when(env.userIdSource.getUserId()).thenReturn(userId);

    when(env.usersConnectionRepository.findUserIdsConnectedTo(
            data.getProviderId(), set(data.getProviderUserId())))
        .thenReturn(empty(String.class));

    // fallback to default /added
    when(authService.getConnectionAddedRedirectUrl(env.req, connection)).thenReturn(null);

    // already authenticated
    SecurityContextHolder.getContext().setAuthentication(env.authSuccess);

    env.doFilter();

    // still authenticated
    assertSame(env.authSuccess, SecurityContextHolder.getContext().getAuthentication());

    assertEquals("/added", env.res.getRedirectedUrl());

    verify(env.connectionRepository).addConnection(env.auth.getConnection());
  }
 @Transactional
 public void updateConnection(Connection<?> connection) {
   ConnectionData data = connection.createData();
   jdbcTemplate.update(
       "update "
           + tablePrefix
           + "UserConnection set displayName = ?, profileUrl = ?, imageUrl = ?, accessToken = ?, secret = ?, refreshToken = ?, expireTime = ? where userId = ? and providerId = ? and providerUserId = ?",
       data.getDisplayName(),
       data.getProfileUrl(),
       data.getImageUrl(),
       encrypt(data.getAccessToken()),
       encrypt(data.getSecret()),
       encrypt(data.getRefreshToken()),
       data.getExpireTime(),
       userId,
       data.getProviderId(),
       data.getProviderUserId());
 }
  @Override
  @Atomic(mode = TxMode.WRITE)
  public void updateConnection(Connection<?> connection) {
    ConnectionData data = connection.createData();

    LdoD.getInstance()
        .getUserConnectionSet()
        .stream()
        .filter(
            uc ->
                uc.getUserId().equals(userId)
                    && uc.getProviderId().equals(data.getProviderId())
                    && uc.getProviderUserId().equals(data.getProviderUserId()))
        .forEach(
            uc -> {
              uc.setDisplayName(data.getDisplayName());
              uc.setProfileUrl(data.getProfileUrl());
              uc.setImageUrl(data.getImageUrl());
              uc.setAccessToken(encrypt(data.getAccessToken()));
              uc.setSecret(encrypt(data.getSecret()));
              uc.setRefreshToken(encrypt(data.getRefreshToken()));
              uc.setExpireTime(data.getExpireTime());
            });
  }
  @Override
  @Atomic(mode = TxMode.WRITE)
  public void addConnection(Connection<?> connection) {
    try {
      ConnectionData data = connection.createData();

      int nextRank =
          LdoD.getInstance()
              .getUserConnectionSet()
              .stream()
              .filter(
                  uc ->
                      uc.getUserId().equals(userId)
                          && uc.getProviderId().equals(data.getProviderId()))
              .max((uc1, uc2) -> Integer.compare(uc1.getRank(), uc2.getRank()))
              .map(uc -> uc.getRank() + 1)
              .orElse(1);

      LdoD.getInstance()
          .createUserConnection(
              userId,
              data.getProviderId(),
              data.getProviderUserId(),
              nextRank,
              data.getDisplayName(),
              data.getProfileUrl(),
              data.getImageUrl(),
              encrypt(data.getAccessToken()),
              encrypt(data.getSecret()),
              encrypt(data.getRefreshToken()),
              data.getExpireTime());

    } catch (DuplicateKeyException e) {
      throw new DuplicateConnectionException(connection.getKey());
    }
  }