springSecurityService.principal.id giving firstname instead of userid - grails

I am using springSecurityCore plugin in my application and after user login in the appStartupController, I do like
def index = {
if (springSecurityService.isLoggedIn()) {
session.loginId=springSecurityService.principal.id
def userRole=UserRole.findAllByUserAndRole(User.get(session.loginId), Role.findByAuthority('ROLE_USERSDASH'))
if(userRole){
redirect(controller:'dashboard',action:'getRiskUserDashboard')
}
}
}
when I read session.loginId in the header.gsp I see the firstname from the User table is printed.
I need to have the userId field in the User table mapped to the session.loginId.
How to do that?

You can get the current User by calling the following:
def user = springSecurityService.getCurrentUser()
And then just pass that user into the UserRole find method.

Related

Filtering data based on username

The domain class 'Message' displayed below:
String name
String age
User user
From the following code, i retrieve all the messages that was posted. But what i really want is to display is all messages of a particular user. For example : user.firstName. How can i do it?
def messages = Message.listOrderByDate(order: 'asc', max:1000)
println messages.firstName + " BOOOOOOO "
[messages:messages.reverse()]
So instead of displaying all the data i want to filter the data based on users name. How can this be done ?
It could be queried in the following way:
def results = Message.withCriteria {
user {
eq("name", theUserNameYouWantToQuery)
}
order("date", "asc")
maxResults(1000)
}
This example could be extended to grouping etc. See http://grails.org/doc/latest/ref/Domain%20Classes/createCriteria.html
create as hasMany relationship from user to Message like this:
class User {
static hasMany = [messages: Message]
}
class Message{
String name
String age
static belongsTo [user: User]
}
and then use myUser.messages to fetch all Messages from this user.

Grails/Groovy: Cannot cast object to java.util.Set (twitter clone project)

I am trying to make a follow user like in twitter. I'm getting an exception when I try to save the user of the currently logged in session user.
Error 500: Internal Server Error
URI - /blog-dwit/user/follow/3
Class - org.codehaus.groovy.runtime.typehandling.GroovyCastException
Message - Cannot cast object 'blog.dwit.User : 3' with class 'blog.dwit.User' to class 'java.util.Set'
User domain:
class User {
String email_id;
String password;
Profile profile
static hasMany = [ posts:Post, following: User ]
}
Controller action
def follow(){
def followUser = User.get(params.id)
def user = User.get(session.user)
user.following = followUser
user.save()
}
When adding instances to collections you have to use the addTo* method for the corresponding collection. The documentation explains this in further detail.
Your action should look like this:
def follow(){
def followUser = User.get(params.id)
def user = User.get(session.user)
user.addToFollowing(followUser)
user.save()
}

grails findByDomain returns null

A domain Staff has a User.
class Person {
User user
}
class Staff extends Person {
//other properties
}
class User {
String username
String password
}
I know a user logged in, now I want to find the Staff by the same logged in User. No relation is maintained from User's side.
The code I am implementing is :
def createdBy = User.get(springSecurityService.principal.id)
log.info("User id : "+createdBy.id) // it works
def staff = Staff.findByUser(createdBy) //it returns null
Is this not applicable in GORM or I'm missing something?
grails findBy documentation has nothing to tell about findByDomain().
The question is CLOSED as the error was while inserting a Staff with a User which was not heppening in proper way.(poor grails didn't notify me.)
Above code works perfectly.
def createdBy = User.get(springSecurityService.principal.id)
def staff = Staff.findByUser(createdBy)
But, meanwhile implemented another way of finding Staff in criteria way :
def createdBy = User.get(springSecurityService.principal.id)
def staff = staffCriteria.get{
user{
idEq(createdBy.id)
}
}

Save On My Domain Class Object Is Not Working.

I have a User class which has a List field namely pt. This field is not initialized when User register his account. But when user goes this controller action :
def updatePt() {
//performs some action
def user = User.get(springSecurityService.principal.id) //find the user
user.pt = []
//on certain conditions i put values into user.pt like this
user.pt << "E"
//at last I save it
user.save()
}
But using user/show action via scaffolding I found that pt field is not saved on users object. Where I'm making a mistake?
You have to provide a static mapping in the Users domain class so that Grails knows the field must be persisted:
class User {
static hasMany = [pt: String]
}
It's possible because of validation error. Try with
if (!user.save()) {
log.error('User not saved')
user.errors.each {
log.error('User error: $it')
}
}
PS or you can use println instead of log.error

httpSession in Grails

I need to access the domain class User of the current session. The following code works:
class RatingController {
def rate = {
def rating = params.rating
def artist = Artist.get( params.id )
def user = User.get(1)
user.addToRatings(new Rating(artist:artist, rating:rating))
user.save()
render(template: "/artist/rate", model: [artist: artist, rating: rating])
}
}
But instead of explicitly get the user with ID equal 1 (User.get(1)) I need to access the user of the current session. I tried the following code, but it doesn't work:
class RatingController {
def rate = {
def rating = params.rating
def artist = Artist.get( params.id )
def user = user.session
user.addToRatings(new Rating(artist:artist, rating:rating))
user.save()
render(template: "/artist/rate", model: [artist: artist, rating: rating])
}
}
I'm still struggling to fully understand the httpSession concept, so a little help would be great.
Thank in advance.
UPDATE
In my UserController, my authentication looks like this:
def authenticate = {
def user = User.findByLoginAndPassword(params.login, params.password)
if(user){
session.user = user
flash.message = "Hello ${user.name}!"
redirect(controller:"event", action:"list")
}else{
flash.message = "Sorry, ${params.login}. Please try again."
redirect(action:"create")
}
}
the http session is nothing more than data that is maintained among a sequence of requests from a single source, like a browser.
To put something on the session, just do
session.setAttribute("key", value)
and to get data off the session just do
session.getAttribute("key")
Grails also adds some fanciness to session access as outlined here. Their example shows
def user = session["user"]
session["user"] = "John"
asset "John" == session.user
Note that if you are using a grails plugin for authentication and authorization, it will probably provide a way to get the user. For example Spring Security gives you the following
springSecurityService.getCurrentUser()
depending on the details of your plugin, that user might or might not be on the session.
In your code I noticed you wrote
def user = user.session
When I think you mean
def user = session.user
The other thing I do is make it session.userId ie session.userId = user.id and then
def user = User.get(session.userId)
Not sure if that's necessary.
You'll need to use .merge():
user.merge(flush: true)
This is because the instance is detached from the persistence context when you save it to HttpSession. Here is the doc from grails:
http://grails.org/doc/2.3.1/ref/Domain%20Classes/merge.html

Resources