Set a cookie from view, then read it from Controller in Rails - javascript

I would like to set cookie value from within Rails view using Javascript, then use Controller to read this cookie. Is this possible with Rails, and how should I go about it?
My situation: I have an input field (say, address) that user needs to fill out when s/he first comes to my site. The user then logs in using Omniauth. I would like to persist address until after he logs in.
Update:
I was able to add to document.cookies on client. However, cookies["something"] returns nil from Rails end. Below is the cookie hash:
#<ActionDispatch::Cookies::CookieJar:0x007 #secret="f4d518c0b2", #set_cookies={}, #delete_cookies={}, #host="localhost", #secure=false, #closed=false, #cookies={"_myapp_session"=>"BAh7Ck==--776b2fcfcd63d3c84d2b1de5327e277499add6d4", "fbsr_1505068851081"=>"mqZeyvoRC"}, #signed=#<ActionDispatch::Cookies::SignedCookieJar:0x007 #parent_jar=#<ActionDispatch::Cookies::CookieJar:0x007fdf...>, #verifier=#<ActiveSupport::MessageVerifier:0x007fdfa34548d8 #secret="f4d518c0b2e9d8", #digest="SHA1", #serializer=Marshal>>>

To set a cookie in javascript you can do:
document.cookie="something= test";
So you can add an event (click, submit, ..) to get the value from the input and create a cookie the way i mentioned above.
In rails you can read the value like this:
cookies["something"]
You can also specify when the cookie will expire in javascript if you need to.

Short Answer
Install the MDN JavaScript Cookie Framework
On your js file:
docCookies.setItem('my_cookie', 'my_cookie_value', '', '/');
On your rails controller:
cookies[:my_cookie]
Not so short answer
Rails ActionDispatch::Cookies defaults the cookie path to the root of the application, while plain JavaScript defaults it to the current path.
This means that if you don't declare the path, you'll end up with two different cookies bearing the same name and a headache.
In order to troubleshoot this you can use the 'Application/Cookies' on the Chrome DevTools window so you can see all the details for each cookie and reload their values as you modify them via the 'Console' panel.

This may explain your problem. Apparently you need to make sure the cookie's path lines up.
How can i read cookies in rails that have been set by jquery

Related

Paypal - customize return url with dynamic params

I set up a button to connect with Paypal on my website.
BUT
I would like to pass some parameters in the return url, it seems that it is not possible. I have read the documentation 10 times and got no more informations.
https://developer.paypal.com/docs/log-in-with-paypal/
For example = https://returnurl?id=12345.
Does anyone know if this is possible and who has done it before ?
Thank you..
If you set a Redirect URL in the app without the parameters and it works, does adding the parameters on to that working base URL (only to the redirect_uri in your code) not work?
If not, then assuming they are being redirected back to a page on the same server they started at, the other best/simplest solution is probably to use a webserver session to story any additional info of this type so it's available on return pageload.
If it's pure client-side JavaScript then browser local storage could work, though it's strange to have to resort to that and Log in with PayPal requires server calls to do anything useful with an authorization_code anyway.

Users can set cookies in console?

I'm wondering the best way to implement cookies to my site. I would like a user to be able to edit a given post based off a cookie that I set at the time the post is created.
I'm using Angular to set the cookie. ie:
var favoriteCookie = $cookies.myFavorite;
$cookies.myFavorite = 'oatmeal';
(per the Angular tutorial for $cookies).
My question is more at the core of how to use cookies. Wouldn't it be easy for a user to set the cookie using the console? ie:
document.cookie = 'key=value';
And get access to a post for editing? Perhaps I should be creating a unique id to use as a cookie that I then check for when the actual creator visits the page? If so, how might I go about this to best ensure only the actual creator of the post has access to editing?
You can restrict JavaScript manipulation by setting the HttpOnly flag in the cookie on a response. The console won't be able to set it programatically.

Send token stored in cookie to server and get boolean return

I dont know if this is even possible to do. I have searched a lot on the web with no big help to prove that it could work.
What i want to do is to grab a token saved in a cookie. Then put this cookie in a freemarker function call. So then the server will reply true or false. Depending on if the token is valid or not. If it is valid the content will be written.
<#if (object.somefunction (GrabTokenAndSendIt) )!false> Show Content </#if>
Is it possible to do something like this? Im new to freemarker. So any tips is helpful here.
I use the following command in javascript to grab the token from the cookie
localStorage.getItem('userToken')
FreeMarker doesn't prove anything to access HTTP or servlet related stuff out of the box. It's up to the web application framework to expose such things to it, if it wants to, but usually it shouldn't. FreeMarker is mostly used as MVC View, and as such, it shouldn't deal with non-presentation issues like cookies. You should check that cookie in the MVC Controller, then put into the date-model (aka. template context) if the visitor is authorized to see that conditional content or not.

Javascript - Show Asterisk or bullet dot in text fields and labels for which user dont have permission to view

I have a requirement, wherein, I need to display asterisk or bullet dot for fields which user does not have view access. I do not want to hide the entire label or text but to show them as read only but with asterisk data.
Another thing that I want to ensure if, the asterisk or dot are just for viewing, but when I submit my form, I want the actual contents to be posted, instead of asterisk or dot.
I, had implemented it by using password type field for fields for which user does not have view access.
Is there any other better way or a Jquery plugin, that might be handy for this requirement.
Thanks.
As saied by epascarello, this is not secure as even if you mask the content, user can easily modify the content by editing HTML and perform HTML injections.
If you want to do something like that, this should be done on Server Side (the service called)
Add more info on your architecture, what you have access to and what can not be modified and we may find a proper solution for that.
It defeats the purpose if you bring the read-only value to client side. No matter whether you show * in the field or not, user can read the value somehow because the value has been brought to client side. User can see the page source or page DOM using a debugger to see what data is on the page. User can also see the HTTP request/response to get the data. Therefore a pure client side solution will not work.
Your solution depends on how you render the page:
Server side rendering like JSP/PHP etc.: In this case you render the whole page contents from server. Therefore you can decide whether user has read permission on a field or not and render the field appropriately. Typically you would render the read only fields as a label with * so that (a) values never reach client - keeping it secure and, (b) field will not even be posted back to the server when the user posts the form to the server. On the server side you will handle the posted values as field level updates. That is necessary to avoid blanking out the read-only fields which are not even posted in the first place!
Client side rendering: In this case your client talks to the server using some kind of service. Recent trend is using a RESTful service responding with JSON content. In such a case your JSON should indicate each field with its value and read-write permissions. Fields with read-only permissions should not have the value so that it is secure. Client side JS code should look at the read-only flag and render the data as a label with * in it. I am not aware of any ready-made JS component for doing this. You can implement a reusable component to go with the client side library you are using. For example - if you are using jQuery you can implement a jQuery plugin, if you are using angularJS you may implement a directive etc.
Hope that helps.

Hide the url in a Grails application

Is there a way to hide the url in the address bar with Grails application. Now users of the web application can see and change the request parameter values from the address bar and they see the record id in the show page.
Is there a way in Javascript or Groovy (URL Mapping) or Grails (.gsp) or HTML or Tomcat (server.xml or conf.xml or in web.xml inside application in the webapps)
ex(http://www.example.com/hide/show /) i want to avoid this url and always see (http://www.example.com) or (http://www.example.com/hide/show) without the record id
Is there a way to prevent this?
No, most browsers doesn't let you hide the address field, even if you open a new window using window.open. This is a security feature, so that one site can't easily pretend to be another.
Your application should have security checks so that one user can't access data that only another user should see. Just hiding the URL would not be safe anyway, you can easily get around that using tools built into the browser, or readily available addons.
It's part of the restful URL pattern implemented by grails.
Your best bet to hide the URL would be using an iframe within the page you want the user to see in their address bar.
Not quite sure what you mean, but I would change the default root URL mapping in UrlMappings.groovy so it looks a bit like this:
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
//Change it here!!!!
"/"(controller: 'controllerName', action: 'actionName')
Where 'actionName' and 'controllerName' are what you want them to be - 'hide', 'show' in your example?
Than pass all parameters via a post instead of a get, just change the <g:form> method.
You will still obviously need to implement any security checking required in the controller as stated by other posters.
Thanks,
Jim.
You can probably handle this using a variation of Post/Redirect/Get:
http://en.wikipedia.org/wiki/Post/Redirect/Get
At our Grails site we have a lot of search fields. When a user clicked a pagination link all those search fields ended up in the URL which created ugly URL:s with a higher risk that users bookmarked those addresses which could mean future problems.
We solved this by saving not only all POST but also GET with parameters into the session, redirect to GET without parameters and append those again in the controller. This not only creates nice URL:s but also a memory so that if a user goes back to an earlier menu, then selected details within that menu are redisplayed.
For your specific request to hide the id in "show/42" you can probably handle that likewise or possibly configure Grails to use "show?id=42" instead, but we don't have that requirement so I haven't looked further into that issue. Good luck!
Forgot to mention: this won't add much to security since links will still contain ids, it will only clean up the address bar.
Here's some sample code that should work. If show?id=42 is called, it saves id=42 in the session, then redirects to just show and id=42 is added to params before further processing. It does what you want, but as commented it might not always be a wise thing to do.
def show = {
if (request.method == 'GET' && !request.queryString) {
if (session[controllerName]) {
params.putAll(session[controllerName])
// Add the typical code for show here...
}
} else {
session[controllerName] = extractParams(params)
redirect(action: 'show')
return
}

Categories