Search code examples
grailsspring-securitygrails-orm

Grails Spring Security creating account that's not in bootstrap.groovy


By default Spring Security gives you three domain classes User, Role, and UserRole. I can easily make accounts in my bootstrap.groovy file in Grails 2.4.4 doing this

User admin = new User(username:'admin', password:'secret', enable:true, accountExpired:false, accountLocked:false, passwordExpired:false).save();
Role a = new Role(authority:'ROLE_ADMIN').save()
UserRole.create(admin, a);

but how in the world do you create one when in the session?

I have made classes that extend User, Role, and UserRole. I am able to save a new Role and a User, but I'm not able to save the relationship between them.

I realize this must have something to do with UserRole.create instead of save that User and Role use, I can't find any documentation on it because everyone just uses Bootstrap.


Solution

  • I have solved the problem. If you run s2-quickstart you cannot use the relation domain class for anything. Say we make three classes User, Role, and UserRole. UserRole is only good for its methods. If you make a class that extends User, in my case SystemUser we can map the role to System user like so...

    class SystemUser extends User
    {
    
    static belongsTo = [role:Role]
    
    static constraints = {}
    
    }
    

    Then if we run a 'generate-all' for the SystemUser class we then modify the controller for SystemUser in the save section. Right under where the Instance is saved, you can easily assign a role. The code that assigns the user role is the key. You can then put the Roles in the boot strap or in the app.

     def save(SystemUser systemUserInstance) {
        if (systemUserInstance == null) {
            notFound()
            return
        }
    
        if (systemUserInstance.hasErrors()) {
            respond systemUserInstance.errors, view:'create'
            return
        }
    
        systemUserInstance.save flush:true
    
        //The code that assigns the Users Roles
        Role b = systemUserInstance.role;
        UserRole.create(systemUserInstance,b);
    
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'systemUser.label', default: 'SystemUser'), systemUserInstance.id])
                redirect systemUserInstance
            }
            '*' { respond systemUserInstance, [status: CREATED] }
        }
    }