Fixes  https://issues.infn.it/jira/browse/VOMS-416

And other refactorings.