user1854751
user1854751

Reputation: 107

Getting a meaningful String using Groovy Spring security getCurrentUser

My Code to gather a string for the current user looks like this.

package timetracker2

import grails.timesecurity.*
import timetracker2.TimeController

class Time {

   def springSecurityService

   int id
   Project projectname
   Date dateCreated
   Date dateWorked
   Double timeSpent
   TimeClassification classification

   String currentUser = {
      String currentUser = springSecurityService.getCurrentUser()
      def user = springSecurityService.getCurrentUser()
      String username = user
      return username
   }

   static constraints = {
      timeSpent blank: false
      classification blank: true
   }

   static mapping = {
      table 'Time'
      cache true
      id column: 'Time_id'
      dateCreated column: 'Date_created'
      dateWorked column: 'Date_Worked'
      timeSpent column: 'Time_Spent'
      currentUser column: 'Username'
   }
}

this is the string that I get out.... timetracker2.Time$_closure1@108115

What is up with that???? Any help would be very much appreciated.

I have tried using get authorisation as well, and I have tried to add a toString method in my person class. Alas no success.

Upvotes: 0

Views: 352

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122414

I suspect part of the problem here is that you're trying to use springSecurityService before it has been set. The initializer expression in the declaration

String currentUser = springSecurityService.getCurrentUser()

runs when the object is constructed, but the springSecurityService reference is null at this point as it only gets injected after the constructor has finished. You could put the code that refers to springSecurityService into a beforeInsert event instead, which would delay the call until the point where the object is first saved to the DB. And you probably want principal.username instead of getCurrentUser() (thanks to Burt Beckwith for the pointer)

class Time {
  def springSecurityService

  String currentUser
  // other fields...

  def beforeInsert() {
    currentUser = springSecurityService.principal.username
  }

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 692181

You're initializing the currentUser variable with the result of calling toString() on a closure which, when invoked, returns the current user.

What you want is

String currentUser = springSecurityService.getCurrentUser()

which initializes the currentUser variable with the value returned by springSecurityService.getCurrentUser().

Upvotes: 0

Related Questions