@RequestMapping(value = "/swapToken")
public String swapToken(HttpServletRequest request) throws Exception {
final String errorMessage = request.getParameter("error");
final Guest guest = AuthHelper.getGuest();
Connector connector = Connector.getConnector("up");
if (errorMessage!=null) {
notificationsService.addNamedNotification(guest.getId(),
Notification.Type.ERROR, connector.statusNotificationName(),
"There was an error while setting you up with the Jawbone UP service: " + errorMessage);
return "redirect:/app";
}
final String code = request.getParameter("code");
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("grant_type", "authorization_code");
parameters.put("code", code);
parameters.put("client_id", env.get("jawboneUp.client.id"));
parameters.put("client_secret", env.get("jawboneUp.client.secret"));
final String json = HttpUtils.fetch("https://jawbone.com/auth/oauth2/token", parameters);
JSONObject token = JSONObject.fromObject(json);
if (token.has("error")) {
String errorCode = token.getString("error");
notificationsService.addNamedNotification(guest.getId(),
Notification.Type.ERROR,
connector.statusNotificationName(),
errorCode);
// NOTE: In the future if we implement renew for the UP connector
// we will potentially need to mark the connector as permanently failed.
// The way to do this is to get hold of the existing apiKey and do:
// guestService.setApiKeyStatus(apiKey.getId(), ApiKey.Status.STATUS_PERMANENT_FAILURE, null);
return "redirect:/app";
}
final String refresh_token = token.getString("refresh_token");
// Create the entry for this new apiKey in the apiKey table and populate
// ApiKeyAttributes with all of the keys fro oauth.properties needed for
// subsequent update of this connector instance.
ApiKey apiKey;
final String stateParameter = request.getParameter("state");
if (stateParameter !=null&&!StringUtils.isEmpty(stateParameter)) {
long apiKeyId = Long.valueOf(stateParameter);
apiKey = guestService.getApiKey(apiKeyId);
} else {
apiKey = guestService.createApiKey(guest.getId(), Connector.getConnector("up"));
}
guestService.populateApiKey(apiKey.getId());
guestService.setApiKeyAttribute(apiKey,
"accessToken", token.getString("access_token"));