Reputation: 185
I'm developing an application that requires to restrict data to specific users. I'm using Spring Security Core to handle users management. What I need is to obtain a reference to the logged user in order to make some filtering operations. Consider this code:
class Cliente {
Deposito deposito
String ci
String nombre
String telefono
String celular
static constraints = {
...
}
}
class Empresa {
Deposito deposito
String tipoDeEmpresa
String nombreDeEmpresa
String departamento
String provincia
String municipio
static constraints = {
...
}
}
class SecUser implements Serializable {
private static final long serialVersionUID = 1
Deposito deposito
String nombre
String username
String password
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
...
}
I need help with this fragment of GSP (generated form.gsp
view) code:
<div class="fieldcontain ${hasErrors(bean: clienteInstance, field: 'empresa', 'error')} required">
<label for="empresa">
<g:message code="cliente.empresa.label" default="Empresa"/>
<span class="required-indicator">*</span>
</label>
<g:select id="empresa" name="empresa.id" from="${org.socymet.proveedor.Empresa.findAllByDeposito(loggedUser.deposito,[sort: 'nombreDeEmpresa'])}" optionKey="id" required="" value="${clienteInstance?.empresa?.id}" class="many-to-one"/>
</div>
In the line where the Empresa.findAllByDeposito(loggedUser.deposito,[sort: 'nombreDeEmpresa'])
finder is called I need to replace the loggedUser with an efficient and correct code to obtain the referce to the current logged user.
I was trying to implement a method in the Cliente
domain class but I think it is not a good practice.
Thanks in advance.
Upvotes: 0
Views: 160
Reputation: 3932
You can get the current user using...
<sec:ifLoggedIn>
<sec:username />
</sec:ifLoggedIn>
You can make decisions based on roles like...
<sec:ifAnyGranted roles="ROLE_YOUR_ROLE">
// do stuff
</sec:ifAnyGranted>
Roles are prefixed by default with ROLE_ when accessing like above, this would be restricting based on the role named YOUR_ROLE
Upvotes: 1