Daniel T.
Daniel T.

Reputation: 38400

How do I programmatically change a user's password as an admin using Grails Spring Security?

I need to be able to change a user's password as an admin user, sort of like a manual password reset feature that can be performed over the phone. How would I do this using the Grails Spring Security plugin? I tried looking for documentation on how this can be accomplished but didn't come up with anything.

Upvotes: 2

Views: 1303

Answers (2)

Burt Beckwith
Burt Beckwith

Reputation: 75671

@AA's answer is technically correct, but over-generic because the plugin has to be configuration-based. The real code would be a lot more compact since you can hard-code the class and field names. Also since you only asked to update the password, the role updates at the end aren't relevant.

If your user class name is User then use this action to display the user information:

def editUserPassword() {
   [user: User.get(params.userId)]
}

and configure the form in the GSP (it'd be similar to the generated edit.gsp) to post to this action:

def updateUserPassword() {
   def user = User.get(params.userId)
   user.password = params.newPassword
   if (!user.save())
      render view: 'editUserPassword', model: [user: user]
      return
   }

   // redirect to the 'success' page or render the user with [user: user]
}

Change userId and newPassword to whatever parameter names you're actually using

Upvotes: 4

AA.
AA.

Reputation: 4606

You can use spring-security-ui plugin or you can see its source code and learn how:

def update = {
    String passwordFieldName = SpringSecurityUtils.securityConfig.userLookup.passwordPropertyName

    def user = findById()
    if (!user) return
    if (!versionCheck('user.label', 'User', user, [user: user])) {
        return
    }

    def oldPassword = user."$passwordFieldName"
    user.properties = params
    if (params.password && !params.password.equals(oldPassword)) {
        String salt = saltSource instanceof NullSaltSource ? null : params.username
        user."$passwordFieldName" = springSecurityUiService.encodePassword(params.password, salt)
    }

    if (!user.save(flush: true)) {
        render view: 'edit', model: buildUserModel(user)
        return
    }

    String usernameFieldName = SpringSecurityUtils.securityConfig.userLookup.usernamePropertyName

    lookupUserRoleClass().removeAll user
    addRoles user
    userCache.removeUserFromCache user[usernameFieldName]
    flash.message = "${message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), user.id])}"
    redirect action: edit, id: user.id
}

Upvotes: 1

Related Questions