Java Code Examples for org.springframework.social.connect.Connection

The following are top voted examples for showing how to use org.springframework.social.connect.Connection. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: osoon   File: AuthUtil.java   View source code 8 votes vote down vote up
public void authenticate(Connection<?> connection) {
    Facebook facebook = (Facebook) connection.getApi();
    String [] fields = { "id", "name", "email", "first_name", "last_name" };
    User userProfile = facebook.fetchObject("me", User.class, fields);
    String username = userProfile.getName();

    log.info("User Profile by facebook {} {} {}", userProfile.getFirstName(), userProfile.getLastName(), userProfile.getEmail());

    Optional<io.osoon.domain.User> byEmail = userService.findByEmail(userProfile.getEmail());
    io.osoon.domain.User osoonUser;

    if (byEmail.isPresent()) {
        osoonUser = byEmail.get();
    } else {
        io.osoon.domain.User newUser = io.osoon.domain.User.of(userProfile.getEmail(), username);
        newUser.setImageUrl(connection.getImageUrl());
        osoonUser = userService.saveOne(newUser);
    }

    OSoonUserDetails userDetails = new OSoonUserDetails(osoonUser);
    RememberMeAuthenticationToken rememberMeToken = new RememberMeAuthenticationToken("osoon-remember-me", userDetails, null);
    SecurityContextHolder.getContext().setAuthentication(rememberMeToken);

    log.info("User {} {} {} connected.", userProfile.getFirstName(), userProfile.getLastName(), userProfile.getEmail());
}
 
Example 2
Project: xm-uaa   File: ConnectSupport.java   View source code 7 votes vote down vote up
/**
 * Complete the connection to the OAuth2 provider.
 *
 * @param connectionFactory the service provider's connection factory e.g. FacebookConnectionFactory
 * @param request the current web request
 * @return a new connection to the service provider
 */
public Connection completeConnection(OAuth2ConnectionFactory<?> connectionFactory, NativeWebRequest request) {
    if (connectionFactory.supportsStateParameter()) {
        verifyStateParameter(request);
    }

    String code = request.getParameter("code");
    try {
        AccessGrant accessGrant = connectionFactory.getOAuthOperations()
            .exchangeForAccess(code, callbackUrl(request), null);
        return connectionFactory.createConnection(accessGrant);
    } catch (HttpClientErrorException e) {
        log.warn("HttpClientErrorException while completing connection: " + e.getMessage());
        log.warn("      Response body: " + e.getResponseBodyAsString());
        throw e;
    }
}
 
Example 3
Project: xm-uaa   File: SocialController.java   View source code 6 votes vote down vote up
@GetMapping("/signup")
public RedirectView signUp(WebRequest webRequest,
    @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = "\"en\"") String langKey) {
    String providerId = null;
    try {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest);
        providerId = connection.getKey().getProviderId();
        socialService.createSocialUser(connection, langKey.replace("\"", ""));
        return redirect(URIBuilder
                        .fromUri(TenantUtil.getApplicationUrl() + "/social-register/"
                                        + connection.getKey().getProviderId())
                        .queryParam("success", "true").build().toString());
    } catch (Exception e) {
        log.error("Exception creating social user: ", e);
        return redirectOnError(providerId);
    }
}
 
Example 4
Project: xm-uaa   File: SocialController.java   View source code 6 votes vote down vote up
private RedirectView handleSignIn(Connection<?> connection, ConnectionFactory<?> connectionFactory,
    NativeWebRequest request) {
    List<String> userIds = usersConnectionRepository.findUserIdsWithConnection(connection);
    if (userIds.isEmpty()) {
        ProviderSignInAttempt signInAttempt = new ProviderSignInAttempt(connection);
        sessionStrategy.setAttribute(request, ProviderSignInAttempt.SESSION_ATTRIBUTE, signInAttempt);
        return redirect(getSignUpUrl());
    } else if (userIds.size() == 1) {
        usersConnectionRepository.createConnectionRepository(userIds.get(0)).updateConnection(connection);
        String originalUrl = signInAdapter.signIn(userIds.get(0), connection, request);
        return originalUrl != null ? redirect(originalUrl) : redirect(POST_SIGN_IN_URL);
    } else {
        log.error("Find more than one user with connection key: {}", connection.getKey());
        return redirectOnError(connection.getKey().getProviderId());
    }
}
 
Example 5
Project: xm-uaa   File: CustomSocialUsersConnectionRepositoryIntTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void findConnectionsToUsers() {
    connectionFactoryRegistry.addConnectionFactory(new TestTwitterConnectionFactory());
    insertTwitterConnection();
    insertFacebookConnection();
    insertFacebookConnection2();
    MultiValueMap<String, String> providerUsers = new LinkedMultiValueMap<>();
    providerUsers.add("facebook", "10");
    providerUsers.add("facebook", "9");
    providerUsers.add("twitter", "1");
    MultiValueMap<String, Connection<?>> connectionsForUsers = connectionRepository.findConnectionsToUsers(providerUsers);
    assertEquals(2, connectionsForUsers.size());
    String providerId=connectionsForUsers.getFirst("facebook").getKey().getProviderUserId();
    assertTrue("10".equals(providerId) || "9".equals(providerId) );
    assertFacebookConnection((Connection<TestFacebookApi>) connectionRepository.getConnection(new ConnectionKey("facebook", "9")));
    assertTwitterConnection((Connection<TestTwitterApi>) connectionsForUsers.getFirst("twitter"));
}
 
Example 6
Project: sentry   File: DiscordResource.java   View source code 6 votes vote down vote up
private DiscordConnectionVM viewModel(Connection<Discord> connection, boolean user, boolean guilds, boolean connections) {
    DiscordConnectionVM vm = new DiscordConnectionVM();
    vm.setUserId(connection.getKey().getProviderUserId());
    vm.setUsername(connection.getDisplayName());
    vm.setAvatarUrl(connection.getImageUrl());
    if (user) {
        UserProfile userProfile = connection.fetchUserProfile();
        vm.setNickname(userProfile.getFirstName() + "#" + userProfile.getLastName());
    }
    if (guilds) {
        vm.setGuilds(connection.getApi().userOperations().getGuilds());
    }
    if (connections) {
        vm.setConnections(connection.getApi().userOperations().getConnections());
    }
    return vm;
}
 
Example 7
Project: OAuth-2.0-Cookbook   File: FacebookConfiguration.java   View source code 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(Facebook.class)
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Facebook facebook(ConnectionRepository repository) {
	Connection<Facebook> connection = repository
			.findPrimaryConnection(Facebook.class);
	return connection != null ? connection.getApi() : null;
}
 
Example 8
Project: Code4Health-Platform   File: CustomSignInAdapter.java   View source code 6 votes vote down vote up
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
Example 9
Project: spring-io   File: CustomSignInAdapter.java   View source code 6 votes vote down vote up
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException ae) {
        log.error("Social authentication error");
        log.trace("Authentication exception trace: {}", ae);
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
Example 10
Project: gamesboard   File: RegistrationController.java   View source code 6 votes vote down vote up
/**
 * Creates the form object used in the registration form.
 * @param connection
 * @return  If a user is signing in by using a social provider, this method returns a form
 *          object populated by the values given by the provider. Otherwise this method returns
 *          an empty form object (normal form registration).
 */
private RegistrationForm createRegistrationDTO(Connection<?> connection) {
    RegistrationForm dto = new RegistrationForm();

    if (connection != null) {
        UserProfile socialMediaProfile = connection.fetchUserProfile();
        dto.setEmail(socialMediaProfile.getEmail());
        dto.setFirstName(socialMediaProfile.getFirstName());
        dto.setLastName(socialMediaProfile.getLastName());

        ConnectionKey providerKey = connection.getKey();
        dto.setSignInProvider(SocialMediaService.valueOf(providerKey.getProviderId().toUpperCase()));
    }

    return dto;
}
 
Example 11
Project: Spring-Security-Third-Edition   File: SocialAuthenticationUtils.java   View source code 6 votes vote down vote up
public static CalendarUser createCalendarUserFromProvider(Connection<?> connection){
    // TODO: FIXME: Need to put this into a Utility:
    UserProfile profile = connection.fetchUserProfile();

    CalendarUser user = new CalendarUser();

    if(profile.getEmail() != null){
        user.setEmail(profile.getEmail());
    }
    else if(profile.getUsername() != null){
        user.setEmail(profile.getUsername());
    }
    else {
        user.setEmail(connection.getDisplayName());
    }

    user.setFirstName(profile.getFirstName());
    user.setLastName(profile.getLastName());

    user.setPassword(randomAlphabetic(32));

    return user;

}
 
Example 12
Project: dawn-marketplace-server   File: AbstractController.java   View source code 6 votes vote down vote up
/**
 * Add profile information to the model map.
 *
 * @param map
 *            the model map
 * @param principal
 *            the princial or <code>null</code>
 */
private void addProfile(ModelMap map, Principal principal) {
	if (principal != null) {
		Connection<?> connection = null;
		connection = connectionRepository.findPrimaryConnection(Twitter.class);
		if (connection == null)
			connection = connectionRepository.findPrimaryConnection(Google.class);
		if (connection == null)
			connection = connectionRepository.findPrimaryConnection(GitHub.class);
		if (connection != null) {
			map.addAttribute("profileImage", connection.getImageUrl());
			map.addAttribute("profile", connection.getProfileUrl());
		}
		Account findAccountByUsername = accountRepository.findOne(principal.getName());
		map.addAttribute(findAccountByUsername);
	}
}
 
Example 13
Project: unity   File: CustomSocialConnectionRepository.java   View source code 6 votes vote down vote up
@Override
public MultiValueMap<String, Connection<?>> findAllConnections() {
    final List<SocialUserConnection> socialUserConnections
            = socialUserConnectionRepository.findAllByUserIdOrderByProviderIdAscRankAsc(userId);

    final List<Connection<?>> connections = socialUserConnectionsToConnections(socialUserConnections);

    final MultiValueMap<String, Connection<?>> connectionsByProviderId = new LinkedMultiValueMap<>();

    final Set<String> registeredProviderIds = connectionFactoryLocator.registeredProviderIds();

    registeredProviderIds.forEach(registeredProviderId -> connectionsByProviderId
            .put(registeredProviderId, Collections.emptyList()));

    connections.forEach(connection -> {
        final String providerId = connection.getKey().getProviderId();

        if (connectionsByProviderId.get(providerId).isEmpty()) {
            connectionsByProviderId.put(providerId, new LinkedList<>());
        }
        connectionsByProviderId.add(providerId, connection);
    });

    return connectionsByProviderId;
}
 
Example 14
Project: unity   File: CustomSocialConnectionRepository.java   View source code 6 votes vote down vote up
@Override
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
        final MultiValueMap<String, String> providerUserIdsByProviderId) {

    if (Objects.isNull(providerUserIdsByProviderId) || providerUserIdsByProviderId.isEmpty()) {
        throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }

    final MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<>();

    providerUserIdsByProviderId.forEach((providerId, providerUserIds) -> {
        final List<Connection<?>> connections = providerUserIdsToConnections(providerId, providerUserIds);
        connections.forEach(connection -> connectionsForUsers.add(providerId, connection));
    });

    return connectionsForUsers;
}
 
Example 15
Project: unity   File: CustomSocialConnectionRepository.java   View source code 6 votes vote down vote up
private SocialUserConnection connectionToUserSocialConnection(final Connection<?> connection,
                                                              final Long rank) {
    final ConnectionData connectionData = connection.createData();

    return SocialUserConnection.builder()
            .userId(userId)
            .providerId(connection.getKey().getProviderId())
            .providerUserId(connection.getKey().getProviderUserId())
            .rank(rank)
            .displayName(connection.getDisplayName())
            .profileURL(connection.getProfileUrl())
            .imageURL(connection.getImageUrl())
            .accessToken(connectionData.getAccessToken())
            .secret(connectionData.getSecret())
            .refreshToken(connectionData.getRefreshToken())
            .expireTime(connectionData.getExpireTime())
            .build();
}
 
Example 16
Project: unity   File: CustomSocialConnectionRepository.java   View source code 6 votes vote down vote up
private Connection<?> socialUserConnectionToConnection(final SocialUserConnection socialUserConnection) {
    final ConnectionData connectionData = new ConnectionData(socialUserConnection.getProviderId(),
            socialUserConnection.getProviderUserId(),
            socialUserConnection.getDisplayName(),
            socialUserConnection.getProfileURL(),
            socialUserConnection.getImageURL(),
            socialUserConnection.getAccessToken(),
            socialUserConnection.getSecret(),
            socialUserConnection.getRefreshToken(),
            socialUserConnection.getExpireTime());

    final ConnectionFactory<?> connectionFactory
            = connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId());

    return connectionFactory.createConnection(connectionData);
}
 
Example 17
Project: unity   File: DefaultSocialAuthenticationService.java   View source code 6 votes vote down vote up
@Override
public RedirectView authenticate(final WebRequest request) {
    try {
        final Connection<?> connection = providerSignInUtils.getConnectionFromSession(request);

        final User user = socialUserService.create(connection);

        final String jwt = tokenService.getToken(user.getUsername(), user.getPassword());

        final ServletWebRequest servletWebRequest = (ServletWebRequest) request;

        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));

        return new RedirectView(URIBuilder.fromUri(redirectUrl)
                .build().toString(), true);
    } catch (Exception e) {
        return new RedirectView(URIBuilder.fromUri(redirectUrl)
                .queryParam("success", "false")
                .build().toString(), true);
    }
}
 
Example 18
Project: unity   File: CustomSocialUsersConnectionRepositoryTest.java   View source code 6 votes vote down vote up
@Test
public void findUserIdsWithConnection_Success_IfUserConnected() {
    final String providerId = "providerId";
    final String providerUserId = "providerUserId";
    final ConnectionKey key = new ConnectionKey(providerId, providerUserId);

    final Connection connection = mock(Connection.class);

    doReturn(key).when(connection).getKey();

    final List<SocialUserConnection> socialUserConnections
            = new ArrayList() {{
        add(createSocialConnection());
    }};

    final String userId = socialUserConnections.get(0).getUserId();

    doReturn(socialUserConnections).when(socialUserConnectionRepository)
            .findAllByProviderIdAndProviderUserId(providerId, providerUserId);

    Assert.assertTrue(connectionRepository.findUserIdsWithConnection(connection).contains(userId));
}
 
Example 19
Project: sentry   File: DiscordResource.java   View source code 6 votes vote down vote up
private DiscordConnectionVM viewModel(Connection<Discord> connection, boolean user, boolean guilds, boolean connections) {
    DiscordConnectionVM vm = new DiscordConnectionVM();
    vm.setUserId(connection.getKey().getProviderUserId());
    vm.setUsername(connection.getDisplayName());
    vm.setAvatarUrl(connection.getImageUrl());
    if (user) {
        UserProfile userProfile = connection.fetchUserProfile();
        vm.setNickname(userProfile.getFirstName() + "#" + userProfile.getLastName());
    }
    if (guilds) {
        vm.setGuilds(connection.getApi().userOperations().getGuilds());
    }
    if (connections) {
        vm.setConnections(connection.getApi().userOperations().getConnections());
    }
    return vm;
}
 
Example 20
Project: jhipster-ribbon-hystrix   File: _CustomSignInAdapter.java   View source code 6 votes vote down vote up
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
Example 21
Project: spring-social-garmin   File: GarminSigninController.java   View source code 6 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public RedirectView signIn(@RequestParam("username") String username, @RequestParam("password") String password, NativeWebRequest request) {
    try {
        GarminConnectConnectionFactory connectionFactory = (GarminConnectConnectionFactory) this.connectionFactoryLocator.getConnectionFactory(GarminConnectConnection.PROVIDER_ID);

        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
        preSignIn(connectionFactory, parameters, request);

        Connection<GarminConnect> connection = connectionFactory.createConnection(username, password);

        GarminConnect api = connection.getApi();
        // will throw exception if authentication fails
        api.authenticate();

        return handleSignIn(connection, connectionFactory, request);
    } catch (Exception e) {
        LOGGER.error("Exception while signing in to Garmin", e);
        return redirect(URIBuilder.fromUri(signInUrl).queryParam("error", "provider").build().toString());
    }
}
 
Example 22
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: FacebookAutoConfiguration.java   View source code 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(Facebook.class)
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Facebook facebook(ConnectionRepository repository) {
	Connection<Facebook> connection = repository
			.findPrimaryConnection(Facebook.class);
	return connection != null ? connection.getApi() : null;
}
 
Example 23
Project: Thesis-JHipster   File: _CustomSignInAdapter.java   View source code 6 votes vote down vote up
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
Example 24
Project: travel_portal   File: UserDAO.java   View source code 6 votes vote down vote up
public User createUserAccount(Connection<?> connection) {

        UserProfile userProfile = connection.fetchUserProfile();

        String sql = "Insert into USERS "
                + " (id, email,user_name,first_name,last_name,role) "
                + " values (?,?,?,?,?,?) ";

        // Random string with 36 characters.
        String id = UUID.randomUUID().toString();

        String userName = userProfile.getFirstName().trim()
                + " " + userProfile.getLastName().trim();

        this.getJdbcTemplate().update(sql, id, userProfile.getEmail(), userName,
                userProfile.getFirstName(), userProfile.getLastName(), User.ROLE_USER);
        return findById(id);
    }
 
Example 25
Project: spring-social-botFramework   File: BotFrameworkReConnectHandler.java   View source code 6 votes vote down vote up
/**
 * Get existing connection or create new one if no connection found or it expired
 * @return {@link Connection} actual connection
 */
private Connection<BotFramework> getOrCreateConnection() {
    Connection<BotFramework> botFramework = repository.findPrimaryConnection(BotFramework.class);
    if(botFramework == null || botFramework.hasExpired()){
        synchronized (BotFrameworkReConnectHandler.class) {
            botFramework = repository.findPrimaryConnection(BotFramework.class);
            if(botFramework == null || botFramework.hasExpired()){
                if (botFramework != null) {
                    repository.removeConnection(botFramework.getKey());
                }

                botFramework = repository.findPrimaryConnection(BotFramework.class);
                if (botFramework == null) {
                    AccessGrant accessGrant = connectionFactory.getOAuthOperations().authenticateClient(scope);
                    Connection<BotFramework> connection = connectionFactory.createConnection(accessGrant);
                    repository.addConnection(connection);
                    botFramework = repository.findPrimaryConnection(BotFramework.class);
                }
            }
        }
    }
    return botFramework;
}
 
Example 26
Project: spring-oauth-social-microservice-starter   File: SocialConnectionSignUp.java   View source code 6 votes vote down vote up
public String execute(Connection<?> connection) {
      UserProfile profile = connection.fetchUserProfile();

      // If the user already exists we return the user id (email)
      Optional<User> user = userService.findByEmail(profile.getEmail());
      if (user.isPresent()) {
          log.info("Connecting existing account to " + connection.getKey().getProviderId());
          return user.get().getEmail();
      }

      // The user doesn't exist so we need to create them
      User newUser = userService.create(profile.getEmail(), profile.getFirstName(), profile.getLastName());

log.info("Creating new user {} from {}", newUser.getEmail(), connection.getKey().getProviderId());

      return newUser.getEmail();
  }
 
Example 27
Project: spring-boot-concourse   File: FacebookAutoConfiguration.java   View source code 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(Facebook.class)
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Facebook facebook(ConnectionRepository repository) {
	Connection<Facebook> connection = repository
			.findPrimaryConnection(Facebook.class);
	return connection != null ? connection.getApi() : null;
}
 
Example 28
Project: music-for-all-application   File: AccountConnectionSignUpService.java   View source code 6 votes vote down vote up
@Override
public String execute(Connection<?> connection) {
    final UserProfile profile = connection.fetchUserProfile();
    final User user = new User();
    user.setEmail(profile.getEmail());
    if ((profile.getUsername() == null) ||
            (profile.getUsername().length() < 2) ||
            (profile.getUsername().length() > MAX_NAME_LENGTH)) {
        user.setUserData(new UserData(user, profile.getFirstName(), profile.getFirstName(),
                profile.getLastName(), connection.getImageUrl(), "", false));
    } else {
        user.setUserData(new UserData(user, profile.getUsername(), profile.getFirstName(),
                profile.getLastName(), connection.getImageUrl(), "", false));
    }
    user.setPassword(KeyGenerators.string().generateKey());
    if (userService.getByEmail(user.getEmail()) == null) {
        userService.save(user);
        publisher.publishEvent(mails.welcomeMail(user));
    }
    return user.getEmail();
}
 
Example 29
Project: metaworks_framework   File: BroadleafSocialRegisterController.java   View source code 6 votes vote down vote up
public String register(RegisterCustomerForm registerCustomerForm, HttpServletRequest request,
                       HttpServletResponse response, Model model) {
    Connection<?> connection = ProviderSignInUtils.getConnection(new ServletWebRequest(request));
    if (connection != null) {
        UserProfile userProfile = connection.fetchUserProfile();
        Customer customer = registerCustomerForm.getCustomer();
        customer.setFirstName(userProfile.getFirstName());
        customer.setLastName(userProfile.getLastName());
        customer.setEmailAddress(userProfile.getEmail());
        if (isUseEmailForLogin()){
            customer.setUsername(userProfile.getEmail());
        } else {
            customer.setUsername(userProfile.getUsername());
        }
    }

    return super.register(registerCustomerForm, request, response, model);
}
 
Example 30
Project: p2p-webtv   File: SocialServiceTest.java   View source code 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testCreateSocialUserShouldThrowExceptionIfConnectionHasNoEmailAndLoginAlreadyExist() {
  // Setup
  User user = createExistingUser("@LOGIN",
    "[email protected]",
    "OTHER_FIRST_NAME",
    "OTHER_LAST_NAME");
  Connection<?> connection = createConnection("@LOGIN",
    "",
    "FIRST_NAME",
    "LAST_NAME",
    "PROVIDER");

  // Exercise
  socialService.createSocialUser(connection, "fr");

  // Teardown
  userRepository.delete(user);
}
 
Example 31
Project: p2p-webtv   File: SocialServiceTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateSocialUserShouldNotCreateUserIfEmailAlreadyExist() {
  // Setup
  User user = createExistingUser("@OTHER_LOGIN",
    "[email protected]",
    "OTHER_FIRST_NAME",
    "OTHER_LAST_NAME");
  long initialUserCount = userRepository.count();
  Connection<?> connection = createConnection("@LOGIN",
    "[email protected]",
    "FIRST_NAME",
    "LAST_NAME",
    "PROVIDER");

  // Exercise
  socialService.createSocialUser(connection, "fr");

  //Verify
  assertThat(userRepository.count()).isEqualTo(initialUserCount);

  // Teardown
  User userToDelete = userRepository.findOneByEmail("[email protected]").get();
  userRepository.delete(userToDelete);
}
 
Example 32
Project: p2p-webtv   File: SocialServiceTest.java   View source code 6 votes vote down vote up
private Connection<?> createConnection(String login,
                                       String email,
                                       String firstName,
                                       String lastName,
                                       String providerId) {
  UserProfile userProfile = mock(UserProfile.class);
  when(userProfile.getEmail()).thenReturn(email);
  when(userProfile.getUsername()).thenReturn(login);
  when(userProfile.getFirstName()).thenReturn(firstName);
  when(userProfile.getLastName()).thenReturn(lastName);

  Connection<?> connection = mock(Connection.class);
  ConnectionKey key = new ConnectionKey(providerId, "PROVIDER_USER_ID");
  when(connection.fetchUserProfile()).thenReturn(userProfile);
  when(connection.getKey()).thenReturn(key);

  return connection;
}
 
Example 33
Project: awesome-agile   File: AwesomeAgileConnectionRepositoryTest.java   View source code 6 votes vote down vote up
@Test
public void testGetConnection() throws Exception {
  Connection connection = mock(Connection.class);
  ArgumentCaptor<ConnectionData> connectionDataCaptor =
      ArgumentCaptor.forClass(ConnectionData.class);
  when(connectionFactoryOne.createConnection(connectionDataCaptor.capture()))
      .thenReturn(connection);
  when(userRepository.findOneByAuthProviderUserId(PROVIDER_ONE, providerUserId()))
      .thenReturn(user());
  Connection<?> foundConnection = connectionRepository.getConnection(
      new ConnectionKey(PROVIDER_ONE, providerUserId()));
  assertNotNull(foundConnection);
  assertEquals(connection, foundConnection);
  ConnectionData connectionData = connectionDataCaptor.getValue();
  assertConnectionData(user(), connectionData);
}
 
Example 34
Project: p2p-webtv   File: CustomSocialUsersConnectionRepositoryTest.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void findConnectionsToUsers() {
  connectionFactoryRegistry.addConnectionFactory(new TestTwitterConnectionFactory());
  insertTwitterConnection();
  insertFacebookConnection();
  insertFacebookConnection2();
  MultiValueMap<String, String> providerUsers = new LinkedMultiValueMap<>();
  providerUsers.add("facebook", "10");
  providerUsers.add("facebook", "9");
  providerUsers.add("twitter", "1");
  MultiValueMap<String, Connection<?>> connectionsForUsers = connectionRepository.findConnectionsToUsers(providerUsers);
  assertEquals(2, connectionsForUsers.size());
  assertEquals("10", connectionsForUsers.getFirst("facebook").getKey().getProviderUserId());
  assertFacebookConnection((Connection<TestFacebookApi>) connectionsForUsers.get("facebook").get(1));
  assertTwitterConnection((Connection<TestTwitterApi>) connectionsForUsers.getFirst("twitter"));
}
 
Example 35
Project: p2p-webtv   File: SocialServiceTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateSocialUserShouldCreateUserWithSocialInformation() {
  // Setup
  Connection<?> connection = createConnection("@LOGIN",
    "[email protected]",
    "FIRST_NAME",
    "LAST_NAME",
    "PROVIDER");

  // Exercise
  socialService.createSocialUser(connection, "fr");

  //Verify
  User user = userRepository.findOneByEmail("[email protected]").get();
  assertThat(user.getFirstName()).isEqualTo("FIRST_NAME");
  assertThat(user.getLastName()).isEqualTo("LAST_NAME");

  // Teardown
  userRepository.delete(user);
}
 
Example 36
Project: p2p-webtv   File: SocialServiceTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateSocialUserShouldCreateUserWithSocialLoginWhenIsTwitter() {
  // Setup
  Connection<?> connection = createConnection("@LOGIN",
    "[email protected]",
    "FIRST_NAME",
    "LAST_NAME",
    "twitter");

  // Exercise
  socialService.createSocialUser(connection, "fr");

  //Verify
  User user = userRepository.findOneByEmail("[email protected]").get();
  assertThat(user.getLogin()).isEqualTo("@LOGIN");

  // Teardown
  userRepository.delete(user);
}
 
Example 37
Project: p2p-webtv   File: SocialServiceTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateSocialUserShouldCreateUserWithLoginSameAsEmailIfNotTwitter() {
  // Setup
  Connection<?> connection = createConnection("@LOGIN",
    "[email protected]",
    "FIRST_NAME",
    "LAST_NAME",
    "PROVIDER_OTHER_THAN_TWITTER");

  // Exercise
  socialService.createSocialUser(connection, "fr");

  //Verify
  User user = userRepository.findOneByEmail("[email protected]").get();
  assertThat(user.getLogin()).isEqualTo("[email protected]");

  // Teardown
  userRepository.delete(user);
}
 
Example 38
Project: cloudstreetmarket.com   File: CurrencyExchangeServiceOnlineImpl.java   View source code 6 votes vote down vote up
private void updateCurrencyExchangeFromYahoo(String ticker) {
	String guid = AuthenticationUtil.getPrincipal().getUsername();
	SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
	if(socialUser == null){
		return;
	}
	
	String token = socialUser.getAccessToken();
	Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

       if (connection == null) {
       	return;
       }

	List<YahooQuote> yahooQuotes = connection.getApi().financialOperations().getYahooQuotes(Lists.newArrayList(ticker), token);
	if(yahooQuotes == null || yahooQuotes.size() > 1){
		throw new IllegalArgumentException("Currency ticker:"+ticker+" not found at Yahoo!");
	}
	currencyExchangeRepository.save(yahooCurrencyConverter.convert(yahooQuotes.get(0)));
}
 
Example 39
Project: cloudstreetmarket.com   File: SignInAdapterImpl.java   View source code 6 votes vote down vote up
public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {
    User user = userRepository.findOne(userId);
    String view = null;
	if(user == null){
		//temporary user for Spring Security
		//won't be persisted
		user = new User(userId, communityServiceHelper.generatePassword(), null, null, true, true, true, true, communityService.createAuthorities(new Role[]{Role.ROLE_BASIC, Role.ROLE_OAUTH2}), null, null, null, null);
	}
	else{
		//Here we have a successful previous oAuth authentication
		//Also the user is already registered
		//Only the guid will be sent back
		
		List<SocialUser> socialUsers = socialUserRepository.findByProviderUserIdOrUserId(userId, userId);
		if(socialUsers!= null && !socialUsers.isEmpty()){
			//For now we only deal with Yahoo!
			//Later we will have to get the provider the user has selected to login with
			view = successView.concat("?spi="+socialUsers.get(0).getProviderUserId());
		}
	}
	
    communityService.signInUser(user);
    return view;

}
 
Example 40
Project: SparkCommerce   File: SparkSocialRegisterController.java   View source code 6 votes vote down vote up
public String register(RegisterCustomerForm registerCustomerForm, HttpServletRequest request,
                       HttpServletResponse response, Model model) {
    Connection<?> connection = ProviderSignInUtils.getConnection(new ServletWebRequest(request));
    if (connection != null) {
        UserProfile userProfile = connection.fetchUserProfile();
        Customer customer = registerCustomerForm.getCustomer();
        customer.setFirstName(userProfile.getFirstName());
        customer.setLastName(userProfile.getLastName());
        customer.setEmailAddress(userProfile.getEmail());
        if (isUseEmailForLogin()){
            customer.setUsername(userProfile.getEmail());
        } else {
            customer.setUsername(userProfile.getUsername());
        }
    }

    return super.register(registerCustomerForm, request, response, model);
}