* @param user Existing user
* @param roleName Role name
*/
public void addRole(AuthUser user, String roleName) {
AuthRoleRepo roleRepo = JuDbUtils.getJpaRepository(this.em, AuthRoleRepo.class);
AuthUserRepo userRepo = JuDbUtils.getJpaRepository(this.em, AuthUserRepo.class);
// Check if the role exists
AuthRole role = roleRepo.getByName(roleName);
if (role == null) {
role = new AuthRole();
role.setName(roleName);
this.em.persist(role);
}
// Check if the role has already been assigned to the user
if (roleRepo.getByNameAndUsersId(roleName, user.getId()) == null) {
// Role hasn't been assigned, so do it
user.getRoles().add(role);
role.getUsers().add(user);
userRepo.save(user);
roleRepo.save(role);
}
}