How to access User object in grails controller - grails

I'm using spring security, and I need to get the User domain object in a controller.
If I call SpringSecurityService.getPrincipal(), I get back an object of type org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser. However, what I'm looking for is the User domain object I've defined in my Config.groovy like so:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'project.auth.User'
How can I best get at the User domain object?

Load the user instance using the cached id in the GrailsUser instance:
def user = User.get(SpringSecurityService.principal.id)

Related

Session variables in MVC 5

I have a question about using Sessions in MVC.
After the user validated and before going to the index page, from the login controller I save some data into a session variable as follows:
Session["user"] = new User() { usrNme = name, usrFirstName = dataset.usrFirst, usrLastName = dataset.usrLast };
Where User is a model that represents database table. My question is, what is the best way to display only first name usrFirstName in the index page?
Thank you
You can retrieve the user object from the session like this :
User objectName = (User) Session["user"];
Note: while retrieving an object from session its important to cast
it to the object type
Then access the object to get its properties.
objectName.usrFirstName

Using session variable in another session grails 2.4.2

I am using grails 2.4.2 and I want to use session value from another session is this possible ? case is :
i have a user when user is logged in and updates his profile then super admin will get notification for updated profile. For that purpose I have set variable as
String notification = session.count
session.count =Integer.parseInt(notification) + verify
where verify is the value of the updated profile
Now when superadmin is logged in I want to get the session.count variable at the menu page is this possible without using session filters how?
No, the sessions are isolated. If you want to access the state set by one user from the session of another one, you have to use a more or less persistent storage:
You could store your vars in a DB or use a service with a e.g. ConcurrentHashMap:
class CrossContextService {
ConcurrentHashMap cache
}
class SomeController{
def crossContextService
def someAction(){
crossContextService.cache.count = ...
}
}

grails and spring security acl: show only some instances of a domain class

I'm using Spring Security ACL in my Grails project to manage access into my application. I can create Admin and User to have different permissions into the application.
Now, I want that a particular user can see only some instances of a domain class object. That is:
following the example domain class object
class Patient
{
String name;
String surname;
...
}
Suppose that there are 3 created Patient objects.
I want that, if I login with
username = test1
password=test1
I can see only Patient that belongs to this User.
I think that is needed that, when I create a new Patient, it is stored that this Patient belongs to the User currently logged.
How can I do that?
EDIT:
Another problem is that, if I change the URL in the part of id to show, I can see all the Patient that are created. I want that, if I change URL manually, I see an access error. Is it possible?
EDIT 2:
How can I get the role of the user currently logged in? I've tried with the following code How to get current user role with spring security plugin? but I cannot perform the getAuthorities() because it tells me that it does not exists
I've solved EDIT2 in the following discussion grails exception: Tag [paginate] is missing required attribute [total]
I need to solve the EDIT1
thanks
If I understand you right you need to define belongsTo. This will create mapping in database from Patient to User.
Edit: to get current logged in user use
class SomeController {
def authenticateService
def list = {
def user = authenticateService.principal()
def username = user?.getUsername()
.....
.....
}
}
To map to user change logic in controller or use events to create mapping
Edit: edit create action:
class PatientController {
def authenticateService
...
def create() {
def patientInstance = new Patient(params)
patientInstance.user = authenticateService.principal()
...
[patientInstance: patientInstance]
}
...
}

Grails - passing domain classes between controllers

In my Grails application, I have created a User class. In one controller, I query the database to confirm that the information a user has given is valid. Then, I would like to pass that User object to another controller to do some more processing on it. Is this possible? Thanks!
For your question on passing objects between controllers, if you are using a redirect or a forward you can add objects in the param map:
redirect(action: "actionName", user: userInstance)
or
forward(action: "actionName", user: userInstance)
Another solution would be to store the user in the flash object (a temporary storage map cleared after the next request) or session:
flash.user = userInstance
or
session.user = userInstance
But in your case, as stated by tim_yates, you should create a service to handle the User entity.
To do so execute the command:
create-service com.package.user
Then add all the processing you are doing on a User in the newly created class and inject the User service in your controller like this:
def controller{
def userService
def action(){
userService.validate(...)
}
}
Essentaily what #tim_yates was getting at was the logic for all of your controllers should be in services. Then any action in any controller can execute that logic without redirecting/forwarding a request. This also is the way it should be due to the transactional nature of services.

How to get current user role with spring security plugin?

I am using the spring-security-core plugin in my grails app. I need to know the current user's role in a controller action. How can I retrieve that?
You can inject springSecurityService into your controller:
def springSecurityService
and then in your action, call:
def roles = springSecurityService.getPrincipal().getAuthorities()
See the docs here.
From a controller you can use two methods the plugin adds to the metaclass, getPrincipal and isLoggedIn:
def myAction = {
if (loggedIn) {
// will be a List of String
def roleNames = principal.authorities*.authority
}
}
If the action is secured you can skip the loggedIn/isLoggedIn() check.
If you simply need to check to see if a user is in a specific role then use SpringSecurityUtils.ifAllGranted which takes a single String as an argument which contains a comma-delimited list of roles. It will return true if the current user belongs to all of them. SpringSecurityUtils also has methods like ifAnyGranted, ifNotGranted, etc, so it should work for whatever it is you are trying to accomplish.
To get the user
def springSecurityService
def principal = springSecurityService.principal
String username = principal.username
SecurityContextHolder knows that:
SecurityContextHolder.getContext().getAuthentication().getAuthorities()
You can also use getAuthenticatedUser() by itself. This method is automatically injected in every controller, and thus only available from controllers. You will have to use one of the other methods if you want to access the current logged in user from anywhere else.

Resources