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
Related
I have a website through which you can create bundles and add custom or predefined tasks to them.
Everything works okay, I can change all these fields whenever I want. Once all these fields look alright to you, you have to click the "Save" button. Once you click it, the fields are validated through several methods. If all the fields were validated successfully, Ajax sends a post request to my Spring controller which then stores everything into a database. After that, I would like to redirect user to the page which displays all the existing bundles.
I have already tried to do this:
#RequestMapping(value = "/bundle", method = RequestMethod.POST, consumes = {"application/octet-stream", "multipart/form-data"})
public void bundle(MultipartHttpServletRequest request,
HttpServletResponse response) throws IOException {
// Code to store bundles to a database.
// Redirect
response.setHeader("Location", "http://localhost:8080/bundles");
response.setStatus(302); //302 Found
// I have also tried to replace above two statements with this
response.sendRedirect("http://localhost:8080/bundles");
}
The above code does execute and the request is sent to /bundles
But I seem to be stuck on the initial page, no redirect was made.
I had the same problem as you have. I solved the issue by redirecting in the Front-End with Angular.
You can use the answer from your HTTP-Request in javascript and then redirect from there.
My Server-Side code:
#PostMapping(AdminToolConstants.MAPPING_CHECK_USER)
public ResponseEntity checkUser(HttpServletResponse response, #RequestBody UserDto userDto) throws IOException{
if (userService.checkUser(userDto)) {
return new ResponseEntity(HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
Client-side javascript:
angular.module('admintool.services', []).factory('UserService', ["$http", "CONSTANTS", function($http, CONSTANTS) {
var service = {};
service.checkUser = function (userDto) {
return $http.post(CONSTANTS.checkUser, userDto).then(function (value) {
window.location.href = "/";
}).catch(function (reason) { window.location.href = "/register" });
};
return service;
}]);
Inside .then I redirect the user when the, for example, login was successfull and inside .catch if the login wasn't successfull.
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.
Can someone explain me how to write a custom login interceptor that checks username, password and also checks if the users validity date is greater than the current date. Im new to java programming & struts 2...i would really appreciate step by step info. I get the username, etc info by manual jdbc connection...i have a jndi setup for that. This also needs to have session management.
So a step by step with the following code samples would be nice,
1) The dao using jndi to get username,etc from DB
2) The login action with session aware
3) interceptor
4) login.jsp
5) struts.xml definition for the interceptor
6) task.jsp and task2.jsp ( internal pages that can only be seen if user is logged in)
Thank you!
You are on the right track.
There are many articles on that topic (google it). Choose one and try to understand it. The interceptor part should look something like this:
public String intercept (ActionInvocation invocation) throws Exception {
// Get the action context from the invocation so we can access the
// HttpServletRequest and HttpSession objects.
final ActionContext context = invocation.getInvocationContext ();
HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
HttpSession session = request.getSession (true);
// Is there a "user" object stored in the user's HttpSession?
Object user = session.getAttribute (USER_HANDLE);
if (user == null) {
// The user has not logged in yet.
// Is the user attempting to log in right now?
String loginAttempt = request.getParameter (LOGIN_ATTEMPT);
if (! StringUtils.isBlank (loginAttempt) ) { // The user is attempting to log in.
// Process the user's login attempt.
if (processLoginAttempt (request, session) ) {
// The login succeeded send them the login-success page.
return "login-success";
} else {
// The login failed. Set an error if we can on the action.
Object action = invocation.getAction ();
if (action instanceof ValidationAware) {
((ValidationAware) action).addActionError ("Username or password incorrect.");
}
}
}
// Either the login attempt failed or the user hasn't tried to login yet,
// and we need to send the login form.
return "login";
} else {
return invocation.invoke ();
}
}
Above code sample is part of this article where you will also find other steps.
Another way I would recommend is integration of spring security with Struts 2. That way you get secured and proven configurable security stack.
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);
}
}
}
I have a JSF web application I need to provide functionality as mentioned below:
In order to comment on something user must be logged in
If he is not logged in then 'Click here to login' takes him to the login page
Successfull login must redirect him to the url from where he navigated to login page
Is there any way this can be achieved?
As per the problem, you're apparently not using container managed authentication with a realm and <security-constraint> in web.xml. It will namely handle this fully transparently for you.
I'll assume that you've homegrown a filter which redirects the user to the login page when there's no logged-in user present in the session. In that case, you need to add the current request URL as a request parameter or session attribute as well.
Here's an example which passes it as a request parameter in the filter:
if (user == null) {
String from = URLEncoder.encode(request.getRequestURI(), "UTF-8");
if (request.getQueryString() != null) from += "?" + request.getQueryString();
response.sendRedirect("login.jsf?from=" + from);
}
Embed it as a hidden field in the login form (yes, using plain HTML/JSTL, JSF 1.x isn't helpful here):
<input type="hidden" name="from" value="${fn:escapeXml(param.from)}" />
In the login method, check if it is there and handle accordingly:
public String login() {
// ...
String from = externalContext.getRequestParameterMap().get("from");
if (from != null && !from.isEmpty()) {
externalContext.redirect(from);
return null;
} else {
return "home"; // Default landing page after login.
}
}
Here's an example which passes it as a session attribute in the filter:
if (user == null) {
String from = request.getRequestURI();
if (request.getQueryString() != null) from += "?" + request.getQueryString();
request.getSession().setAttribute("from", from);
response.sendRedirect("login.jsf");
}
This doesn't need a hidden field. In the login method, check if it is there and handle accordingly:
public String login() {
// ...
String from = externalContext.getSessionMap().get("from");
if (from != null && !from.isEmpty()) {
externalContext.getSessionMap().remove("from");
externalContext.redirect(from);
return null;
} else {
return "home"; // Default landing page after login.
}
}
JSF and URLs don't work well together: JSF URLs are not bookmarkable, the URL is always one page late compared to the page you're viewing, etc... So in your case you should not think in terms of URLs but in terms of views (.xhtml) files.
One way to solve your problem is create a session managed bean that stores the current view (and associated bean parameters if any) when you are at step 2. Once the user has logged in, checks if this session bean exist, and if so, redirects the user to the stored view rather than redirecting him to the standard post-login view. This is done with a return "viewName" in your doSignIn method.