Liferay and ZK Integration : User Info - liferay

I wrote a portlet and added to liferay.
I have found the way to get user name from cookie:
https://www.everit.biz/web/guest/blog/-/blogs/getting-current-liferay-user-in-a-standalone-webapp?_33_redirect=/web/guest/blog
I have looked into the zk liferay package, there is just JQuery related classes.
http://www.zkoss.org/javadoc/6.0.0/zk/org/zkoss/zkplus/liferay/package-summary.html
Is there any way to get the current user in ZK?

Follow simple pattern
In the main Entry controller class, the class which extends the DHtmlLayoutPortlet
In the process method you can setup commonParameter of liferay to zk-session
I am providing you code snippet :
#Override
protected boolean process(Session sess, RenderRequest request,
RenderResponse response, String path, boolean bRichlet)
throws PortletException, IOException {
setupSessionParameters(sess, request);
return super.process(sess, request, response, path, bRichlet);
}
protected void setupSessionParameters(Session sess, RenderRequest request) {
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
PortletSession portletSession = request.getPortletSession();
PortletPreferences prefs = request.getPreferences();
sess.setAttribute("SESSION_ID", portletSession.getId());
sess.setAttribute("THEME_DISPLAY", themeDisplay);
sess.setAttribute("GROUP_ID", themeDisplay.getScopeGroupId());
sess.setAttribute("PORTLET_PREFERENCES", prefs);
sess.setAttribute("PORTLET_ID", themeDisplay.getPortletDisplay().getId());
sess.setAttribute("currentUser", themeDisplay.getUser().getScreenName());
}
Use that zk session for getting those parameters in your application
If you want more information
Follow this link
It has all information that you want ...:)

Execution exe = Executions.getCurrent();
Session session = Sessions.getCurrent();
PortletSession ps = (PortletSession) session.getNativeSession();
User user = PortalUtil.getUser((HttpServletRequest) exe.getNativeRequest());
user.getUserId();

Related

Liferay - autologin hook/portlet doesn't logout the current user

It seems Liferay's autologin hook doesn't logout the current user. So I tried to do it programmatically with the following method call:
request.getSession().invalidate();
but with no success.Does anyone had the same issues with the auto-login hook ?
Hi to logout you have to invalidate the cookies and then invalidate the session see the Liferay LogoutAction for more detail
https://github.com/liferay/liferay-portal/blob/6.2.x/portal-impl/src/com/liferay/portal/action/LogoutAction.java
The main problem is that if a user is logged in, an autologin filter is not executed, so you can't do any logout action in it.
For my solution I created a servlet filter which check some paramteres for autologin and execute logout process. For creating a filter I follow this guide: http://www.liferaysavvy.com/2016/02/liferay-servlet-filter-hooks.html
My code for logout in doFilter method (in servlet filter):
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
final HttpSession session = request.getSession(false);
if (session != null)
{
session.invalidate();
}
filterChain.doFilter(request, response);
In Liferay 7.2, create a module portlet and do the following:
At the top after import add:
#Component(immediate = true, property = {"key=login.events.pre"}, service = LifecycleAction.class)
Customize your class as below:
public class LoginPreAction implements LifecycleAction
Add:
lifecycleEvent.getRequest().getSession().invalidate();
this will invalidate your session
Now send redirect:
try {
lifecycleEvent.getResponse().sendRedirect("/c/portal/logout");
} catch (IOException e) {
System.out.println("IOException while redirecting:::: "+e.getStackTrace());
}

Intercept user visits a group

I am new to liferay and I need to enhance my User Object with a Map(groupId, lastVisitedDate) after a user visited a group.
Any ideas when, where and how I can intercept this request and enhance my user with the called groupId and the current Date?
I solved my issue by creating a hook which extends the portal.properties.
In this properties file I created this property
servlet.service.events.pre=org.my.company.project.event.MyCustomAction
the MyCustomAction Class extends Action.
This is how I got the necessary informations
#Override
public void run(HttpServletRequest request, HttpServletResponse response)
throws ActionException {
try {
User user = PortalUtil.getUser(request);
ThemeDisplay themeDisplay = (ThemeDisplay) request
.getAttribute(WebKeys.THEME_DISPLAY);
Group group = themeDisplay.getLayout().getGroup();
[...]
} catch (Exception e) {
throw new ActionException(e);
}
}

Configure Apache Shiro to load [urls] section fully from JPA Entities

I can't seem to find an example to load the [users] AND [urls] from my JPA objects.
I want to use shiro.ini for [main] section only.
The source code of what I achieved so far is this:
Unable to #Inject my DAO in a Custom Apache Shiro AuthorizingRealm
Is there any example where [users] (user/pass) AND [urls] (roles, permissions) are FULLY loaded from database? I can't seem to find that anywhere. I'm looking for it for 1 week now.
After some long research, the "best" solution I came up with was this:
shiro.ini
[main]
jsfFilter = com.test.security.CustomAuthorizationFilter
jsfFilter.loginUrl = /login.jsf
[urls]
/** = jsfFilter
// You can add the methods to filter Ajax requests described by BalusC inside this filter.
CustomAuthorizationFilter.java
public class CustomAuthorizationFilter extends AuthorizationFilter {
#Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (!httpRequest.getRequestURI().startsWith(httpRequest.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) {
Subject subject = SecurityUtils.getSubject();
AuthenticatingSecurityManager authenticatingSecurityManager = ((AuthenticatingSecurityManager) SecurityUtils.getSecurityManager());
PrincipalCollection principals = subject.getPrincipals();
JPARealm jpaRealm = (JPARealm) authenticatingSecurityManager.getRealms().iterator().next();
AuthorizationInfo authorizationInfo = jpaRealm.getAuthorizationInfo(principals);
for (String permission : authorizationInfo.getStringPermissions()) {
if (pathsMatch(permission, request)) {
return true;
}
}
} else {
return true;
}
return false;
}
}
The pathsMatch(permission, request) method will try to validate/compare the received string permission with the path the user is trying to access.
This filter relies on ALWAYS having an authenticated user.
If the subject.getPrincipal() is null, more coding is necessary.
If anyone needs the whole code, let me know.

How to get portlet context in config (Liferay)?

I'd like to access the Context of the portlet in config mod (in my implement of ConfigurationAction interface).
I try since hours to get the same Context in my ConfigurationActionImpl.processAction(PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse) as I have in my doView(RenderRequest renderRequest, RenderResponse renderResponse), but without any good result.
In my doView(), I can access my portlet Context using getPortletContext() (same as getPortletConfig().getPortletContext()) and renderRequest.getPortletSession() (it's NOT the same Context instances), but I don't know how I can access one of those objects from my processAction().
Can somebody help me, please ?
This is the method I ended up using:
PortletBag portletBag = PortletBagPool.get(portletId);
DispatcherPortlet portlet = (DispatcherPortlet)portletBag.getPortletInstance();
PortletContext pCtx = portlet.getPortletContext();
In case you want to compute the portletId, you can do this:
String portletResource = ParamUtil.getString(renderRequest, "portletResource");
String portletId;
if (portletResource.contains("_INSTANCE")) {
portletId = portletResource.substring(0, portletResource.indexOf("_INSTANCE"));
} else {
portletId = portletResource;
}
As a side note, I want to mention that I needed it in order to be able to get the Spring ApplicationContext of the portlet, which I did with this:
PortletContext pCtx = portlet.getPortletContext();
ApplicationContext portletAppContext = (ApplicationContext)pCtx.getAttribute(FrameworkPortlet.PORTLET_CONTEXT_PREFIX + portlet.getPortletName());

Liferay 5.2.3 portlet configuration page issue

I wrote a portlet that has custom conf page here is configuration-action-class:
public class ConfigurationActionImpl implements ConfigurationAction {
private static Logger log = Logger.getLogger(ConfigurationActionImpl.class);
private config conf=config.getInstance();
public String render(PortletConfig config, RenderRequest renderRequest, RenderResponse renderResponse) throws Exception {
if(renderRequest.isUserInRole("administrator")){
log.info("UserRole:::admin");
return "/config.jsp";
}else if(renderRequest.isUserInRole("guest")){
log.info("UserRole:::guest");
}else if(renderRequest.isUserInRole("power-user")){
log.info("UserRole:::power-user");
return "/config.jsp";
}else if(renderRequest.isUserInRole("user")){
log.info("UserRole:::user");
}else{
log.info("UserRole:::dafug");
}
return "/config.jsp?mode=guest";
}
public void processAction(PortletConfig config, ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
conf.Names.clear();
String count = ParamUtil.getString(actionRequest, "count");
String portletResource = ParamUtil.getString(actionRequest, "portletResource");
PortletPreferences prefs = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletResource);
String[] list=count.split("/");
for(String a : list){
if( a!=null&& !a.equals("")){
String en = ParamUtil.getString(actionRequest,"En"+a);
String pa = ParamUtil.getString(actionRequest,"Pa"+a);
if(!en.equals("")&&!pa.equals("")){
conf.Names.put(pa,en);
log.info("word::"+en+"::::"+pa);
prefs.setValue("En"+a,en);
prefs.setValue("Pa"+a,pa);
}else if(a!=null&& !a.equals("")){
count=count.substring(0,count.lastIndexOf("/"+a))+count.substring(count.lastIndexOf("/"+a)+("/"+a).length());
}
}
}
prefs.setValue("count",count);
prefs.store();
}
public void serveResource(ResourceRequest request, ResourceResponse response){
log.info("HERE in conf");
}
}
This class worked fine for only one time after clicking on return to full page, the button that locate in right corner of portlets does not work and I cannot go to configuration page again!
and also the menu bar in up right corner of portal did not work after getting back from configuration page unless I delete my portlet and all of them will work fine again!
I solved this problem.
My problem is that first I should change all the to
and I change all of my JQuery code to JavaScript because some how these version of JQuery that I used generates some error with this version of Liferay (5.2.3)

Resources