Installed the latest spring-security-core plugin for grails 2.1.0, launched s2-quickstart com.myapp User Role, it create User Role and UserRole domain, then generate-all com.myapp.User and com.myapp.Role to build basic CRUD. Now i'm trying to create a "Register" button to allow new users to sign in, using the User create() method, the problem is that when creating a new User, this one comes without Role, i'm trying to auto-assignate 'ROLE_USER' to every new user that register through the 'register' button and form.
Any help or suggestion is most welcome.
Add this in the controller action after checking that the user creation was successful:
def roleUser = Role.findByName('ROLE_USER')
UserRole.create user, roleUser, true
I've been doing something like this in one of my apps. I've used
generate-all mypackage.User
User was class which extends SecUser (domain object created by Spring Security Core). I add this code to UserController:
def springSecurityService // injection of Spring Security
def create() {
def user = springSecurityService.getPrincipal()
[userInstance: new User(params)]
}
def save() {
def map=params
def userInstance = new User(params)
if (!userInstance.save(flush: true)) {
render(view: "create", model: [userInstance: userInstance])
return
}
if (!userInstance.authorities.contains(SecRole.findByAuthority(params.role))) {
SecUserSecRole.create userInstance, SecRole.findByAuthority(params.role)
}
flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
redirect(action: "show", id: userInstance.id)
}
In BootStrap class I've made some roles:
def springSecurityService
def init = { servletContext ->
def userRole = SecRole.findByAuthority('ROLE_USER') ?: new SecRole(authority: 'ROLE_USER').save(failOnError: true)
def adminRole = SecRole.findByAuthority('ROLE_ADMIN') ?: new SecRole(authority: 'ROLE_ADMIN').save(failOnError: true)
def moderatorRole = SecRole.findByAuthority('ROLE_MODERATOR') ?: new SecRole(authority: 'ROLE_MODERATOR').save(failOnError: true)
}
In user/_form.gsp template I've added this select to select role and send it in params
<sec:ifAllGranted roles="ROLE_ADMIN">
<g:select name="role" from="${['ROLE_USER', 'ROLE_MODERATOR', 'ROLE_ADMIN']}" value='ROLE_MODERATOR'/>
</sec:ifAllGranted>
<sec:ifNotLoggedIn>
<div class="hidden"><g:textField name="role" value="ROLE_USER"/></div>
</sec:ifNotLoggedIn>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With