Get the current user Liferay using a simple Java code - authentication

I'm working with : Liferay 6.0.6 with JBoss 5.1 and Struts2.
My question is, how to get the current user in Liferay once logged in, using a Java code.

In your doView/processAction method do following
User user = (User) request.getAttribute(WebKeys.USER);
or use the ThemeDisplay object. It contains another information like companyId, groupId, ...
ThemeDisplay td =(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
User user = td.getUser();
Classes ThemeDisplay, User nad WebKeys are part of portal-service.jar.
If you need just some id to identify current user you can also use
String userId = request.getRemoteUser();
This solution is not Liferay specific and should be portable among jsr-286 portals.

Liferay provides Util class
com.liferay.portal.util.PortalUtil
This class contains all utility methods to get the frequently used attributes.
Try using PortalUtil.getUser(PortletRequest portletRequest) method to avoid creating new objects and references.

This is an other possible way to do it :
private LiferayFacesContext liferayFacesContext = LiferayFacesContext.getInstance();
User currentUser=liferayFacesContext.getUser()

Related

How to make ProfileViews count in laravel?

I need help. How do I create profile visitors in Laravel 8? I have not written the code yet and I do not even have an idea how to complete this task. I would be very grateful if you could help me.
You can leave the visitor without any profile. He will be able to access public web pages without authentication and therefore only logged in users will have profile.
UPDATE
Proposed skeleton in two steps using cookies
1- When a user make request on profile page generate an unique identifier and store it in user cookie with a long enough validity if it not yet exists
2- Using this unique token register a new view count (if not yet done) before sending response to user.
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
public function getProfilePage(Request $request){
if(!Cookie::has('uniqueId')){
$uniqueId = Str::uuid(); // generate unique id for current user
Cookie::queue('uniqueId', $uniqueId, [live time in minutes]);
// save it using Cookie::queue
// one year for example as live time
}
// check if view count already exists for $uniqueId
// and save it in a persistent way if not
// other stuff ....
return ....
}

silverstripe 3 - How to add access control to generated data objects?

Good afternoon,
Please let me know if this question is not clear enough, I'll try my best to make as straight-forward as possible.
How can I add access control to objects that are generated by an end-user using my data object?
Example: I have a class that extends a DataObject. Someone logs in the back-end; fills out the form that's generated by the CMS for the data object. A record is then created in the database by the CMS.
I would like to add an access control to that newly created record in the database.
For a code scenario you can take a look at one of my posts: Silverstripe 3 - Unable to implement controller access security from CMS
The only other way I can think of asking this question is: How to Dynamically (or programmatically) create permissions for records that are created by a DataObject extension via the CMS?
Thanks for your assistance.
Update - Sample Code
///>snippet, note it also has a Manager class that extends ModelAdmin which manages this!
class component extends DataObject implements PermissionProvider{
public static $db = array(
'Title' => 'Varchar',
'Description' => 'Text',
'Status' => "Enum('Hidden, Published', 'Hidden')",
'Weight' => 'Int'
);
///All the regular permission checks (overrides), for the interface goes here, etc...
///That is: canView, canDelete, canEdit, canCreate, providePermissions
}
Now, from the back-end an end-user can add components using the Manager Interface that's generated by extending ModelAdmin. How can I add individual permissions to those added components by the end-user?
Thanks.
Update 2
Example: Add Process Data Object that extends ModelAdmin will give you this in the back end
Then, when you click on the generated 'Add Process' button, you'll get this:
Finally, someone fills out the form and clicks on the 'Create' button, which saves the data in the database. That looks like this:
Now, on that record thats created in MySQL I'd like to add granular permissions to that record. Meaning, for every record created I want to be able to Deny/Allow access to it via a Group/Individual, etc.
Is that even possible with the SilverStripe framework? Thanks.
Implement the functions canView, canEdit, canDelete, and/or canCreate on your DataObject.
Each function will return true or false depending on the conditions you set - any conditions, not just what is defined in the CMS.
See the example code on the tutorial site.

"Department" user field not accessible through the API?

We have set up the available departments for our workspace and were hoping to migrate an existing Excel document with user:department relationships over to the new data fields. I wrote a Python script using the Pyral package that attempts to do this, but it looks like the "Department" field is not accessible via the API? Is this intended or could there be a problem with my query?
Pyral defaults to Webservices API (WSAPI) 1.37, and the new User fields are only present on WSAPI >= 1.41.
You can override pyral's default WSAPI version by changing this variable:
WS_API_VERSION = "1.37"
in pyral's config.py to:
WS_API_VERSION = "1.42"

MVC user's full name in Url, how to handle duplicates

I want to setup the following url in my MVC4 website, using the user's full name in the url:
http://www.myapp.com/profile/steve-jones
I have setup the following route in Global.asax:
routeCollection.MapRoute(
"profile", "profile/{userName}",
new { controller = "myController", action = "profile", userName = string.Empty
});
And I can take the parameter 'steve-jones' and match it to a user with matching name. My only problem though is, what if there is more than one 'Steve Jones', how can I handle this?
Does anyone know of a workaround/solution to this so that I can use a user's full name as part of the url and still be able to retrieve the correct user in the controller method?
Am I forced into including the user's id with the url (something that I do not want to appear)?
The usual way of handling this is by appending a number when creating the profiles. So if "steve-jones" is already a name in the database, then make the user's display name "steve-jones2". You basically have to insist that all profile urls are unique, which includes updating any existing database and account creation code.
Alternatively (and/or additionally), if two same names are found then have the script reroute to a disambiguation page where the user is presented with links and snippet of profile info of the many existing Steve Joneseses so they can go to the full correct profile.
Another way of handling it is by giving all user profiles an additional numeric code on the end. At my university all logins are based on name, so they give everyone pseudo-random 3-digit extensions so that they are safe as long as they don't get 1000 people with the exact same names :)
Some people might be happier being steve-jones-342 if there is no steve-jones or steve-jones1, if you're concerned.

Connection strings for different users

How do I send two users coming from different company domains to different SQL databases to retrieve/store data? I use Application variables to store the connection strings and the Request.ServerVariables("LOGON_USER") variable is an effective way to get the domain name. Is the GLOBAL.AsA file to be modified? The table names are exactly the same in both databases, so I think changing the connection strings based on the user domain should do the trick.
User A with domain ABC --> Application("ConnecttoDB") send to database A
User B with domain XYZ --> Application("ConnecttoDB") send to database B
I have roughly 900+ classic ASP pages so I would really hate to add a bunch of IF-THEN's to choose the correct database in each page. All ideas are greatly appreciated!
UPDATE: To make things simple I'm envisioning one single Application variable (i.e.: ConnecttoDB) However, wouldn't its value be constantly changing every time a different user gets access and altering page results?
You can't use an Application variable since that's shared across all users. This would be a race condition. Instead you'll need to use the Session object to store the connection and then use that whenever you need to connect to the DB.
myDB=Server.CreateObject("ADODB.Connection")
StrConn = Session("ConnecttoDB")
myDB.Open StrConn
Here's one way of doing it:
I'm guessing that your classes for your web page codebehind files inheit the Page class. Create a new class file in your ASP.net project that inherits Page. Call it JorgePage. Then, make your codebehind file classes inherit JorgePage.
In JorgePage, write two functions:
private string getUsersDomain()
{
// returns the user's domain
}
protected string getUsersConnectionString()
{
switch (getUsersDomain().ToUpper())
{
case "ABC":
return Application("ConnecttoDB_ABC");
break;
case "xYZ":
return Application("ConnecttoDB_XYZ");
break;
}
}
Now, the function getUsersConnectionString() is available in the context of all your pages and returns the correct connection string. Furthermore, you have the code in only one place, so if you need to change the logic later, you can do so easily.
Given that you're using classic ASP, you can define a function to return the appropriate connection string in another .asp file and use the #include directive to add it to all your pages.