String url = Utils.formatMessage(TOKEN_URL, authCode,
request.getRequestURL().toString(), Config.FB_APP_ID, Config.FB_SECRET);
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet tokenPost = new HttpGet(url);
CloseableHttpResponse resp1 = httpclient.execute(tokenPost);
ObjectReader jreader = Utils.getJsonReader(Map.class);
if (resp1 != null && resp1.getEntity() != null) {
String token = EntityUtils.toString(resp1.getEntity(), Config.DEFAULT_ENCODING);
if (token != null && token.startsWith("access_token")) {
// got valid token
String accessToken = token.substring(token.indexOf("=") + 1, token.indexOf("&"));
HttpGet profileGet = new HttpGet(PROFILE_URL + accessToken);
CloseableHttpResponse resp2 = httpclient.execute(profileGet);
HttpEntity respEntity = resp2.getEntity();
String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
if (respEntity != null && Utils.isJsonType(ctype)) {
Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());
if (profile != null && profile.containsKey("id")) {
String fbId = (String) profile.get("id");
Map<String, Object> pic = (Map<String, Object>) profile.get("picture");
String email = (String) profile.get("email");
String name = (String) profile.get("name");
user.setIdentifier(Config.FB_PREFIX.concat(fbId));
user = User.readUserForIdentifier(user);
if (user == null) {
//user is new
user = new User();
user.setEmail(StringUtils.isBlank(email) ? "email@domain.com" : email);
user.setName(StringUtils.isBlank(name) ? "No Name" : name);
user.setPassword(new UUID().toString());
user.setIdentifier(Config.FB_PREFIX.concat(fbId));
if (user.getPicture() == null && pic != null) {
Map<String, Object> data = (Map<String, Object>) pic.get("data");
// try to get the direct url to the profile pic
if (data != null && data.containsKey("url")) {
user.setPicture((String) data.get("url"));
} else {
user.setPicture("http://graph.facebook.com/" + fbId +
"/picture?width=400&height=400&type=square");
}
}
String id = user.create();
if (id == null) {
throw new AuthenticationServiceException("Authentication failed: cannot create new user.");
}
}
userAuth = new UserAuthentication(user);
}
EntityUtils.consumeQuietly(resp2.getEntity());
}
EntityUtils.consumeQuietly(resp1.getEntity());
}
}
}