javascriptcoldfusion

Coldfusion not redirecting after login


I have a simple coldfusion app that uses Google Single Sign On. When a user logs in, they should be redirected to the index.cfm page. And their session tokens should be set. However, they keep being redirected back to the login page. I've been troubleshooting this for a while and I'm stuck. I've tried modifying onRequestStart and I can only get a too many redirects error. I just want to get users to the main page after signing in. I must be missing something.

Application.cfc:

<cfcomponent>
    <cfset this.name = "myApp">
    <cfset this.sessionManagement = true>
    <cfset session.email=''>
    <cfset session.loggedIn = false>
            
   <cffunction name="onRequestStart" returntype="void">
    <cfargument name="targetPage" type="string" required="false">
    
    <cfif session.loggedIn EQ "false" AND targetPage NEQ "login.cfm">
        <cflocation url="login.cfm" addtoken="false">
    </cfif>
        
</cffunction>        
</cfcomponent>

login.cfm:

<script>
        
        function decodeJwtResponseFromGoogleAPI(token) {
            var base64Url = token.split('.')[1]
            var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            var jsonPayload = 
           decodeURIComponent(atob(base64).split('').map(function (c) {
                return '%' + ('00' + 
           c.charCodeAt(0).toString(16)).slice(-2);
            }).join(''));
            return JSON.parse(jsonPayload)
        }
    
        function handleCredentialResponse(response) {
            responsePayload = decodeJwtResponseFromGoogleAPI(response.credential);

            email = responsePayload.email;
            
            $.ajax({
                url: 'setSession.cfm',
                type: 'POST',
                data: { email: email },
            });
                window.location.href="index.cfm";
        };
       
            window.onload = function () {
                    google.accounts.id.initialize({
                        client_id: CLIENT_ID,
                        callback: handleCredentialResponse
                    });
                    google.accounts.id.renderButton(
                        document.getElementById('g_id_signin'),
                        { theme: 'outline', size: 'large' }
                    );
                    google.accounts.id.prompt();   
        };
       
    </script>

setSession.cfm:

<cfif structKeyExists(form, "email")>
        <cfset email = form.email>
        <cfset session.loggedIn = true>
        <cfset session.email = email>
</cfif>

Solution

  • I figured it out. onRequestStart runs when any page is accessed. Including the page where I set session variables, setSession.cfm. I just had to add logic to onRequestStart that would skip the redirect while that page was accessed. Otherwise, the session variables weren't getting set first and it was redirecting back to the login page.