2013-10-20 103 views
3

嗨我很难尝试在我的grails引导中添加第一个用户。我尝试了许多不同的方法,但都失败了,因为Audit Trail插件希望用户为createdBy和EditedBy字段加戳,但第一个不会退出。如何在Grails Bootsrap中添加用户以及审计跟踪?

这里是我的审计跟踪配置,它本质上只是我使用User.username在User.id是一样的默认:

grails { 
    plugin { 
     audittrail { 
      createdBy.field = "createdBy" 
      createdBy.type = "java.lang.String" //Long is the default 
      editedBy.field = "editedBy" 
      editedBy.type = "java.lang.String" //Long is the default 
      createdDate.field = "createdDate" 
      editedDate.field = "editedDate" 

      currentUserClosure = {ctx-> 
       def authPrincipal = ctx.springSecurityService.principal 
       if(authPrincipal && authPrincipal != "anonymousUser"){ 
        return authPrincipal.username 
       } else { 
        return null //fall back 
       } 
      } 
     } 
    } 
} 

这里是我的User类的样子,即。我只是添加注释该插件的工作:

@gorm.AuditStamp 
class User { 
    //... basic Spring Security Generated User File with minor changes 
} 

这里是我的引导文件的内容:

def adminUser = new User(
    username: 'admin', 
    enabled: true, 
    password: 'password', 
    firstName: 'ADMIN', 
    lastName: 'ADMIN' 
).save(flush: true) 

// The below will work if I take off the annotation on User class. 
SpringSecurityUtils.doWithAuth('admin') { 
    def adminRole = new Role(authority: 'ROLE_ADMIN').save(flush: true) 
    UserRole.create adminUser, adminRole, true 
} 

所以现在我怎么可以添加第一个用户?我试过了:

- Using annonymousUser 
    - Failed, plugin prevents it 
- Hardcoding the createdBy and editedby to "admin" 
    - Failed get's overridden 
- Use executeUpdate to insert the user directly in the DB 
    - Failed: in bootstrap 
- Delay the save of the first user until the doWithAuth 
    - Failed: couldn't find the user 

任何帮助都会很棒!谢谢!

+0

任何人都可以帮忙吗? –

回答

2

我有同样的问题,正在寻找解决方案。我设法得到它的工作通过执行以下:

grails { 
plugin { 
audittrail { 
createdBy.field = "createdBy" 
createdBy.type = "java.lang.String" //Long is the default 
editedBy.field = "modifiedBy" 
editedBy.type = "java.lang.String" //Long is the default 
createdDate.field = "createdDate" 
editedDate.field = "modifiedDate" 

//custom closure to return the current user who is logged in 
currentUserClosure = {ctx-> 
//ctx is the applicationContext 
def userName = ctx.springSecurityService.principal?.username 
return userName != null ? userName : "System" 
} 
} 
} 
} 

在BootStrap.groovy中的文件,只是做一个像保存:

def adminUser = new User(username: 'admin', enabled: true, password: 'password', 
firstName: 'ADMIN', lastName: 'ADMIN').save(flush: true) 
def adminRole = new Role(authority: 'ROLE_ADMIN').save(flush: true) 
UserRole.create adminUser, adminRole, true 

新创建的第一个用户将与用户进行加盖“系统“(createdBy和modifiedBy列)。

+0

谢谢!我试图与匿名用户做到这一点,但它失败了,我从来没有想过把它改成另一个字符串! –