How to run query on session end?
Asked Answered
Q

1

6

I have query that should run on session end. If there is record that is tied to user account then I would like to remove that record. I use session scope to store users ID's. Once user manually logs out or their session timed out this query should run. Here is example:

public void function onSessionEnd(required struct sessionScope, struct applicationScope={}) {
    local.qryTest = new Query();
    local.qryTest.setDatasource("#arguments.Application.dsnWriteDelete#");
    local.qryTest.setSQL("DELETE Locked WHERE RecID = :RecID");
    local.qryTest.addParam(name="RecID",value="#SESSION.userID#",cfsqltype="cf_sql_integer");
    qryTest.execute();

    return; 
} 

I use J2EE sessions in my application. Here is how I end my session when user logs out manually:

<cffunction name="LogOut" access="remote" output="yes" returnformat="JSON">
        <cfset local.fnResults = structNew()>

        <cfif structKeyExists(SESSION.AccountInfo, "AccountID")>
            <cftry>
                <cfset local.temp = getPageContext().getSession().invalidate()>
                <cfset local.fnResults = {status : "200"}>

                <cfcatch type="any">
                    <cfset local.fnResults = {status : "400", message : "Error! Please contact your administrator."}>
                </cfcatch>
            </cftry>
        <cfelse>
            <cfset local.fnResults = {status : "400", message : "Error! Please contact your administrator."}>
        </cfif>

        <cfreturn fnResults>
    </cffunction>

I'm not sure if onSessionEnd works any different with J2EE but code that I have above never deletes records from database table. I'm not sure if something is wrong in my code or this is not possible to achieve on session end.

Quarterhour answered 27/8, 2018 at 20:3 Comment(3)
In onSessionEnd, session isn't available. You have to use the argument name instead - i.e. arguments.sessionScopeStew
@Ageax I fixed that and if session times out query will be processed. However, if user logs out manually then onSessionEnd is not triggered. Do you know if it's possible to manually trigger onSessionEnd int hat case?Quarterhour
@espression_coffee - Technically yes, though I think it probably makes more sense to have the logout logic in a component and then call the appropriate method from both locations.Stew
S
4

The session scope isn't available inside OnSessionEnd(). You must use the argument name instead, i.e. arguments.sessionScope

However, if user logs out manually then onSessionEnd is not triggered. Do you know if it's possible to manually trigger onSessionEnd int [t]hat case?

Technically yes, though it probably makes more sense to place the logout logic in a component and then call the appropriate method from both locations (OnSessionEnd and manual logout script).

Stew answered 28/8, 2018 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.