Search code examples
javascriptjspspring-securitydatatablesjsp-tags

Hide buttons in Datables for non-authorized users with Spring Security


I need to hide buttons in Datables for non-authorized users.

In plain jsp I was used spring security tags to hide elements for non-authorized users.

E.g. hide delete button:

<sec:authorize access="hasRole('ROLE_ADMIN')"> <a href="delete/${author.id}">Delete</a></sec:authorize>

But in jquery datatables, buttons are come from inner javascript config. And I can't use spring security tags. E.g. delete button in DataTables:

"buttons": [
{
    text: "Delete",
    action: function (e, dt, button, config){
        //button onClick here
    }
}
]

Solution

  • Here's an example:

    var authStatus = true; //your auth status variable from JSP
    
    var buttons = [];
    
    if (authStatus) {
        buttons = [
            {
                text: "Delete",
                action: function(e, dt, button, config) {
                    //button onClick here
                }
            }
        ];
    }
    
    $('#example').DataTable({
        dom: 'Bfrtip',
        buttons: buttons,
    });
    

    You could instead write it inline with a ternary operator, but it won't be as clear.