Foren

Fetch Logged in User Id in Service Layer

thumbnail
Subhasis Roy, geändert vor 8 Jahren.

Fetch Logged in User Id in Service Layer

Expert Beiträge: 275 Beitrittsdatum: 20.01.12 Neueste Beiträge
Hi,

I need to fetch the logged in user id in the service layer (No REQUEST available, so no access to ThemeDisplay object).
Can I please have a pointer or sample on this.

thanks,
subhasis
thumbnail
Subhasis Roy, geändert vor 8 Jahren.

[SOLVED] RE: Fetch Logged in User Id in Service Layer

Expert Beiträge: 275 Beitrittsdatum: 20.01.12 Neueste Beiträge
Hi All,

I am able to get that using the following code in the service layer without using request.
I tried the following 2 code snippet and it worked for me.

Approach 1

import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextThreadLocal;

// other codes.....

ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();
User user = UserLocalServiceUtil.getUser(serviceContext.getUserId());



Approach 2

import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.kernel.util.GetterUtil;

// other codes.....

long userId = 0;
if (PrincipalThreadLocal.getName() != null) { 
     userId = GetterUtil.getLong(PrincipalThreadLocal.getName()); 
     User user = UserLocalServiceUtil.getUser(userId);
}
thumbnail
David H Nebinger, geändert vor 8 Jahren.

RE: Fetch Logged in User Id in Service Layer

Liferay Legend Beiträge: 14916 Beitrittsdatum: 02.09.06 Neueste Beiträge
This is actually not a good idea. Before you know it, someone will start invoking your service from a scheduled task or via a web service call (soap or json).

If you need an argument in your service layer, then it is a requirement of your API. You should add it to the method signature and ensure it is provided.
thumbnail
Subhasis Roy, geändert vor 8 Jahren.

RE: Fetch Logged in User Id in Service Layer

Expert Beiträge: 275 Beitrittsdatum: 20.01.12 Neueste Beiträge
David H Nebinger:
This is actually not a good idea. Before you know it, someone will start invoking your service from a scheduled task or via a web service call (soap or json).

If you need an argument in your service layer, then it is a requirement of your API. You should add it to the method signature and ensure it is provided.



Thanks David. I fully agree to this.
Basically I needed a quick fix so I used that approach. I will changed that later point of time.