3

嗨,我很难在我的 grails 引导程序中添加第一个用户。我尝试了许多不同的方法,但都失败了,因为 Audit Trail 插件希望用户标记 createdBy 和 EditedBy 字段,但第一个还没有退出。

这是我的 Audit Trails 配置,基本上它与默认配置相同,除了我在 User.id 上使用 User.username:

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
                }
            }
        }
    }
}

这是我的用户类的样子,即。我只是添加了插件的注释来工作:

@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

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

4

1 回答 1

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 列)。

于 2014-03-24T10:28:58.490 回答