<%

var login = function (username, password,tenantMode) {
    var result, isSuperTenant, message,
            log = new Log();

try{
    if(tenantMode != 'null' && tenantMode != '' && tenantMode != null){
     var userDomain=username.split("@")[1];
     if(tenantMode!=userDomain){
     return {
             error:true,
            cookie:null,
            message:"Authentication failed."+username.split("@")[0]+" is not from the tenant domain " + tenantMode
        };
    }
    }


    var xhr = new XMLHttpRequest();
    var store = jagg.module("manager").getAPIStoreObj();
    var endpoint =  store.getAuthServerURL()+"AuthenticationAdmin";
    xhr.open("POST", endpoint);
    xhr.setRequestHeader('SOAPAction','urn:login');
    xhr.setRequestHeader('Content-Type','application/soap+xml');
    var payload = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:aut="http://authentication.services.core.carbon.wso2.org"><soap:Header/><soap:Body><aut:login><aut:username>' +  username + '</aut:username><aut:password>' + password + '</aut:password><aut:remoteAddress>localhost</aut:remoteAddress></aut:login></soap:Body></soap:Envelope>';
    xhr.send(payload);
    var cookie = (xhr.getAllResponseHeaders());

   var result=xhr.responseText.toString();
   var start=result.indexOf("ns:return");
   var end=result.indexOf("</ns:return");
   var isLogged=result.substring(start,end).split(">")[1];

   var isAllowed=isUserAllowed(username,password);
   if(isAllowed){
   getWorkflowCookie(username,password);
   if (isLogged=='false') {
        if (log.isDebugEnabled()) {
            log.debug("Error while authenticating user : " + username);
        }

        message = "Login Failed.";

        return {
            error:true,
            cookie:null,
            message:message
        };
    }else{
    isSuperTenant =tenantMode;
    var sessionCookie = xhr.getResponseHeader("Set-Cookie");//cookie.split(';')[0];
    jagg.setUser({username:username, isSuperTenant:isSuperTenant, cookie:sessionCookie, userDomain : username.split("@")[1]});


    return {
        error:false,
        cookie:sessionCookie
    };
    }
}else{
     return {
            error:true,
            cookie:null,
            message:"Login Failed."
        };

}}
catch (e) {
        log.error(e.message);
 return {
        error:true,
        message:e.message.split("Exception:")[2]
    };
}
};
var loginWithSAMLToken = function (token) {
    var site = require("/site/conf/site.json");
    var security =require("sso");
    var ssoRelyingParty = new security.SSORelyingParty(site.ssoConfiguration.issuer);

    var result,
            log = new Log(),
            manager = jagg.module("manager"),
            store = manager.getAPIStoreObj();


    var encodedToken = ssoRelyingParty.xmlEncode(token);
    var xhr = new XMLHttpRequest();
    var endPoint = manager.getHTTPsURL() + "/services/SAML2SSOAuthenticationService";
    xhr.open("POST", endPoint);

    var payload = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sso="http://sso.saml2.authenticator.identity.carbon.wso2.org" xmlns:xsd="http://dto.sso.saml2.authenticator.identity.carbon.wso2.org/xsd"><soap:Header/><soap:Body><sso:login><sso:authDto><xsd:response>'+encodedToken+'</xsd:response></sso:authDto></sso:login></soap:Body></soap:Envelope>';

    xhr.send(payload);
    var cookie = (xhr.getAllResponseHeaders());

   // var cookieString = cookie.split(";")[0].split(":")[1];
   var cookieString = xhr.getResponseHeader("Set-Cookie");
    var userName = ssoRelyingParty.getSAMLResponseNameId(token);
    getWorkflowCookie(username,password);

    return {
        error:false,
        username:userName,
        cookie:cookieString
    };
};

var logout = function () {
    //TODO : implement logout
     session.put("createPermitted", null);
     session.put("publishPermitted", null);
    return {
        error:false
    };
};

var getWorkflowCookie=function(username,password){
var log=new Log();
try{
var xhr = new XMLHttpRequest();
var site = require("/site/conf/site.json");
var endpoint =  site.workflows.applicationWorkFlowServerURL+"AuthenticationAdmin";
xhr.open("POST", endpoint);
var payload = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:aut="http://authentication.services.core.carbon.wso2.org"><soap:Header/><soap:Body><aut:login><aut:username>' +  username + '</aut:username><aut:password>' + password + '</aut:password><aut:remoteAddress>localhost</aut:remoteAddress></aut:login></soap:Body></soap:Envelope>';
xhr.send(payload);
var cookie = (xhr.getAllResponseHeaders());
//session.put("workflowCookie",cookie.split(";")[0].split(":")[1]);
var sessionCookie =  xhr.getResponseHeader("Set-Cookie");
session.put("workflowCookie",sessionCookie);
}catch (e) {
        log.error(e.message);

}};

var isUserAllowed=function(username,password){
var log=new Log();
try{

var version = new ws.WSRequest();
var options = new Array();
options.useSOAP = 1.2;
options.action = "urn:getRoleListOfUser";
var store = jagg.module("manager").getAPIStoreObj();
var isEmailLoginEnabled=store.isEnableEmailUsername();
var checkedUserName=username;
if(!isEmailLoginEnabled && (username.indexOf("@") != -1)){
checkedUserName=username.split("@")[0];
}
if(isEmailLoginEnabled) {
  var email = username.split("@")[1];
  if(email != null) {
    checkedUserName=username.split("@")[0] + "@" + email ;
  }
}
var endpoint =  store.getAuthServerURL()+"RemoteUserStoreManagerService/";
var payload = '<ser:getRoleListOfUser xmlns:ser="http://service.ws.um.carbon.wso2.org">'+
              '<ser:userName>'+checkedUserName+'</ser:userName></ser:getRoleListOfUser>';
version.open(options,endpoint, false,username,password);
version.send(payload);
result = version.responseE4X;

return parseRolesResponse(result);
}catch (e) {
        log.error(e.message);
        return false;

}};


var parseRolesResponse=function parseResponse(result){
var site = require("/site/conf/site.json");
var roles= result. *::["return"];
for(var i=0; i<roles.length(); i++){
 var entry=roles[i];
var roleName= entry.text();
var approvedRole;
var roleNames = site.allowedRoles.split(",");
var count = roleNames.length;
for(var j=0; j < count ; j++ ){
  approvedRole = roleNames[j];
  if(approvedRole==roleName) {
     return true;
  }
}
}
return false;
};

%>
