UIAccountSocial uiForm = event.getSource();
OrganizationService service = uiForm.getApplicationComponent(OrganizationService.class);
WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
PortalRequestContext prContext = Util.getPortalRequestContext();
UIApplication uiApp = context.getUIApplication();
ConversationState state = ConversationState.getCurrent();
String userName = ((User) state.getAttribute(CacheUserProfileFilter.USER_PROFILE)).getUserName();
User user = service.getUserHandler().findUserByName(userName);
if (user != null) {
UserProfile userProfile = (UserProfile)prContext.getAttribute(UserProfileLifecycle.USER_PROFILE_ATTRIBUTE_NAME);
String unlinkProviderKey = prContext.getRequestParameter(PARAM_PROVIDER_FOR_UNLINK);
OAuthProviderType<AccessTokenContext> oauthProviderTypeToUnlink = uiForm.getApplicationComponent(OAuthProviderTypeRegistry.class).getOAuthProvider(unlinkProviderKey, AccessTokenContext.class);
// Obtain current accessToken
AccessTokenContext accessToken = uiForm.getApplicationComponent(SocialNetworkService.class).getOAuthAccessToken(oauthProviderTypeToUnlink, userName);
// Unlink social account in userProfile (AccessTokenInvalidationListener will automatically remove accessToken)
if (oauthProviderTypeToUnlink != null) {
userProfile.setAttribute(oauthProviderTypeToUnlink.getUserNameAttrName(), null);
} else {
log.warn("Social account field to unlink not found");
}
service.getUserProfileHandler().saveUserProfile(userProfile, true);
// Revoke accessToken remotely
if (accessToken != null) {
try {
oauthProviderTypeToUnlink.getOauthProviderProcessor().revokeToken(accessToken);
} catch (OAuthException oe) {
if (OAuthExceptionCode.TOKEN_REVOCATION_FAILED.equals(oe.getExceptionCode())) {
Throwable t = oe.getCause() != null ? oe.getCause() : oe;
ApplicationMessage appMessage = new ApplicationMessage("UIAccountSocial.msg.failed-revoke", null, ApplicationMessage.WARNING);
appMessage.setArgsLocalized(false);
uiApp.addMessage(appMessage);
log.warn("Revocation of accessToken failed for user " + userName + ". Details: " + t.getClass() + ": " + t.getMessage());
} else {
throw oe;
}
}
}
Object[] args = { oauthProviderTypeToUnlink.getFriendlyName(), userName};
ApplicationMessage appMessage = new ApplicationMessage("UIAccountSocial.msg.successful-unlink", args);
appMessage.setArgsLocalized(false);
uiApp.addMessage(appMessage);
prContext.setAttribute(UserProfileLifecycle.USER_PROFILE_ATTRIBUTE_NAME, userProfile);
uiForm.updateUIFields();
prContext.addUIComponentToUpdateByAjax(uiForm);