Express.js: Cookie being saved late - node.js

I think this is because of the asynchronous nature of Node.js in general.
I am changing a cookie's value, then rendering a new page. However upon rendering the new page, the page shows the just-overwritten contents of the cookie. It's as if the cookie is being saved a step late.
res.cookie('loginid',req.body.name,{maxAge:60000});
res.render('page1');
In page1, I have:
<% if(req.cookies.loginid){ %>
cookie remembered. Hi, <%= req.cookies.loginid %>! <% } %>
Example: Cookie currently has loginid="id1". I set it to id2, then render page1. Then I am sent to page1 and of course, it shows id1. If I repeat the procedure by replacing id2 with id3, page1's contents will show id2, and so on.
I tried doing a callback on the res.cookie(...) function, but nothing was called inside it. It looked like:
res.cookie('loginid',req.body.name,{maxAge:60000}, function(req,res){console.log('test');});

When your template (or any other code for that matter) accesses req.cookies, it will access the cookies that were sent by the client (so the values that were previously set, in a different request, using res.cookie()).
Those cookies are independent of cookies that you are setting using res.cookie(), so using that won't update any values in req.cookies within the same request (you're merely telling Express, when this request is done, please include a Set-Cookie header in the response with this value).
Since you're storing req.body.name as cookie value, you can just use that in rendering your template:
res.render('page1', { loginid : req.body.name });
And in your template:
<% if (loginid) { %>
cookie remembered. Hi, <%= loginid %>! <% } %>
(However, you cannot be sure at the time of rendering that the cookie that you are sending back will actually be accepted by the client, so technically saying cookie remembered is premature).

Related

Yesod Non-AJAX HTML Form CSRF Token

I just turned on CSRF protection middleware in Yesod.
My jQuery AJAX calls are working, with the CSRF token being added into the header as per the normal scaffold.
Now I have a normal HTML "POST" form, not generated by Yesod. I want to include the CSRF protection token as a hidden input.
So far I have this in my ExampleHandler.hs
mcsrftoken <- fmap reqToken getRequest
let csrftoken = case mcsrftoken of
Nothing -> "NO_TOKEN"
Just t -> t
(Thanks to the Snoymaster at Yesod 1.2 CSRF protection)
And in example.hamlet:
<form method="post" action="#{ExampleR someId}">
<input name="_token" type="text" value=#{csrftoken}>
This one form works.
I have a lot of handlers, so I do not want to paste the code (or a function) in every one, to retrieve the token. I also do not want to convert all my HTML forms into AJAX.
I tried to paste the above token retrieving snippet into Foundation.hs, to get the token everywhere, but then I get:
Variable not in scope: csrftoken
On the line in the handler where the example.hamlet is pulled in.
How can I make get the csrftoken variable in scope in all handlers?
Is there a better way to get the CSRF token into the non-generated HTML forms?
Thank you haskellers and Yesod fans

How to pass a string between two jsp pages?

I want to pass a string(username) between my two jsp pages,
Login.jsp and Details.jsp.
Please tell how it can be done?
I tries this in Login.Jsp
<html>
......
<%
session.setAttribute("key","value");
%>
.....
</html>
In Details.jsp
<html>
......
<%
session.getAttribute("key");
%>
.....
</html>
It showed "NULL" as output.
Usually after a login you should save the user data in sessions:
session.setAttribute("key","value");
and then access from other pages with
session.getAttribute("key");
if you need more information there's a lot around: http://www.jsptut.com/sessions.jsp
Try this
jsp1.jsp
request.setAttribute("name",somevalue);
RequestDispatcher dispatcher = request.getRequestDispatcher("jsp2.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
jsp2.jsp
out.println(request.getAttribute("name"));
There are several ways to pass data from one webpage to another:
Put a form on Login.jsp and let it post to Details.jsp. This will post the values in the form to Details.jsp.
Redirect to Details.jsp?username=ARJUN. This will pass a variable to Details.jsp in te query string.
Put the username in a cookie. The cookie will be submitted to Details.jsp (and every other page), which makes it possible to determine the username in every page.
Put the username in the session. Similar to a cookie, but the session is stored on the server and associated with the user that is currently viewing your website.
First create servlet in write this code:
Here we can get the value using requet.getParameter("name"); here, name is textbox name of a previous page
<%! String name=request.getParameter("name")%>
<% out.println("Welcome :"+name) %>

How to safely pass an email address through a query string using javascript/php?

I have a form who's data will be submitted to a salesforce.com database via the action parameter
<form name="ifsLeadsForm" id="ifsLeads" action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="post">
Salesforce allows for a return url where the user will be sent after the data is submitted to the database.
<input type="hidden" name="retURL" value="myReturnURL" />
I need to pass the value of the "firstName" input and the "email" input from the form on to the return URL (a php document) so I can $_GET the name and email address and an email can be sent to the user thanking them for submitting their info.
I used the .serialize() function to grab the key/value of the firstName and email inputs and appended them to the return URL:
<script type="text/javascript">
$('#submit').click(function(ev){
var queryString = $('#first_name, #email').serialize();
document.ifsLeadsForm.retURL.value = "http://www.myDomain.com/return.php?"+queryString;
});
</script>
My question is -
Is it safe to be passing an email address through a query string like this? If not, what is the safe way?
I appreciate any help.
Michael
With GET request data is visible to everyone in the URL. POST request is a little safer than GET because the parameters are not stored in browser history or in web server logs.
You have to make ajax request and get it on the server side with $_POST.
More info on http://www.w3schools.com/tags/ref_httpmethods.asp

Use fragments-like views in Symfony2

I have two tables in a database. One of them contains the users of the application, and the other one keeps some medical reports about them in a ManyToOne relationship, so every user can have a random number of medical reports in the info table.
On the left of the screen I want to display a list of the users' names, an easy thing to do. Every time I click on the name of one of them, I get to another page that shows the medical data, and I have to go back to get again the list of the users. However, I'd like to have this info in the same view, so every time I click on a name on the left I get his or her data on the right, and when I click on another user, the info of the previous user disappear and the new is shown. I mean, I want a similar behavior that the old HTML iframes had, or the new Android 4 fragments.
Is this possible in Symfony2/Twig?
Twig is just a template engine, it is parsed on the server side and raw HTML/CSS/JS is returned to the browser, you can't write interactions with the user in Twig.
Symfony is a server-side framework, which means it is parsed on the server side and raw HTML/CSS/JS is returned to the browser, you can't write interactions with users with Symfony.
You need to use a client side script lanuage, like JavaScript. You can create AJAX requests to solve your problem. AJAX requests a url and displays the content of the url on the page. As AJAX is one of the most not-crossbrowser things in JavaScript, it is recommend to use a library like MooTools or jQuery.
I recommend to create a RESTful API for the AJAX requests. Something like /users/{id} should show the user information. For that, create a controller that shows the user data and map it to the /users/{id} route:
<?php
// src/Acme/DemoBundle/Controller/UserController.php
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class UserController extends Controller
{
// ...
/**
* #Route("/users/{id}")
*/
public function showAction($id)
{
// select user by id
$user = ...;
// renders the user data
$this->render('AcmeDemoBundle:User:show.html.twig', array('user' => $user));
}
}
And now you create an AJAX request to that url to get the user data:
<ul>
<li><a class="js-show-user" data-id="1">Joren</a></li>
<li><a class="js-show-user" data-id="2">Wouter</a></li>
<!-- ... -->
</ul>
<div id="js-user-data"></div>
<!-- ... include jquery -->
<script>
jQuery(function($) {
var output = $('#js-user-data');
$('.js-show-user').click(function(e) {
jQuery.ajax({
url: '/users/' + $(this).data('id'), // request the correct url
success: function (result) {
output.html(result); // output the result
},
});
});
});
</script>

Best ways to secure form data from malicious users wielding Firebug?

I've read a couple of related questions on this, but they don't answer my question directly. Developer tools like Firebug allow anyone to see and manipulate form data before a form is sent. A good example of this is adjusting the value of a hidden "member ID" field so that the form submission is credited to another user.
What are the best ways to prevent this type of tampering? My research suggests moving sensitive form inputs to a server-side script, but are there any other options or considerations?
I'm familiar with PHP and jQuery, so my ideal solution would use one or both of those languages.
You can't use jQuery for security since it's all handled on the client side.
In your example just use a PHP session in staed of a hidden input field, because as you rightfully noted this can be manipulated.
Using sessions would look something like the following:
login page
<form action="login.php" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" value="submit">
</form>
login.php
// you have to include this on every page to be able to user sessions.
// also make sure that you include it before any output
session_start();
//Always sanitize the user input before doing any db actions.
//For example by using: `mysql_real_escape_string()` ( http://php.net/manual/en/function.mysql-real-escape-string.php ).
// check user credentials against db
$_SESSION['user'] = $dbresult['username'];
page-where-userid-is-required.php
session_start();
if (!isset($_SESSION['user'])) {
// user is not logged in!
} else {
// use user info to place order for example
}
The session will be active until the user closes his browser / until the session expires (which is a PHP setting)
The above is just some sample code to give you an idea.
It works smaller projects, however as projects get more complex I would suggest going for the MVC (Model, View, Controller) way. ( http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller )
But that's just a whole other story :)
Here are a few basic suggestions:
You need to validate form inputs using a server-side (PHP) script.
Instead of relying on sensitive pieces of information, such as member ID, from the form you could instead cache such data in your server session. That way there is no way for a malicious user to change the data on the fly.
You can still use jQuery validation as a convenience to catch basic input problems, but you can only trust data that is validated using server-side code.

Resources