<%

/*
 * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *                                                                         
 * Licensed under the Apache License, Version 2.0 (the "License");         
 * you may not use this file except in compliance with the License.        
 * You may obtain a copy of the License at                                 
 *                                                                         
 * http://www.apache.org/licenses/LICENSE-2.0                              
 *                                                                         
 * Unless required by applicable law or agreed to in writing, software     
 * distributed under the License is distributed on an "AS IS" BASIS,       
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and     
 * limitations under the License.
 */

include("util/constants.jag");
var util = require("util/utility.jag");

var log = new Log();
var multitenantUtils = Packages.org.wso2.carbon.utils.multitenancy.MultitenantUtils;


var userId = session.get(LOGGED_IN_USER_ID);
if (!userId) {
    var userStoreDomain = PRIMARY_DEFAULT_DOMAIN_NAME;
    var username = session.get(LOGGED_IN_USER);
    if (!username) {
        response.sendError(401);
    }

    var tenantDomain = multitenantUtils.getTenantDomain(username);

// Remove tenant domain from the username.
    username = multitenantUtils.getTenantAwareUsername(username);

// Extract the user store domain from the username, if there is one.
    var usernameTokens = username.split('/');
    if (usernameTokens.length > 1) {
        userStoreDomain = usernameTokens[0];
        username = usernameTokens[1];
    }

    userId = util.getUserId(username, tenantDomain, userStoreDomain);

}

var log = new Log();
var carbon = require('carbon');
var userSessionManagementService = carbon.server.osgiService('org.wso2.carbon.identity.application.authentication.framework.UserSessionManagementService');
var sessionId = request.getParameter("sessionId");

log.debug("Terminating session:" + sessionId + "of userId:" + userId);
userSessionManagementService.terminateSessionBySessionId(userId, sessionId);

%>
