Actually, I just realized that I should recommend you place this code where we have some similar processing for our Intranet site. In our case, when a user signs in and is automatically created via LDAP, we give them an "employees" role and refresh the role cookie so they can see the site in one step.
So if you move this into a User Sign In Event Handler, the code will run after they sign into mojoPortal, but before the site is displayed, and I think that will work better for you.
Jamie