How to use session in EL? [duplicate] - el

How do you check if a session exists for the request in EL? I'm trying something like:
<c:if test="${pageContext.request.session != null}"> ... </c:if>
but it seems like it's never null.

It's indeed never null. The session is always present in JSP EL, unless you add
<%#page session="false" %>
to top of JSP. You could then check for the session as follows (EL 2.2 only!):
<c:if test="${pageContext.request.getSession(false) != null}">
<p>The session has been created before.</p>
</c:if>
I'm not sure what's the concrete functional requirement is. If you'd like to check if the session is new or has already been created, use HttpSession#isNew() instead.
<c:if test="${not pageContext.session['new']}">
<p>You've already visited this site before.</p>
</c:if>
<c:if test="${pageContext.session['new']}">
<p>You've just started the session with this request!</p>
</c:if>
(the brace notations for new are mandatory because new is a reserved literal in Java language)
Of if you're relying on a specific session attribute, such as the logged-in user which is been set as
session.setAttribute("user", user);
then you should rather be intercepting on that instead:
<c:if test="${not empty user}">
<p>You're still logged in.</p>
</c:if>
<c:if test="${empty user}">
<p>You're not logged in!</p>
</c:if>

Seems to works with:
<c:if test="${fn:length(sessionScope) > 0}">
I wonder if there's a better way, since this requires that I have session attributes (I always do, but it's not really clean)?

In J2EE there will always be a session object when a user visits a site.
What is a Session ?
A session is pretty much what it sounds, when a user makes a page request to the server, the server creates a temporary session to identify that user. So when that same user goes to another page on that site, the server identifies that user. So a session is a small and temporary unique connection between a server and the user enabling it to identify that user across multiple page requests or visits to that site.
So basically if your hitting a page you have a session because your using JSP, which eventually gets converted to servlets.
http://www.stardeveloper.com/articles/display.html?article=2001062001&page=1

Related

Phoenix Framework: current_user not available in view despite successfully fetching from database

Using a module plug, I fetch the current users information from the database and store it in Plug.Conn.assigns as current_user. By inspecting the connection I see the current users details in the assigns but I'm unable to access any details.
For example, I would like to display the current user's name, as in, "you are logged in as #conn.assigns.current_user.name " but Phoenix is showing the current user is nil.
Please view the accompanying screenshot.
There is certainly a current_user object in the Plug.Conn.assigns. I should be able to access the name, "cooldude77#aol.com". So, why is Phoenix telling me the current_user is nil?
EDIT:
Adding the current user plug:
def call(conn, _params) do
if conn.assigns[:current_user] do
conn
else
user_id = get_session(conn, :user_id)
cond do
user = Repo.get_by(User, auth_id: user_id) ->
conn
|> assign(:current_user, user)
|> assign(:user_signed_in?, true)
true ->
conn
|> assign(:current_user, nil)
|> assign(:user_signed_in?, false)
end
end
end
So, here I'm using Auth0 for authentication. The user logs in at Auth0 and is redirected back to app with 3 attributes that I track, a unique auth_id, a name, and an avatar. Upon logging in I check if this is a new user by checking if their auth_id is saved in my database, if it is then I know they are a returning user and I assign the current_user object to the user. If they are a new user I add them to my database (where they are given some additional attributes) and assign the current_user object to the user.
Still experiencing this problem where I have a current_user in the connection but I cannot access the user's attributes - they are showing as nil
You should be able to just use #current_user.name in the template to get the user.
Also, since the value of current_user is set to nil in the plug when nobody is logged in, you can just do !!#current_user instead of #conn.assigns[:user_signed_in?] up above.
The assumptions of #Badu lead me to discover the issue. In my controller code I originally passed the current_user from the session to the render function like so:
def index(conn, _params) do
render(conn, "index.html", current_user: get_session(conn, :current_user))
end
As the application grew and I added more pages I had to keep grabbing the current user out of the session so I decided to replace this behavior with a plug, the code of which I posted above. However, I forgot to delete the current_user object I was storing in the connection from the controller. So, while a current_user object did exist in my connection, my view_template was accessing an older deprecated version of current_user, which did not have the same attributes, hence the nil values.

Maintain Session when logged in across all Pages, End session after set time (OWA_COOKIE)

I need to maintain a session for session credentials throughout the web pages I have made. I have next to no experience using OWA_COOKIE and am unsure how to go about it.
I just need it to maintain the session, Finish session if
inactive for 15 mins OR 2. they log out
I have had a whirl at it and this what I have but it doesn't work and am at a lose, can someone help or point me in the right direction?
FUNCTION maintain_session_cookie
AS
TYPE vc_arr IS TABLE OF varchar2(4000)
INDEX BY BINARY_INTEGER.
TYPE cookie IS RECORD (
NAME varchar2(4000),
vals vc_arr,
num_vals integer);
BEGIN
owa_util.mime_header('', FALSE);
owa_cookie.send(
NAME=>'Session_Cookie',
VALUE=>LOWER(),
expires => SYSDATE + 365);
-- Set the cookie and redirect to another page
owa_util.redirect_url();
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
I have been just fiddling to see how it works and provide the functionality that I need.
First of all, it is a quite awkward way to set session lifetime by cookies. You can setup the parameter timeout-secs in either web.xml or weblogic.xml (see Oracle docs).
Your both requirements should be processed by the HTTP server, that's my point of view.
Now, let's say you still want to use cookies (maybe you do not use WebLogic or another reason, whatever). You will face following problems:
You will need to specify these cookies on every page you will display to the user, and not only pages, every ajax call should also have the cookies. So, everything which shows user activity should have this cookie.
Expires parameter should, obviously, be sysdate + interval '15' minute, then your cookie will work exactly for 15 minutes and if you do like it is written in point 1 the cookie will be lost only if there is no activity.
You will have to close the session by yourself if the cookie is not more presented in HTTP request, this is an additional problem.
The thing I want to say is: do it with server configuration and not with cookies. This will save your time and nerves.

Laravel, get currently logged-in users

I want to display a list of currently logged-in users in an app. I want to use Laravel Auth method. I'm looking at the API and I cannot find anything like it.
I would probably need to loop through the sessions store and then match it to a user ID. Am I right?
UPDATE: Forgot to mention, I'm storing sessions in the DB.
"Currently logged in" is something you can't do with plain old sessions. Let me explain why:
A session is a bunch of data stored at server side which is assigned to an user through a cookie. That cookie remains on user browser and so it keeps the session active. Sessions can stay "alive" months without the user even logging in.
But, it's possible to store sessions on database.
As you can see, Laravel keeps a field called last_activity and, through that field, you should be able to retrieve all sessions that had activity within the last 15 minutes (or something else, you call it).
When your retrieve those records, the data field is a serialized representation of session data. You can unserialize($session_record->data) and retrieve the user id.
Depending on your Auth driver, session's user id may have different names:
For eloquent driver, it should be eloquent_login.
For fluent driver fluent_login.
For your Custom\AuthClass, it should be called custom_authclass_login.
Assume that all http requests from logged in users are passing auth middleware, we can override terminate function like following:
public function terminate($request, $response)
{
Auth::user()->save();
}
Then a query like User::where('updated_at', '>', Carbon::now()->subMinutes(12))->get(); will bring all logged in user, where 12 is the lifetime of session.
Of course, for real time, we should use ajax calls every 5 seconds or websockets via pusher or other.
First create a table where the logged in user's id will be inserted
Schema::create('active_users', function(Blueprint $table)
{
$table->increments('id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
Then in yourcontroller insert data while logging in
if (Auth::attempt($credentials)) {
DB::table('active_users')->insert(array('user_id' => Auth::id()));
}
and delete the data while logging out
DB::table('active_users')->where('user_id', '=', Auth::id())->delete();
Print the online users list in your view
<ul><strong>Online Users</strong>
<?php $online_users = DB::table('active_users')->where('user_id','!=',Auth::id())->get(); ?>
#foreach($online_users as $online_user)
<li>{{User::find($online_user->user_id)->first_name}}</li>
#endforeach
</ul>

Incorrect password redirects to incorrect page?

So I put together a very crude login form using php and a mysql database, and I have it set (or so I think) to redirect back to the login page with a "loginFailed=true&reason=password"". I'm trying to just have it redirect back to the login, and display an incorrect password message, but instead it just redirects to the main index page.
What am I doing wrong here? Granted I borrowed heavily from some pre-existing code due to my lack of coding-knowledge, but it did work as intended for a bit before redirecting.
Here is the code:
passwordcheck.php
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("password");
header("location:admin.html");
}
else {
die(header("location:login.html?loginFailed=true&reason=password"));
}
?>
And here is the password field in the login page:
<span class="add-on"><i class="icon-list-alt"></i></span>
<input type="password" id="inputIcon" class="span4" name='password' id='password' maxlength="50" placeholder="<?php $reasons = array("password" => "Yo shitbird, wrong password."); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>" />
</div>
Try moving the header() command out of the die() call:
else {
header("location:login.html?loginFailed=true&reason=password");
die();
}
There are many other potential problems with this code, I would suggest reading a few tutorials on the subject, there are plenty out there; although be careful, there are many low-quality PHP tutorials that might teach you dangerous practices. Learning more about PHP security is important, especially if this code is going to be on a publicly accessible web server.
One of the problems is the fact that you are storing passwords in plain-text. Passwords should never be stored in plain-text, they should be salted and stored with a secure hashing algorithm. PHPass is a great utility to help with this.

subdomain,testing using cucumber or capybara and rspec

Some part of the development of my project has been done.Our
company asks me to write cucumber test cases for the developed code
and for the henceforth development as well.
The routes file have two subdomains for admin and hosts.Devise is also
being used.
Now i installed cucumber and have written the first scenario for the
first story when the non registerd user lands on the home page,enters
a valid email and gets redirected to the next page..the page has no
password field.
Scenario: Non registered user lands on beta home page.
Given: I am on the homepage
When: I enter valid email with "bahubalian...#gmail.com".
Then: I should be redirected to request invitation page.
The problem is in my routes file, I have,
constraints :subdomain => ADMIN_SUBDOMAIN do
....
root :to => admin#index
end
constraints :subdomain => HOST do
...
root :to => home#index.
end
Now how do i specify the path.rb file to look for the root_path in
that specific subdomain.
Theres no root_path written outside the subdomain constraints.
This is my first time with testing.
I am really stuck onto this.Any help is deeply appreciated.
I just got to know from somebody that this can be implemented using capybara.If so ,could you please give a little idea about it.
Turned out it was pretty simple.Capybara provides a default_host method.
So I just needed to mention,
When I visit subomain sub
And then the webstep
Given /^I visit subdomain (.*)$/ do |site_domain|
site_domain = "http://sub.example.com" if site_domain == "admin"
Capybara.default_host = site_domain
visit "/"
end
Update:
default_host is not supposed to be used as it is not mentioned in the docs.
Instead try using absolute path in visit.
Given /^I visit subdomain (.*)$/ do |site_domain|
site_domain = "http://sub.example.com" if site_domain == "admin"
visit site_domain
end