Liferay: change the users landing page depending on organization - java

I'm using Liferay 6.0. I have multiple organizations and would like to change the user's landing page depending on organization.
I'm new to Liferay, tried to find some suggestions but could not find the correct answer.
Is it possible to do with out-of-the-box tools? without writing a code?
If code needed, what is the best solution?
Please help,
Thank you

In Liferay 6 the default landing page can be set with the property default.landing.page.path, but it is a general setting affecting each user in the portal instance.
To change the landing page of a user depending on the organization a custom action for the "post login" portal event is needed. Eventually, the property login.events.post has to point to a custom login action:
login.events.post=yourcode.CustomLandingPageAction
There are two options to achieve this:
With a hook: http://www.liferay.com/es/community/forums/-/message_boards/message/9824650
Modifying portal-ext.properties accordingly within your portlet project: http://liferaydemystified.blogspot.com/2011/04/liferay-default-landing-page.html
A custom action to make the user of an organization to land in the organization's private pages (derived from the links above):
public class CustomLandingPageAction extends Action {
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {
try {
doRun(request, response);
} catch (Exception e) {
throw new ActionException(e);
}
}
protected void doRun(HttpServletRequest request, HttpServletResponse response)
throws Exception {
long companyId = PortalUtil.getCompanyId(request);
String path = PrefsPropsUtil.getString(companyId, PropsKeys.DEFAULT_LANDING_PAGE_PATH);;
if (Validator.isNull(path)) {
User user = PortalUtil.getUser(request);
String language = user.getLocale().getLanguage();
List<Organization> orgList = OrganizationLocalServiceUtil.getUserOrganizations(user.getUserId());
// Default landing page: go to the path in DefaultLandingPageAction
LastPath lastPath = new LastPath(StringPool.BLANK, path, new HashMap<String, String[]>());
// But if the logged user is in some community
if (!orgList.isEmpty()){
// and such community has a private page
if (orgList.get(0).hasPrivateLayouts()) {
// go there instead
String orgFriendlyURL = orgList.get(0).getGroup().getFriendlyURL();
String myPath = "/" + language + "/group" + orgFriendlyURL;
lastPath = new LastPath(StringPool.BLANK, myPath);
}
}
HttpSession session = request.getSession();
session.setAttribute(WebKeys.LAST_PATH, lastPath);
}
}
}

Related

How to get page name from WebSphere Portal page?

I am creating a portlet for WebSphere portal 8 and would like to retrieve the page name where my portlet is rendered. This is important because depending on the page, the portlet will server content differently
I've tried to use the NavigationSelectionModel API but do not think I'm using it correctly. I want this code to happen before the view is rendered and I put the code in the doView method. The problem is that I cannot cast a ServletRequest/Response because I only have the RenderRequest and RenderResponse available in the doView method.
public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
// Declarations
List<ForeignAuthority> faList = new ArrayList<ForeignAuthority>();
String resp;
// Set the MIME type for the render response
response.setContentType(request.getResponseContentType());
// Check if portlet session exists
ForeignAuthoritiesPortletSessionBean sessionBean = getSessionBean(request);
if (sessionBean == null) {
response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
return;
}
try{
Context ctx = new InitialContext();
NavigationSelectionModelHome home = (NavigationSelectionModelHome)
ctx.lookup("portal:service/model/NavigationSelectionModel");
if (home != null) {
NavigationSelectionModelProvider provider =
home.getNavigationSelectionModelProvider();
NavigationSelectionModel model =
provider.getNavigationSelectionModel((ServletRequest)request, (ServletResponse)response);
for (java.util.Iterator i = model.iterator(); i.hasNext(); )
{
NavigationNode node = (NavigationNode) i.next();
if (i.hasNext()) {
System.out.println(node.getObjectID().getUniqueName());
}
}
}
}catch(Exception e){
e.printStackTrace();
}
PortletRequestDispatcher rd = getPortletContext()
.getRequestDispatcher(getJspFilePath(request, VIEW_JSP));
rd.include(request, response);
}
The expected result would be to retrieve the page name or unique name of the current page that the portlet is rendered on.
You can try whether the below code snippet helps. You can get the URI value and extract the page name from it.
HttpServletRequest httpServletRequest = PortletUtils.getHttpServletRequest(renderRequest);
httpServletRequest.getRequestURI();

Logged in user null Auth0/Spark Java

I am trying to get Auth0 integrated into my web app which uses the spark-java framework.
The problem is while the authentication works perfectly, including the callback(I see the new user created on Auth0's website and my website gets redirected), I can't access the logged in user info. I've tried several methods like SessionUtils.getAuth0User(request.raw()) and none of them are working.
For example in the provided tutorial here: https://github.com/auth0-samples/auth0-servlet-sample/tree/master/01-Login
they access the logged in user info like so:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
final Auth0User user = SessionUtils.getAuth0User(req);
if (user != null) {
req.setAttribute("user", user);
}
req.getRequestDispatcher("/WEB-INF/jsp/home.jsp").forward(req, res);
}
I've tried doing something similar with Spark but since the get works a bit differently in Spark I do this:
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/spark/template/freemarker");
String clientId = System.getenv("AUTH0_CLIENT_ID");
String clientDomain = System.getenv("AUTH0_DOMAIN");
get("/", (request, response) ->
{
Map<String, Object> attributes = new HashMap<>();
Auth0User user = SessionUtils.getAuth0User(request.raw());
if(user != null) {
attributes.put("user", user);
attributes.put("loggedIn" , true);
}
else
attributes.put("loggedIn" , false);
attributes.put("clientId" , clientId);
attributes.put("clientDomain" , clientDomain);
return new ModelAndView(attributes, "index.ftl");
}, new FreeMarkerEngine());
The code is always reporting the user as null even though the user is created and stored in the database and the signin works properly with no runtime or console errors. The other methods I tried I replaced the line where I set the user variable and wrote the following.
Alternate Method 1:
Auth0User user = (Auth0User) request.session().attribute("auth0User");
Here auth0User is the same string literal Auth0 uses in their implementation of SessionUtils as shown in their source code referenced here: https://github.com/auth0/auth0-java-mvc-common/blob/master/src/main/java/com/auth0/SessionUtils.java
Alternate Method 2:
Auth0User user = (Auth0User) request.raw().getUserPrincipal();
In addition this is my javascript code running client side for the authentication:
var lock = new Auth0Lock('${clientId}', '${clientDomain}', {
auth: {
redirectUrl: 'http://localhost:5000/build',
responseType: 'code',
params: {
scope: 'openid user_id name nickname email picture'
}
}
});
$(document).ready(function()
{
$('.signup').click(function()
{
doSignup();
});
});
function doSignup() {
lock.show();
}
I have no idea why user is being evaluated to null every time and I would love some feedback on what I'm doing wrong. Thanks.
In order for you to get a non null user instance from SessionUtils.getAuth0User(req) some piece of code must first call SessionUtils.setAuth0User. This should be done when you receive confirmation that the user authenticated with success.
In the auth0-servlet-sample you were using as reference this is done by configuring an Auth0ServletCallback that will handle requests performed to /callback endpoint. Since the Auth0ServletCallback calls (see code below) the set user for you, in the servlet example you can then get the user with success.
protected void store(final Tokens tokens, final Auth0User user, final HttpServletRequest req)
{
SessionUtils.setTokens(req, tokens);
SessionUtils.setAuth0User(req, user);
}
At the moment the available samples (auth0-servlet-sample, auth0-servlet-sso-sample, auth0-spring-mvc-sample, auth0-spring-security-api-sample and auth0-spring-security-mvc-sample) don't include one for spark-java so I can't refer you to any sample.
In order to solve this you have to include additional logic to process the result of the authentication operation in your spark-java application and in case of success call the SessionUtils.setAuth0User yourself if you then want to use the corresponding SessionUtils.getAuth0User method.
For general guidance on integrating a web application with Auth0 check Integrating a Web App with Auth0.

Getting user role in Java Portlets

I'm working with liferay server to build a portal application using portlets.
I want to display some user specific data on the website.
How can I get the role of the logged in user in liferay portlet?
my sample java code -
#Override
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
String data = "";
if(userRole = "Admin") { //How to get this user role?
data = "Admin user logged in";
} else if(userRole = "Guest"){
data = "Guest user logged in";
}
request.setAttribute("data", data);
}
And JSP code -
<script>
function WhoLoggedIn() {
document.getElementById("gameForm").submit();
}
</script>
<div onClick="WhoLoggedIn()">Click HERE</div>
<div>${data}</data>
Thanks.
In your portlet's code you can use below method as defined in portlet specification:
portletRequest.isUserInRole("roleName");
Note: Liferay doesn't use the isUserInRole() method in any of the portlets provided by default. Instead it uses Liferay's permission System directly, to achieve more finegrained security.
For more information please refer to below Link
https://www.liferay.com/documentation/liferay-portal/6.1/development/-/ai/security-and-permissio-4
you can use some method which are there in PermissionChecker.
ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();
permissionChecker.isCompanyAdmin() // Returns true if the user is an administrator of their company.
permissionChecker.isOmniadmin() // Returns true if the user is a universal administrator.
permissionChecker.isGroupAdmin(long groupId) // Returns true if the user is an administrator of the group.
for more information about PermissionChecker please refer to below link
http://docs.liferay.com/portal/6.1/javadocs/com/liferay/portal/security/permission/PermissionChecker.html
you can also explore RoleLocalServiceUtil class of Liferay
http://docs.liferay.com/portal/6.1/javadocs/com/liferay/portal/service/RoleLocalServiceUtil.html

How can I get the current logged in gmail user from cloud end point?

I am trying to get the current email id of the logged in google user. I tried something like the following which works in dev mode but not in production mode.
public class EndpointAPI {
#ApiMethod(httpMethod = HttpMethod.GET, path = "getuser")
public Container getLoggedInUser() {
UserService userService = UserServiceFactory.getUserService();
User guser = userService.getCurrentUser();
Container container = new Container();
container.user = "user not logged in";
if (null != guser)
container.user = guser.getEmail();
return container;
}
public class Container {
public String user;
}
}
I tried looking at the documentation (and tried adding client ids, scope etc) but could not successfully find what I need to do.
If someone can post a simple working example it will be much appreciated.
Regards,
Sathya
At simplest, you should register a client ID for a web application, and request a User object within the method signature of your API call. Example that supports requests from the JS client:
Ids.java:
public class Ids {
public static final String WEB_CLIENT_ID = "12345.apps.googleusercontent.com";
}
MyEndpoint.java:
#Api(clientIds = {Ids.WEB_CLIENT_ID})
public class MyEndpoint {
public getFoo(User user) throws OAuthRequestException {
if (user != null) {
// do something with user
} else {
throw new OAuthRequestException("Invalid user.");
}
}
}
user will automatically be populated with the current user represented by the token passed to your API, or null in the case of an invalid or missing token. The example above throws an exception when there isn't a valid user object, but you can also choose to allow unauthenticated access.
Check out the docs for more.

Navigate to external URL from a backing bean?

I'm trying to implement proper logout for my Java EE / JSF2 application.
It requires two things:
I need to logout from JAAS and invalidate the session
I then have to navigate to an external URL to fire Siteminder logout
The Siteminder logout URL (configured on the Policy server -> I cannot change it) is outside my applications context. Eg. if my webapp URL is https://localhost:8080/sm/MyWebApp then the logout URL is https://localhost:8080/anotherwebapp/logout.html.
This is the current local logout code:
public void logout() {
System.out.println("Logging out...");
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
try {
request.logout();
} catch (ServletException e) {
e.printStackTrace();
}
HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if (session != null) {
session.invalidate();
}
}
And here is the property that produces the logout URL:
public String getLogoutUrl() {
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String requestServer = request.getServerName();
String requestScheme = request.getScheme();
int serverPort = request.getServerPort();
String logoutUrl = requestScheme + "://" + requestServer + ":" + Integer.toString(serverPort) + "/anotherwebapp/logout.html";
return logoutUrl;
}
However, I cannot find a JSF2 / Primefaces component that can call logout() then open the external URL. For example, if I have:
<h:outputLink value="#{authBean.logoutUrl}" onclick="#{authBean.logout()}">[Logout]</h:outputLink>
then onclick does not seem to be called.
Another way I tried was putting the external URL to the end of the logout function to have it returned as a navigation string but it is not recognized (also tried with "?faces-redirect=true"...).
Any help would be appreciated.
You can also just use ExternalContext#redirect().
public void logout() throws ServletException, IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
((HttpServletRequest) ec.getRequest()).logout();
ec.invalidateSession();
ec.redirect("http://example.com/anothercontext/logout");
}
No need for an intermediating page with a meta refresh.
You can create a page logout.xhtml, so the code will look like this:
public String getLogoutUrl() {
return "/logout.jsf";
}
and in the page add:
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=https://localhost:8080/anotherwebapp/logout.html">

Categories

Resources