@Test
 public void removeConnection() throws Exception {
   ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
   ConnectionFactory<TestApi2> connectionFactory =
       new StubOAuth2ConnectionFactory("clientId", "clientSecret", THROW_EXCEPTION);
   connectionFactoryLocator.addConnectionFactory(connectionFactory);
   StubConnectionRepository connectionRepository = new StubConnectionRepository();
   connectionRepository.addConnection(
       connectionFactory.createConnection(
           new ConnectionData(
               "oauth2Provider", "provider1User1", null, null, null, null, null, null, null)));
   connectionRepository.addConnection(
       connectionFactory.createConnection(
           new ConnectionData(
               "oauth2Provider", "provider1User2", null, null, null, null, null, null, null)));
   assertEquals(2, connectionRepository.findConnections("oauth2Provider").size());
   ConnectController connectController =
       new ConnectController(connectionFactoryLocator, connectionRepository);
   List<DisconnectInterceptor<?>> interceptors = getDisconnectInterceptor();
   connectController.setDisconnectInterceptors(interceptors);
   MockMvc mockMvc = standaloneSetup(connectController).build();
   mockMvc
       .perform(delete("/connect/oauth2Provider/provider1User1"))
       .andExpect(redirectedUrl("/connect/oauth2Provider"));
   assertEquals(1, connectionRepository.findConnections("oauth2Provider").size());
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).preDisconnectInvoked);
   assertFalse(((TestConnectInterceptor<?>) (interceptors.get(0))).postDisconnectInvoked);
   assertNull(((TestConnectInterceptor<?>) (interceptors.get(0))).connectionFactory);
   assertTrue(((TestConnectInterceptor<?>) (interceptors.get(1))).preDisconnectInvoked);
   assertTrue(((TestConnectInterceptor<?>) (interceptors.get(1))).postDisconnectInvoked);
   assertSame(
       connectionFactory, ((TestConnectInterceptor<?>) (interceptors.get(1))).connectionFactory);
 }
  @SuppressWarnings("unchecked")
  @Test
  public void testExplicitAuth() throws Exception {

    FilterTestEnv env = new FilterTestEnv("GET", "/auth", null);
    env.filter.setFilterProcessesUrl(env.req.getRequestURI());
    env.filter.setPostLoginUrl("/success");

    ConnectionFactory<Object> factory = mock(MockConnectionFactory.class);
    when(factory.getProviderId()).thenReturn("mock");
    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.authManager.authenticate(env.auth)).thenReturn(env.authSuccess);

    assertNull(SecurityContextHolder.getContext().getAuthentication());

    env.doFilter();

    assertNotNull(SecurityContextHolder.getContext().getAuthentication());

    assertEquals("/success", env.res.getRedirectedUrl());
  }
  @SuppressWarnings("unchecked")
  private void testFailedAuth(FilterTestEnv env) throws Exception {
    env.filter.setFilterProcessesUrl(env.req.getRequestURI());
    env.filter.setPostLoginUrl("/success");

    ConnectionFactory<Object> factory = mock(MockConnectionFactory.class);
    when(factory.getProviderId()).thenReturn("mock");
    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.authManager.authenticate(env.auth)).thenThrow(new BadCredentialsException("Failed"));

    assertNull(SecurityContextHolder.getContext().getAuthentication());

    env.doFilter();

    assertNull(SecurityContextHolder.getContext().getAuthentication());

    assertEquals("http://localhost/register", env.res.getRedirectedUrl());
  }
  @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());
  }
 private List<ConnectInterceptor<?>> interceptingConnectionsTo(
     ConnectionFactory<?> connectionFactory) {
   Class<?> serviceType =
       GenericTypeResolver.resolveTypeArgument(
           connectionFactory.getClass(), ConnectionFactory.class);
   List<ConnectInterceptor<?>> typedInterceptors = connectInterceptors.get(serviceType);
   if (typedInterceptors == null) {
     typedInterceptors = Collections.emptyList();
   }
   return typedInterceptors;
 }
  @Test
  public void connectionStatus() throws Exception {
    ConnectionFactoryRegistry connectionFactoryLocator = new ConnectionFactoryRegistry();
    ConnectionFactory<TestApi1> connectionFactory1 =
        new StubOAuth1ConnectionFactory("clientId", "clientSecret", THROW_EXCEPTION);
    connectionFactoryLocator.addConnectionFactory(connectionFactory1);
    ConnectionFactory<TestApi2> connectionFactory2 =
        new StubOAuth2ConnectionFactory("clientId", "clientSecret", THROW_EXCEPTION);
    connectionFactoryLocator.addConnectionFactory(connectionFactory2);
    StubConnectionRepository connectionRepository = new StubConnectionRepository();
    connectionRepository.addConnection(
        connectionFactory1.createConnection(
            new ConnectionData(
                "oauth1Provider", "provider1User1", null, null, null, null, null, null, null)));
    MockMvc mockMvc =
        standaloneSetup(new ConnectController(connectionFactoryLocator, connectionRepository))
            .build();

    mockMvc
        .perform(get("/connect"))
        .andExpect(view().name("connect/status"))
        .andExpect(
            model()
                .attribute(
                    "providerIds", new HashSet<String>(asList("oauth1Provider", "oauth2Provider"))))
        .andExpect(model().attributeExists("connectionMap"));

    mockMvc
        .perform(get("/connect/oauth1Provider"))
        .andExpect(view().name("connect/oauth1ProviderConnected"))
        .andExpect(model().attributeExists("connections"))
        .andExpect(request().attribute("social.addConnection.duplicate", nullValue()))
        .andExpect(request().attribute("social.provider.error", nullValue()));
    mockMvc
        .perform(get("/connect/oauth2Provider"))
        .andExpect(view().name("connect/oauth2ProviderConnect"))
        .andExpect(request().attribute("social.addConnection.duplicate", nullValue()))
        .andExpect(request().attribute("social.provider.error", nullValue()));
  }
  @SuppressWarnings("unchecked")
  @Test
  public void addConnection() {
    UsersConnectionRepository usersConnectionRepository = mock(UsersConnectionRepository.class);
    SocialAuthenticationFilter filter =
        new SocialAuthenticationFilter(null, null, usersConnectionRepository, null);

    SocialAuthenticationService<Object> authService = mock(SocialAuthenticationService.class);
    ConnectionRepository connectionRepository = mock(ConnectionRepository.class);
    ConnectionFactory<Object> connectionFactory = mock(MockConnectionFactory.class);

    MockHttpServletRequest request = new MockHttpServletRequest();
    ConnectionData data =
        new ConnectionData("dummyprovider", "1234", null, null, null, null, null, null, null);
    String userId = "joe";

    DummyConnection<Object> connection = DummyConnection.dummy(data.getProviderId(), userId);

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

    when(authService.getConnectionCardinality()).thenReturn(ConnectionCardinality.ONE_TO_ONE);
    when(authService.getConnectionFactory()).thenReturn(connectionFactory);
    when(authService.getConnectionAddedRedirectUrl(request, connection)).thenReturn("/redirect");

    when(connectionFactory.createConnection(data)).thenReturn(connection);

    Connection<?> addedConnection = filter.addConnection(authService, userId, data);
    assertNotNull(addedConnection);
    assertSame(connection, addedConnection);

    verify(connectionRepository).addConnection(connection);
  }
 public Connection<?> mapRow(ResultSet rs, int rowNum) throws SQLException {
   ConnectionData connectionData = mapConnectionData(rs);
   ConnectionFactory<?> connectionFactory =
       connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId());
   return connectionFactory.createConnection(connectionData);
 }
 private Connection<?> mapUserConnection(UserConnection userConnection) {
   ConnectionData connectionData = mapConnectionData(userConnection);
   ConnectionFactory<?> connectionFactory =
       connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId());
   return connectionFactory.createConnection(connectionData);
 }