Question

I am wondering how to add Administrator user to a Grails app on the boot.

Scenario: I developed Grails application and have User permission in place (implemented in Grails). Now once I deploy app on a server, the very first thing it should do is to create Admin user. My question is how to do it? I don't need elaborate "installation" right now.

My thoughts: I figured to put check and admin creation code in bootstrap, here is a sample code:

def admin = User.findByLogin("admin")
if (!admin) {
   admin = new User(login:"admin", name:"Administrator", password:"password")
   admin.save()
}

However everytime I run app in eclipse it fails to do anything. I mean no errors, no movement at all. Application runs fine but it seems like bootstrap is skipped completely.

Question is how do I add Admin user via Grails app on a first run or a boot? If I need to use a bootstrap, what is an issue with my above code?

Was it helpful?

Solution

It's most likely the case that the save() call is failing to validate. Replace admin.save() with

if (!admin.save()) {
    println "Failed to save admin due to errors: $admin.errors"
}

or something similar to get an indication of what's going on. Also add another println before this code to ensure that the code is even running - you may have a more significant error in the code.

In general it's best to run grails clean when code that should work doesn't. It forces a full recompilation and often makes weird behavior go away.

OTHER TIPS

Try this code:

def admin = User.findByLogin("admin")
if (!admin) {
   admin = new User(login:"admin", name:"Administrator", password:"password")
   admin.save(failOnError:true)
}

The flag failOnError force grails to throw exception if save was unsuccessful due to validation errors, without this flag grails will not save instance silently.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top