Recovering the logged-in user in JS


From Ametys 4.3

As of Ametys 4.3, it is possible (and recommended) to retrieve the logged-in user at javascript using the JS getAmetysUser function.

This makes it possible, for example, to display a login button and/or user menu on public pages and pages that can be laid out.

The getAmetysUser function is used in conjunction with a callback function. The callback function receives :

  • null if no user is logged in
  • either a JSON object representing the logged-in user (with login, name, first name, mail, ...)

Here's an example of HTML/JS code that displays a "Login" button if no user is logged in, or a menu with the user's name and a logout button.

<ul class="ametys-header-profile-menu"> 
    <li id="userConnectItem" style="display: none"> 
        <a class="ametys-header-connect-btn" href="{ametys:siteUriPrefix()}/_authenticate?requestedURL={ametys:siteUriPrefix()}/{$lang}/{$sitemap//page[@sitemap:current = 'true']/@sitemap:path}.html">Se connecter</a> 
    </li> 
    <li id="userMenuItem" style="display: none"> 
        <a id="profileMenuInvoker" data-dropdown-target="#profileMenu"> 
            <span class="ametys-header-profile-menu__item-text"></span> 
            <span class="ametys-dropdown-invoker__icon ametys-icon-angle-down"></span> 
        </a> 
        <div id="profileMenu"> 
            <ul class="ametys-dropdown-menu"> 
                <li class="ametys-dropdown-menu__item"> 
                    <a href="{ametys:siteUriPrefix()}/logout.html?requestedURL={ametys:siteUriPrefix()}/{$lang}/index.html">Se déconnecter</a> 
                </li> 
            </ul> 
        </div> 
    </li> 
</ul> 

<script type="text/javascript"> 
    $j(document).ready(function() { 
        var _getAmetysUserCb = function(user) 
        { 
            if (user) 
            { 
                $j('#userMenuItem').find('.ametys-header-profile-menu__item-text').html(user.fullname); 
                $j('#userMenuItem').show(); 
                $j('#userConnectItem').hide(); 
            } 
            else 
            { 
                $j('#userMenuItem').hide(); 
                $j('#userConnectItem').show(); 
            } 
        } 

        getAmetysUser(_getAmetysUserCb); 
    }); 
</script> 
Back to top