0
votes

I am getting a strange exception on worklight server stating Procedure invocation error. Illegal State: Cannot change identity of an already logged in user in realm 'SingleStepAuthRealm'. The application must logout first. I am implementing Adapter Authentication using Single step. Posting all codes please help me to understand where i am messing up. ************************************SingleStepAuthAdapter-impl.js***************************

function onAuthRequired(headers, errorMessage){
    WL.Logger.debug("Inside adapter.js onAuthRequired");
    errorMessage = errorMessage ? errorMessage : null;

    return {
        authRequired: true,
        errorMessage: errorMessage
    };  
}

function loginAuthentication(username, password,returnvalue){

    WL.Logger.debug("Inside loginAuthentication");

    var returned = WL.Server.invokeSQLStoredProcedure({
        procedure : "loginAuthentication",
        parameters : [username,password,returnvalue]
    });

    var isAuth = (returned.resultSet[0].returnvalue == 1);

    if (isAuth){
        //WL.Logger.debug("Inside loginAuthentication Authentication Successful "+JSON.stringify(WL.Server.getActiveUser("SingleStepAuthRealm")));

        var userIdentity = {
                userId: username,
                displayName: username
        };

        WL.Server.setActiveUser("SingleStepAuthRealm", userIdentity);   

        return {            
            authRequired: false 
        };
        WL.Logger.debug("Inside loginAuthentication Authentication Successful returned authRequired false");
}

    return onAuthRequired(null, "Invalid Login Credentials");
}

function getSecretData(){
    WL.Logger.debug("Inside adapter.js getSecretData");
    return {
        secretData: "Authentication Done and its a secret data"
    };
}

function onLogout(){
    WL.Logger.debug("Inside adapter.js onLogout");
    WL.Server.setActiveUser("SingleStepAuthRealm", null);
    WL.Logger.debug("Logged out");
}

*************************************SingleStepAuthRealmChallengeProcessor.js***********

var singleStepAuthRealmChallengeHandler = WL.Client.createChallengeHandler("SingleStepAuthRealm");

singleStepAuthRealmChallengeHandler.isCustomResponse = function(response) {
    console.log("Inside singleStepAuthRealmChallengeHandler.isCustomResponse "+response +" :: "+ !response.responseJSON +" :: "+ response.responseText);
    if (!response || !response.responseJSON || 
            response.responseText === null) {
        return false;
    }
    console.log("Inside response.responseJSON.authRequired "+response.responseJSON.authRequired);
    if (typeof(response.responseJSON.authRequired) !== 'undefined'){
        return true;
    } else {
        return false;
    }
};

singleStepAuthRealmChallengeHandler.handleChallenge = function(response){

    var authRequired = response.responseJSON.authRequired;
    WL.Logger.debug("Inside singleStepAuthRealmChallengeHandler.handleChallenge :: response.responseJSON.authRequired ");

    /*if(WL.Client.isUserAuthenticated("SingleStepAuthRealm") == false)
    {
        WL.Client.logout("SingleStepAuthRealm");
    }*/

    if (authRequired == true){
        WL.Logger.debug(" Inside authRequired == true");

        // 1.b else display up login screen
        console.log("Login Returned false");
        alert("Already Registered, Please login to continue");
        $("#pagePort").load(path + "pages/Login.html", function() 
                {
                    $.getScript(path+ "js/Login.js",function() {
                        if (currentPage.init) 
                        {
                            currentPage.init();
                        }
                        });
                        //$.getScript(path+ "js/SingleStepAuthRealmChallengeProcessor.js",function() {});
                                });

        if (response.responseJSON.errorMessage)
            {
            alert("Problem "+response.responseJSON.errorMessage);
            }

    } 
    else if (authRequired == false)
    {   


        WL.Logger.debug(" Inside authRequired == false "+WL.Client.isUserAuthenticated("SingleStepAuthRealm"));


        var userName = "Random";//loginResultArr[0].json.uName;
        console.log("Username "+ userName);
            // 1.a if login data exists directly go to home page see
            console.log("Login Returned true");
            appUsernameGlobal = userName;
            $("#pagePort").load(path+ "pages/MainMenu.html",function() {
                $.getScript(path+ "js/MainMenu.js", function() {
                    if (currentPage.init) {
                        currentPage.init();
                        }
                        });
                });

        singleStepAuthRealmChallengeHandler.submitSuccess();
    }
};


function loginClick() {
    WL.Logger.debug(" Inside AuthSubmitButton");
    var username = $("#init-username").val();
    var password = $("#init-password").val();
    var returnvalue = 0;

    var invocationData = {
        adapter : "SingleStepAuthAdapter",
        procedure : "loginAuthentication",
        parameters : [username, password,returnvalue]
    };

    WL.Logger.debug(" before submitAdapterAuthentication");
    singleStepAuthRealmChallengeHandler.submitAdapterAuthentication(invocationData, {onSuccess: getLoginAuthenticationOK, onFailure: getLoginAuthenticationFAIL});
    WL.Logger.debug(" after submitAdapterAuthentication");

}


function getLoginAuthenticationOK(response){
    WL.Logger.debug("Inside SingleStepAuthenticationRealmChallenge.js getLoginAuthenticationOK :: secret data is :: " + JSON.stringify(response.invocationResult));
}  

function getLoginAuthenticationFAIL(response){
    WL.Logger.debug("Inside SingleStepAuthenticationRealmChallenge.js getLoginAuthenticationFAIL "+JSON.stringify(response.invocationResult));
}

*****************************SingleStepAuthAdapter.xml********************************

<?xml version="1.0" encoding="UTF-8"?>

<wl:adapter name="SingleStepAuthAdapter"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:wl="http://www.worklight.com/integration"
    xmlns:sql="http://www.worklight.com/integration/sql">

    <displayName>SingleStepAuthAdapter</displayName>
    <description>SingleStepAuthAdapter</description>
    <connectivity>
        <connectionPolicy xsi:type="sql:SQLConnectionPolicy">
            <dataSourceDefinition>
                <driverClass>com.mysql.jdbc.Driver</driverClass>
                <url>jdbc:mysql://192.168.xx.xx:3306/project</url>
                <user>root</user>
                <password>root</password>
            </dataSourceDefinition>         
        </connectionPolicy>
        <loadConstraints maxConcurrentConnectionsPerNode="10" />
    </connectivity>

    <procedure name="loginAuthentication"/>
    <procedure name="getSecretData" securityTest="SingleStepAuthAdapter-securityTest"/>     

</wl:adapter>

In Worklight - How to check if a client is already logged in, then pass the login screen its said to setActive user as null but setting null before provokes Server to go in infinite loop. And i want to understand if i am not setting any active user than why server saying the app must logout first ? I tried my level best but not getting my problem's soln.

{"errors":["Illegal State: Cannot change identity of an already logged in user in realm 'SingleStepAuthRealm'. The application must logout first."],"isSuccessful":false,"warnings":[],"info":[]} 
1
Can you please provide a sample project demonstrating this infinite loop, as well as mention Where are you testing the app (device? simulator? preview?) - Idan Adar
IDan: I just got it working. Actually, i was waiting for you reply here. :P. I am posting answer soon. Please provide your comment as my answer has nothing to do with Worklight. And just now one of the IBM Technical guy mailed me stating "The Javascript references only need to be made in the main index.html file" - Pawankumar Dubey
Idan Adar: Well that Infinite loop was coming on Simulator, since i had doubt with my code i didn't gone ahead for actual devices. But Issue for Illegal State: Cannot change identity of an already logged in user was coming on Real Devices. I tried on Moto-E and client provided Android hardware(Cant disclose client project name) :D. But now its resolved may be inclusion of that handler.js file was sending request to server at random and server wasnot expecting it and returned Illegal State: Cannot change identity of an already logged in user. - Pawankumar Dubey
Thanks. Please provide this as the answer for the question. - Idan Adar

1 Answers

1
votes

I had files i.e. Registration.html, Login.html and Index.html. Here, I had included "SingleStepAuthRealmChallengeProcessor.js" in all of the file like <script src="js/ SingleStepAuthRealmChallengeProcessor.js"></script>

So, just to try different I removed this from Registration.html and Login.html files ONLY and re-ran this. And it worked like charm.

It may be inclusion of this SingleStepAuthRealmChallengeProcessor.js file was sending request to server at random and server was not expecting it and returned Illegal State: Cannot change identity of an already logged in user.

Just now i came to know via IBM techical guy that js references needs to be done only @ Index.html