Accessing the user from a liferay portlet?

2019-01-12 09:15发布

问题:

I'm attempting to develop a portlet for liferay.

How can I get access to the username and password (and other data liferay has) of the user that's currently logged in?

I'd also like to be able to execute some code when users change their password.

回答1:

You can get the User ID by calling getRemoteUser() in the PortletRequest object. This is defined by JSR-168 therefore it's cross-portal compatible.

Once you have the ID you can fetch the additional informations by calling getUserById() (a Liferay specific service). This is something not covered by Portlet API specification, so it locks you to the Liferay.



回答2:

Liferay Specific stuff, here is a code sample to be written in your Portlet Class to retrieve the User:

ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

User user = themeDisplay.getRealUser(); // it gives you the actual Logged in User
//you can also use
// User user = themeDisplay.getUser(); // this would fetch the User you are impersonating 

long userId = user.getUserId();
String userName = user.getEmailAddress();

Alternatively;

long userId = themeDisplay.getRealUserId(); // themeDisplay.getUserId();
User user = UserLocalServiceUtil.getUser(userId);

Impersonate User:

Liferay has a concept that admins (or persons with the correct set of permissions) can impersonate a particular user of the portal. Through this they can see how the portal looks to that user.

For executing the code when user change their passwords: One approach would be to create a hook plugin and overriding the services by extending the UserLocalServiceWrapper class. Then checking for the password change and executing your code inside the your custom class.

Hope this helps.



回答3:

Or you can just use javascript:

Liferay.ThemeDisplay.getUserId()

There are many nice to haves in the Liferay namespace, take a look at the not so well documented API:

  • https://www.liferay.com/community/wiki/-/wiki/Main/Liferay+JavaScript+API
  • https://www.liferay.com/web/pankaj.kathiriya/blog/-/blogs/usage-of-liferay-js-object

Also, take a look at the web services available under localhost:8080/api/jsonws which you can invoke with a javascript call:

Liferay.Service(
  '/user/get-user-by-id',
  {
    userId: 10199
  },
  function(obj) {
    console.log(obj);
  }
);


回答4:

One simple and easy way to get the user in Liferay is PortalUtil.getUser function.

User user = PortalUtil.getUser(portletRequest);