org.springframework.social.connect.Connection Java Examples

The following examples show how to use org.springframework.social.connect.Connection. 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 File: SignInAdapterImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 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 #2
Source File: _CustomSignInAdapter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 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 #3
Source File: PcConnectionStatusView.java    From paascloud-master with 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 #4
Source File: MongoConnectionRepositoryImpl.java    From JiwhizBlogWeb with Apache License 2.0 6 votes vote down vote up
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 File: CurrencyExchangeServiceOfflineImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: IndexController.java    From pre with 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 #7
Source File: SocialAuthenticationUtils.java    From Spring-Security-Third-Edition with MIT License 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 #8
Source File: MainController.java    From blog-social-login-with-spring-social with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: MongoConnectionRepositoryImpl.java    From JiwhizBlogWeb with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: UserService.java    From computoser with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #11
Source File: MongoUsersConnectionRepositoryImpl.java    From JiwhizBlogWeb with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: IndexController.java    From cola with 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 #13
Source File: AutoSignUpHandler.java    From boot-stateless-social with MIT License 5 votes vote down vote up
@Override
@Transactional
public String execute(final Connection<?> connection) {
    //add new users to the db with its default roles for later use in SocialAuthenticationSuccessHandler
    final User user = new User();
    user.setUsername(generateUniqueUserName(connection.fetchUserProfile().getFirstName()));
    user.setProviderId(connection.getKey().getProviderId());
    user.setProviderUserId(connection.getKey().getProviderUserId());
    user.setAccessToken(connection.createData().getAccessToken());
    grantRoles(user);
    userRepository.save(user);
    return user.getUserId();
}
 
Example #14
Source File: StockProductServiceOnlineImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
private void updateChartStockFromYahoo(StockProduct stock, ChartType type, ChartHistoSize histoSize, ChartHistoMovingAverage histoAverage,
		ChartHistoTimeSpan histoPeriod, Integer intradayWidth, Integer intradayHeight) {
	
	Preconditions.checkNotNull(stock, "stock must not be null!");
	Preconditions.checkNotNull(type, "ChartType must not be null!");
	
	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) {
		byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(stock.getId(), type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
		LocalDateTime dateTime = LocalDateTime.now();
		String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
		String imageName = stock.getId().toLowerCase()+"_"+type.name().toLowerCase()+"_"+formattedDateTime+".png";
    	String pathToYahooPicture = env.getProperty("user.home").concat(env.getProperty("pictures.yahoo.path")).concat(File.separator+imageName);
    	
           try {
               Path newPath = Paths.get(pathToYahooPicture);
               Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
           } catch (IOException e) {
               throw new Error("Storage of " + pathToYahooPicture+ " failed", e);
           }
           
           ChartStock chartStock = new ChartStock(stock, type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, pathToYahooPicture);
           chartStockRepository.save(chartStock);
       }
}
 
Example #15
Source File: SpringSocialUserDetailService.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<Connection<?>> getConnections(ConnectionRepository connectionRepository) {
	MultiValueMap<String, Connection<?>> connections = connectionRepository.findAllConnections();
	List<Connection<?>> allConnections = new ArrayList<Connection<?>>();
	if (connections.size() > 0) {
		for (List<Connection<?>> connectionList : connections.values()) {
			for (Connection<?> connection : connectionList) {
				allConnections.add(connection);
			}
		}
	}
	return allConnections;
}
 
Example #16
Source File: SocialSignInAdapter.java    From computoser with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request) {
    User user = userService.getUser(Long.parseLong(userId));
    signIn(user, (HttpServletResponse) request.getNativeResponse(), true);
    HttpSession session = ((HttpServletRequest) request.getNativeRequest()).getSession();
    String redirectUri = (String) session.getAttribute(AuthenticationController.REDIRECT_AFTER_LOGIN);
    if (redirectUri != null) {
        return redirectUri;
    }
    return "/";
}
 
Example #17
Source File: JpaConnectionRepository.java    From computoser with GNU Affero General Public License v3.0 5 votes vote down vote up
public static SocialAuthentication connectionToAuth(Connection<?> connection) {
    SocialAuthentication auth = new SocialAuthentication();
    ConnectionData data = connection.createData();
    auth.setProviderId(data.getProviderId());
    auth.setToken(data.getAccessToken());
    auth.setRefreshToken(data.getRefreshToken());
    auth.setSecret(data.getSecret());
    auth.setProviderUserId(data.getProviderUserId());
    return auth;
}
 
Example #18
Source File: IndexServiceOfflineImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
private void updateChartIndexFromYahoo(Index index, ChartType type, ChartHistoSize histoSize, ChartHistoMovingAverage histoAverage,
		ChartHistoTimeSpan histoPeriod, Integer intradayWidth, Integer intradayHeight) {
	
	Preconditions.checkNotNull(index, "index must not be null!");
	Preconditions.checkNotNull(type, "ChartType must not be null!");
	
	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) {
		byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(index.getId(), type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
		LocalDateTime dateTime = LocalDateTime.now();
		String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
		String imageName = index.getId().toLowerCase()+"_"+type.name().toLowerCase()+"_"+formattedDateTime+".png";
    	String pathToYahooPicture = env.getProperty("user.home").concat(env.getProperty("pictures.yahoo.path")).concat(File.separator+imageName);
    	
           try {
               Path newPath = Paths.get(pathToYahooPicture);
               Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
           } catch (IOException e) {
               throw new Error("Storage of " + pathToYahooPicture+ " failed", e);
           }
           
           ChartIndex chartIndex = new ChartIndex(index, type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, pathToYahooPicture);
           chartIndexRepository.save(chartIndex);
       }
}
 
Example #19
Source File: GitHubConfiguration.java    From codeway_service with GNU General Public License v3.0 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 File: FacebookConnectionSignup.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public String execute(Connection<?> connection) {
    System.out.println("signup === ");
    final User user = new User();
    user.setUsername(connection.getDisplayName());
    user.setPassword(randomAlphabetic(8));
    userRepository.save(user);
    return user.getUsername();
}
 
Example #21
Source File: GitHubConfiguration.java    From OAuth-2.0-Cookbook with 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 #22
Source File: _SocialService.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
public void createSocialUser(Connection<?> connection, String langKey) {
    if (connection == null) {
        log.error("Cannot create social user because connection is null");
        throw new IllegalArgumentException("Connection cannot be null");
    }
    UserProfile userProfile = connection.fetchUserProfile();
    String providerId = connection.getKey().getProviderId();
    User user = createUserIfNotExist(userProfile, langKey, providerId);
    createSocialConnection(user.getLogin(), connection);
    mailService.sendSocialRegistrationValidationEmail(user, providerId);
}
 
Example #23
Source File: _SocialController.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/signup", method = RequestMethod.GET)
public RedirectView signUp(WebRequest webRequest, @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = "\"<%= nativeLanguageShortName %>\"") String langKey) {
    try {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest);
        socialService.createSocialUser(connection, langKey.replace("\"", ""));
        return new RedirectView(URIBuilder.fromUri("/#/social-register/" + connection.getKey().getProviderId())
            .queryParam("success", "true")
            .build().toString(), true);
    } catch (Exception e) {
        log.error("Exception creating social user: ", e);
        return new RedirectView(URIBuilder.fromUri("/#/social-register/no-provider")
            .queryParam("success", "false")
            .build().toString(), true);
    }
}
 
Example #24
Source File: SocialAuthenticationUtils.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
public static CalendarUser createCalendarUserFromProvider(Connection<?> connection){

        // TODO: There is a defect with Facebook:
        // org.springframework.social.UncategorizedApiException: (#12) bio field is
        // deprecated for versions v2.8 and higher:
//
//        Connection<Facebook> connection = facebookConnectionFactory.createConnection(accessGrant);
//        Facebook facebook = connection.getApi();
//        String [] fields = { "id", "email",  "first_name", "last_name" };
//        User userProfile = facebook.fetchObject("me", User.class, fields);
//
//        Object api = connection.getApi();
//        if(api instanceof FacebookTemplate){
//            System.out.println("Facebook");
//        }


        // Does not work with spring-social-facebook:2.0.3.RELEASE
        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 #25
Source File: SocialAuthenticationUtils.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
public static void authenticate(Connection<?> connection) {

        CalendarUser user = createCalendarUserFromProvider(connection);

        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(
                        user,
                        null,
                        CalendarUserAuthorityUtils.createAuthorities(user));
        SecurityContextHolder.getContext().setAuthentication(authentication);

    }
 
Example #26
Source File: SocialAuthenticationUtils.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
public static void authenticate(Connection<?> connection) {

        CalendarUser user = createCalendarUserFromProvider(connection);

        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(
                        user,
                        null,
                        CalendarUserAuthorityUtils.createAuthorities(user));
        SecurityContextHolder.getContext().setAuthentication(authentication);

    }
 
Example #27
Source File: SocialAuthenticationUtils.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
public static void authenticate(Connection<?> connection) {

        CalendarUser user = createCalendarUserFromProvider(connection);

        /*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());*/


        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(
                        user,
                        null,
                        CalendarUserAuthorityUtils.createAuthorities(user));

        SecurityContextHolder.getContext().setAuthentication(authentication);

    }
 
Example #28
Source File: ProviderConnectionSignup.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public String execute(Connection<?> connection) {

    CalendarUser user = SocialAuthenticationUtils.createCalendarUserFromProvider(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));*/

    calendarUserDao.createUser(user);

    return user.getEmail();
}
 
Example #29
Source File: FacebookConfiguration.java    From OAuth-2.0-Cookbook with 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;
}
 
Example #30
Source File: MongoConnectionRepositoryImpl.java    From JiwhizBlogWeb with Apache License 2.0 5 votes vote down vote up
public List<Connection<?>> findConnections(String providerId) {
    List<Connection<?>> resultList = new LinkedList<Connection<?>>();
    List<UserSocialConnection> userSocialConnectionList = this.userSocialConnectionRepository
            .findByUserIdAndProviderId(userId, providerId);
    for (UserSocialConnection userSocialConnection : userSocialConnectionList) {
        resultList.add(buildConnection(userSocialConnection));
    }
    return resultList;
}