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

The following examples show how to use org.springframework.social.connect.Connection. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cola   Source File: IndexController.java    License: MIT License 6 votes vote down vote up
@RequestMapping("/")
public ModelAndView root(Map<String, Object> model, Principal principal) {

	MultiValueMap<String, Connection<?>> connections = connectionRepository.findAllConnections();
	List<Map<String, Object>> connectionMap = connections.entrySet().stream().map(entry -> {
		Map<String, Object> connection = new HashMap<>();
		connection.put("provider", entry.getKey());
		if (entry.getValue().isEmpty()) {
			connection.put("connected", false);
			connection.put("displayName", "");
		} else {
			connection.put("connected", true);
			connection.put("displayName", entry.getValue().get(0).getDisplayName());
		}
		return connection;
	}).collect(Collectors.toList());
	model.put("connections", connectionMap);
	model.put("name", principal.getName());
	return new ModelAndView("index", model);

}
 
Example 2
public List<String> findUserIdsWithConnection(Connection<?> connection) {
    ConnectionKey key = connection.getKey();
    List<UserSocialConnection> userSocialConnectionList = 
            this.userSocialConnectionRepository.findByProviderIdAndProviderUserId(key.getProviderId(), key.getProviderUserId());
    List<String> localUserIds = new ArrayList<String>();
    for (UserSocialConnection userSocialConnection : userSocialConnectionList){
        localUserIds.add(userSocialConnection.getUserId());
    }
    
    if (localUserIds.size() == 0 && connectionSignUp != null) {
        String newUserId = connectionSignUp.execute(connection);
        if (newUserId != null)
        {
            createConnectionRepository(newUserId).addConnection(connection);
            return Arrays.asList(newUserId);
        }
    }
    return localUserIds;
}
 
Example 3
Source Project: pre   Source File: IndexController.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 保存完信息然后跳转到绑定用户信息页面
 *
 * @param request
 * @param response
 * @throws IOException
 */
@GetMapping("/socialSignUp")
public void socialSignUp(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uuid = UUID.randomUUID().toString();
    SocialUserInfo userInfo = new SocialUserInfo();
    Connection<?> connectionFromSession = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
    userInfo.setHeadImg(connectionFromSession.getImageUrl());
    userInfo.setNickname(connectionFromSession.getDisplayName());
    userInfo.setProviderId(connectionFromSession.getKey().getProviderId());
    userInfo.setProviderUserId(connectionFromSession.getKey().getProviderUserId());
    ConnectionData data = connectionFromSession.createData();
    PreConnectionData preConnectionData = new PreConnectionData();
    BeanUtil.copyProperties(data, preConnectionData);
    socialRedisHelper.saveConnectionData(uuid, preConnectionData);
    // 跳转到用户绑定页面
    response.sendRedirect(url + "/bind?key=" + uuid);
}
 
Example 4
public MultiValueMap<String, Connection<?>> findAllConnections() {
    List<UserSocialConnection> userSocialConnectionList = this.userSocialConnectionRepository
            .findByUserId(userId);

    MultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<String, Connection<?>>();
    Set<String> registeredProviderIds = socialAuthenticationServiceLocator.registeredProviderIds();
    for (String registeredProviderId : registeredProviderIds) {
        connections.put(registeredProviderId, Collections.<Connection<?>> emptyList());
    }
    for (UserSocialConnection userSocialConnection : userSocialConnectionList) {
        String providerId = userSocialConnection.getProviderId();
        if (connections.get(providerId).size() == 0) {
            connections.put(providerId, new LinkedList<Connection<?>>());
        }
        connections.add(providerId, buildConnection(userSocialConnection));
    }
    return connections;
}
 
Example 5
Source Project: paascloud-master   Source File: PcConnectionStatusView.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Render merged output model.
 *
 * @param model    the model
 * @param request  the request
 * @param response the response
 *
 * @throws Exception the exception
 */
@SuppressWarnings("unchecked")
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {

	Map<String, List<Connection<?>>> connections = (Map<String, List<Connection<?>>>) model.get("connectionMap");

	Map<String, Boolean> result = new HashMap<>(8);
	for (String key : connections.keySet()) {
		result.put(key, CollectionUtils.isNotEmpty(connections.get(key)));
	}

	response.setContentType("application/json;charset=UTF-8");
	response.getWriter().write(objectMapper.writeValueAsString(result));
}
 
Example 6
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 7
@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 8
private void updateCurrencyExchangeFromYahoo(String ticker) {
	String guid = AuthenticationUtil.getPrincipal().getUsername();
	String token = usersConnectionRepository.getRegisteredSocialUser(guid).getAccessToken();
	ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(guid);
	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 9
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 10
@RequestMapping(value= "/updateStatus", method = POST)
public String updateStatus(
    WebRequest webRequest,
    HttpServletRequest request,
    Principal currentUser,
    Model model,
    @RequestParam(value = "status", required = true) String status) {
    MultiValueMap<String, Connection<?>> cmap = connectionRepository.findAllConnections();
    LOG.error("cs.size = {}", cmap.size());
    Set<Map.Entry<String, List<Connection<?>>>> entries = cmap.entrySet();
    for (Map.Entry<String, List<Connection<?>>> entry : entries) {
        for (Connection<?> c : entry.getValue()) {
            LOG.debug("Updates {} with the status '{}'", entry.getKey(), status);
            c.updateStatus(status);
        }
    }

    return "home";
}
 
Example 11
public void updateConnection(Connection<?> connection) {
    ConnectionData data = connection.createData();
    UserSocialConnection userSocialConnection = this.userSocialConnectionRepository
            .findByUserIdAndProviderIdAndProviderUserId(userId, connection.getKey().getProviderId(), connection
                    .getKey().getProviderUserId());
    if (userSocialConnection != null) {
        userSocialConnection.setDisplayName(data.getDisplayName());
        userSocialConnection.setProfileUrl(data.getProfileUrl());
        userSocialConnection.setImageUrl(data.getImageUrl());
        userSocialConnection.setAccessToken(encrypt(data.getAccessToken()));
        userSocialConnection.setSecret(encrypt(data.getSecret()));
        userSocialConnection.setRefreshToken(encrypt(data.getRefreshToken()));
        userSocialConnection.setExpireTime(data.getExpireTime());
        this.userSocialConnectionRepository.save(userSocialConnection);
    }
}
 
Example 12
@Transactional
public User completeUserRegistration(String email, String username, String names, Connection<?> connection, boolean loginAutomatically, boolean receiveDailyDigest) {
    User user = new User();
    user.setEmail(email);
    user.setNames(names);
    user.setUsername(username);
    user.setLoginAutomatically(loginAutomatically);
    user.setRegistrationTime(new DateTime());
    user.setReceiveDailyDigest(receiveDailyDigest);
    user = userDao.persist(user);
    if (connection != null) {
        SocialAuthentication auth = JpaConnectionRepository.connectionToAuth(connection);
        auth.setUser(user);
        userDao.persist(auth);
    }
    return user;
}
 
Example 13
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public GitHub gitHub(ConnectionRepository repository) {
	Connection<GitHub> connection = repository
			.findPrimaryConnection(GitHub.class);
	return connection != null ? connection.getApi() : null;
}
 
Example 14
Source Project: cola   Source File: IndexController.java    License: MIT License 5 votes vote down vote up
@RequestMapping("/")
public ModelAndView root(Map<String, Object> model, Principal principal) {

	List<Approval> approvals = clientDetailsService.listClientDetails().stream()
			.map(clientDetails -> approvalStore.getApprovals(principal.getName(), clientDetails.getClientId()))
			.flatMap(Collection::stream)
			.collect(Collectors.groupingBy(Approval::getClientId)).entrySet().stream().map((entry) -> {
				//合并
				Optional<Approval> sum = entry.getValue().stream().reduce((v1, v2) -> {
					v1.setScope(v1.getScope() + "," + v2.getScope());
					return v1;
				});
				return sum.get();
			}).collect(Collectors.toList());
	model.put("approvals", approvals);

	MultiValueMap<String, Connection<?>> connections = connectionRepository.findAllConnections();
	List<Map<String, Object>> connectionMap = connections.entrySet().stream().map(entry -> {
		Map<String, Object> connection = new HashMap<>();
		connection.put("provider", entry.getKey());
		if (entry.getValue().isEmpty()) {
			connection.put("connected", false);
			connection.put("displayName", "");
		} else {
			connection.put("connected", true);
			connection.put("displayName", entry.getValue().get(0).getDisplayName());
		}
		return connection;
	}).collect(Collectors.toList());
	model.put("connections", connectionMap);
	model.put("name", principal.getName());
	return new ModelAndView("index", model);

}
 
Example 15
Source Project: cola   Source File: SocialConnectStatusView.java    License: MIT License 5 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
	Map<String, List<Connection<?>>> connections = (Map<String, List<Connection<?>>>) model.get("connectionMap");

	Map<String, Boolean> result = new HashMap<>();
	for (String key : connections.keySet()) {
		result.put(key, CollectionUtils.isNotEmpty(connections.get(key)));
	}

	response.setContentType("application/json;charset=UTF-8");
	result.put("success", true);
	response.getWriter().write(objectMapper.writeValueAsString(result));
}
 
Example 16
Source Project: cola   Source File: SocialSignUpController.java    License: MIT License 5 votes vote down vote up
@GetMapping(value = "${spring.social.signupUrl:/social/signup}")
public ModelAndView signUpPage(HttpServletRequest request, Map<String, Object> map) {
	SocialUserInfo userInfo = new SocialUserInfo();
	Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
	if (connection != null) {
		userInfo.setProviderId(connection.getKey().getProviderId());
		userInfo.setProviderUserId(connection.getKey().getProviderUserId());
		userInfo.setNickname(connection.getDisplayName());
		userInfo.setHeadImg(connection.getImageUrl());
		map.put("user", userInfo);
		return new ModelAndView("/social/signup", map);
	} else {
		return new ModelAndView("redirect:/login");
	}
}
 
Example 17
Source Project: cola   Source File: SocialSignUpController.java    License: MIT License 5 votes vote down vote up
@ResponseBody
@PostMapping(value = "/social/signup")
public Result<String> signUp(String username, String password, String confirmPassword, String signupType, HttpServletRequest request) {
	Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
	try {
		UserDto user;
		Assert.isTrue(StringUtils.isNotEmpty(signupType), "绑定类型不能为空");
		Assert.isTrue(StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password), "账号和密码不能为空");
		if (SIGNUP_TYPE_LOGIN.equals(signupType)) {
			user = this.userService.findByUsername(username);
			Assert.notNull(user, "账号不存在");
			Assert.isTrue(passwordEncoder.matches(password, user.getPassword()), "账号或密码错误");
		} else {
			Assert.isTrue(password.equals(confirmPassword), "密码不匹配");
			UserAddDto userAddDto = UserAddDto.builder()
					.username(username)
					.password(password)
					.name("用户" + System.currentTimeMillis()).build();
			user = userService.add(userAddDto);
		}

		providerSignInUtils.doPostSignUp(user.getUsername(), new ServletWebRequest(request));
		return Result.success();

	} catch (Exception e) {
		e.printStackTrace();
		return Result.fail(e.getMessage());
	}
}
 
Example 18
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public GitHub gitHub(ConnectionRepository repository) {
	Connection<GitHub> connection = repository
			.findPrimaryConnection(GitHub.class);
	return connection != null ? connection.getApi() : null;
}
 
Example 19
Source Project: oauth2lab   Source File: GitHubConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public GitHub gitHub(ConnectionRepository repository) {
	Connection<GitHub> connection = repository
			.findPrimaryConnection(GitHub.class);
	return connection != null ? connection.getApi() : null;
}
 
Example 20
Source Project: paascloud-master   Source File: AppSecurityController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 需要注册时跳到这里,返回401和用户信息给前端
 *
 * @param request the request
 *
 * @return social user info
 */
@GetMapping(SecurityConstants.DEFAULT_SOCIAL_USER_INFO_URL)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
	Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
	appSingUpUtils.saveConnectionData(new ServletWebRequest(request), connection.createData());
	return buildSocialUserInfo(connection);
}
 
Example 21
Source Project: paascloud-master   Source File: BaseSocialController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据Connection信息构建SocialUserInfo
 *
 * @param connection the connection
 *
 * @return social user info
 */
protected SocialUserInfo buildSocialUserInfo(Connection<?> connection) {
	SocialUserInfo userInfo = new SocialUserInfo();
	userInfo.setProviderId(connection.getKey().getProviderId());
	userInfo.setProviderUserId(connection.getKey().getProviderUserId());
	userInfo.setNickname(connection.getDisplayName());
	userInfo.setHeadimg(connection.getImageUrl());
	return userInfo;
}
 
Example 22
private Connection<?> buildConnection(UserSocialConnection userSocialConnection) {
    ConnectionData connectionData = new ConnectionData(userSocialConnection.getProviderId(),
            userSocialConnection.getProviderUserId(), userSocialConnection.getDisplayName(),
            userSocialConnection.getProfileUrl(), userSocialConnection.getImageUrl(),
            decrypt(userSocialConnection.getAccessToken()), decrypt(userSocialConnection.getSecret()),
            decrypt(userSocialConnection.getRefreshToken()), userSocialConnection.getExpireTime());
    ConnectionFactory<?> connectionFactory = this.socialAuthenticationServiceLocator.getConnectionFactory(connectionData
            .getProviderId());
    return connectionFactory.createConnection(connectionData);
}
 
Example 23
Source Project: FEBS-Security   Source File: SocialConnectionStatusView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void renderMergedOutputModel(@Nullable Map<String, Object> map, @Nullable HttpServletRequest httpServletRequest, @Nullable HttpServletResponse httpServletResponse) throws Exception {
    Map<String, List<Connection<?>>> connection = (Map<String, List<Connection<?>>>) Objects.requireNonNull(map).get("connectionMap");
    Map<String, Boolean> result = new HashMap<>();
    connection.forEach((key, value) -> result.put(key, CollectionUtils.isNotEmpty(connection.get(key))));

    Objects.requireNonNull(httpServletResponse).setContentType(FebsConstant.JSON_UTF8);
    httpServletResponse.getWriter().write(mapper.writeValueAsString(result));

}
 
Example 24
Source Project: FEBS-Security   Source File: SocialConnectedView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    String view = "";
    List<Connection<?>> connections = (List<Connection<?>>) model.get("connections");
    if (!connections.isEmpty()) {
        Connection<?> connection = connections.get(0);
        sessionStrategy.setAttribute(new ServletWebRequest(request, response), FebsConstant.SESSION_KEY_SOCIAL_OPENID, connection.getKey().getProviderUserId());
        view = FebsConstant.SOCIAL_BIND_SUCCESS_URL;
    } else {
        view = FebsConstant.SOCIAL_UNBIND_SUCCESS_URL;
    }
    response.setContentType(FebsConstant.HTML_UTF8);
    response.sendRedirect(view);
}
 
Example 25
Source Project: spring-social-wechat-sample   Source File: Application.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator,
		UsersConnectionRepository usersConnectionRepository, WechatSignInAdapter wechatSignInAdapter) {
	((InMemoryUsersConnectionRepository) usersConnectionRepository)
			.setConnectionSignUp((Connection<?> connection) -> connection.getKey().getProviderUserId());
	return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, wechatSignInAdapter);
}
 
Example 26
@Override
public String signIn(String openId, Connection<?> connection, NativeWebRequest request) {
	ConnectionKey key = connection.getKey();
	if ("wechat".equalsIgnoreCase(key.getProviderId()) || "wechatmp".equalsIgnoreCase(key.getProviderId())) { // 这里的if判断可对微信开放平台和微信公众平台帐号登录做不同的逻辑处理,此例子代码处理逻辑相同
		User user = ((Wechat) connection.getApi()).userOperations().getUserProfile(openId); // 默认语言为英文,如果想切换为中文可改为:getUserProfile(openId,WechatLangEnum.ZH_CN);
		System.out.println(user); // 打印微信用户详细信息
	}
	return "/login.htm"; // 返回跳转的url
}
 
Example 27
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
		throws AuthenticationException, InvalidTokenException {
	AccessGrant accessGrant = new AccessGrant(accessToken);
	Connection<?> connection = this.connectionFactory.createConnection(accessGrant);
	UserProfile user = connection.fetchUserProfile();
	return extractAuthentication(user);
}
 
Example 28
Source Project: OAuth-2.0-Cookbook   Source File: GoogleConfigurerAdapter.java    License: MIT License 5 votes vote down vote up
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public Google google(final ConnectionRepository repository) {
	final Connection<Google> connection = repository
			.findPrimaryConnection(Google.class);
	return connection != null ? connection.getApi() : null;
}
 
Example 29
Source Project: OAuth-2.0-Cookbook   Source File: GitHubConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public GitHub gitHub(ConnectionRepository repository) {
	Connection<GitHub> connection = repository
			.findPrimaryConnection(GitHub.class);
	return connection != null ? connection.getApi() : null;
}
 
Example 30
Source Project: OAuth-2.0-Cookbook   Source File: FacebookConfiguration.java    License: MIT License 5 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;
}