Mantas
Mantas

Reputation: 3249

Multiple Roles for a single User

The Following Code Adds Multiple Roles to a Single user, it also should be noted that this will only work for a single session as we're trying to define the roles and users every time we start the app, to prevent any crashes due to that add a check for the database and create the roles and user IF they don't exist.

import trippinspring.*

class BootStrap {

def init = { servletContext ->

  def adminRole = new SpringRole(authority: 'ROLE_ADMIN').save(flush: true)
  def userRole = new SpringRole(authority: 'ROLE_USER').save(flush: true)

  def testUser = new SpringUser(username: 'me', enabled: true, password: 'password')
  testUser.save(flush: true)

if (!testUser.authorities.contains(adminRole)) {
new SpringUserSpringRole(springUser: testUser, springRole: adminRole).save(flush: true,failOnError: true)
}

if (!testUser.authorities.contains(userRole)) {
new SpringUserSpringRole(springUser: testUser, springRole: userRole).save(flush: true,failOnError: true)
}
}
}

Most of the code is a direct reference to Aram Arabyan's answer, and Ian Roberts comments with some fixes to work with my code.

Upvotes: 0

Views: 854

Answers (2)

16dots
16dots

Reputation: 3080

Just a suggestion, maybe you should try creating a hierarchy for your roles instead of adding two roles for a single user: see doc.

Upvotes: 0

Aram Arabyan
Aram Arabyan

Reputation: 2359

  if (!testUser.authorities.contains(adminRole)) {
    new SpringUserSpringRole(user: testUser, role: adminRole).save(flush: true,failOnError: true)
  }

 if (!testUser.authorities.contains(userRole)) {
    new SpringUserSpringRole(user: testUser, role: userRole).save(flush: true,failOnError: true)
  }

Upvotes: 1

Related Questions