using sessions to add an edit button for the right user - javascript

Lets say I have a lot of reviews on a web page. and I have a req.session.shortId = f43f1. I'm new to sessions but I think that each person that goes to the page will have their own req.session.shortId. (I have this in my schema shortId : {type : String, unique : true, default : shortId.generate}, )
some reviews are made by one person and I want to have those reviews have an edit button. only the person that has the session should be able to see the edit button. I have on the page something like this <div class = "f43f1">Review</div> , <div class = "f43aa">Review</div>. I only want f43f1 to have the button because that is the value of req.session.shortId. I was thinking of doing something like this on the server.
if(req.session.shortId == req.body.shortId){
I really don't know what to do
how would I tell the user's div that he can edit the button
I do stuff like this
res.render("index", {user : user, comp, comp, how do I send out tell the specific div to put the edit button })
}
Truthfully I don't even want the shortId in the div because of security concers. I don't know how developers handle this type of situation

It seems like you would have that shortId stored with your review in the database. Which should make it easy enough to do something like this in your node app:
res.render('index', {shortId: req.session.shortId, review: review});
Then on your ejs template you should be able to conditionally display the button similar to something like this:
<% if (shortId === review.shortId) { %>
<button type="submit">Edit</button>
<% } %>
Sorry if the syntax is a little off here, it's been a while since I've worked with EJS.

Related

if role is admin append a td

i need to check if user role is admin, append a <td>to the table. in other word i have a table as below in my jsp page:
title | description | action
-----------------------------------
.... ...... answer
i want when user role is admin, in the action column see is added. like this:
title | description | action
-----------------------------------
.... ...... answer|see
my jquery code for this is:
$('#my-rows').append($('<tr>')
.append($('<td>').text(poll.title))
.append($('<td>').text(poll.description))
.append($('<td>').append($('<a style="text-decoration: none">').attr({
'onclick' : 'VoteFor(' +poll.poll_id+ ')'}).text('answer'))).append(('${hasRoleAdmin}' == true ? $('<a>').attr({
'onclick' : 'ViewPoll(' +poll.poll_id+ ')'}).text('see'):'')))
and hasRoleAdmin is a variable that i have defined in my jsp page like this:
<sec:authorize access="hasRole('ROLE_ADMIN')" var="hasRoleAdmin"></sec:authorize>
but it doesn't work and my table is as what i showed first earlier above and i can't get see as it is in second table. how can i put my condition on append? can you help?
If I understood correctly -
Since you have Spring security in picture, you can simply:
Hard code your wherever you want.
wrap it in your spring security tags something like this:
<sec:authorize access="hasRole('ADMIN')"><td>your</td></sec:authorize>
Handle security in your SecurityConfig.
should do the trick. That means, no other role should be able to view that tag at all other than Admin. Let the spring security handle it for you. There is no need to hide/unhide/enable/disable using JS/JQ etc.

Event on Keystone JS view not working

I'm doing an e-commerce site (learning purposes) with KeystoneJS. In the view where I display all the products I want to add a filter for sort the items by price and another one to show the products of only one brand. Two forms are needed but I don't get to submit only one
My products.pug looks like this
.container
form(method='post')
input(type='hidden', name='action', value='products')
button(type='submit').btn.btn-primary Send
And my products.js in routes/views/ looks like this
[...]
// Print a word when submit the form
view.on('post', { action: 'products' }, function(next) {
console.log('POST')
next()
})
// Get all products from db
view.on('init'...)
// Render
view.render('products')
So basically what I want to do is to print POST when I hit the button in the view. Instead of that, I receive a 404 error page. I would really appreciate if you guys can help me
Got it! In /routes/index.js I replaced
app.get('/products', route.views.products);
for
app.all('/products', route.views.products);
I feel dummy but happy.

How bind select options in the HTML with two pre-defined values to insert data in mongodb

I create an event creator in my admin dashboard, and everything is working ok, but now i need insert a new field:
info: Object
In my HTML event creator, i have this selection:
<label for="info">Information Type:</label>
<select id="info" name="info">
<option>Normal</option>
<option>Special</option>
</select>
With a post to /create
When this event arrive in my controller, i need save all the form inputs in my database, and is fine, this part is 100% working.
But, before make the save, i am using this code to bind the select option with the real value of the field info in the database:
event.pre('save', function(next) {
if (this.info === 'Normal') {
this.info = ['this text', 'is one text, but i want show as a list', 'that's why i am doing this']
} else if (this.info === 'Special') {
this.info = ['same', 'happens', 'here']
}
});
I want know if this is right, is working, but for me looks wrong.
So for example, if i choose 'Normal', will appear like this:
<ul>
<li>This text</li>
<li>is one text, but i want show as a list</li>
<li>that's why i am doing this</li>
</ul>
I want know if the whole thing is right, and if not, how to do it right. I also want alternatives using only HTML if possible, without using the pre save.
Thanks in advance.
If your info field's values are constant I think your solution is the best.
But if you need to use dynamic values for your info field you might change your codes as like here;
http://jsfiddle.net/oprz2p2e/
If you have a lot of fields on your form, you can collect your data using jQuery $("#yourFormId").serialize() method.
ps: I think you know how to show this data using EJS. You can list info field values using forEach together EJS.

How Do I Overlay a Popup View in Mithril.js?

As a practical exercise in learning bare-bones JS programming in depth (on up to date browsers), I am building an SPA to maintain customer records. The only external library I am using is Mithril.js MVC. So far I have got a table view with live data from my database, which includes edit, merge and delete buttons for each record. The editing is done and working well, using an inline "form" and save/cancel for that works.
I am now trying to implement delete and merge, both of which need a popup confirmation before being actioned, which is where I am stuck. I know exactly what I'd do in a desktop GUI environment, so the roadblock may be my lack of understanding of the browser front-end more than of Mithril, per se.
Ideally, I'd like to create a self-contained, reusable "popup" component represent the popup, but I can't see how I should go about doing this in JS using Mithril, in particular, but not solely, how to make Mithril to overlay one view on top of another.
Any assistance would be appreciated, from a broad outline to specific code snippets.
You probably want to use a view model flag to control the modal popup's visibility.
//modal module
var modal = {}
modal.visible = m.prop(false)
modal.view = function(body) {
return modal.visible() ? m(".modal", body()) : ""
}
//in your other view
var myOtherView = function() {
//this button sets the flag to true
m("button[type=button]", {onclick: modal.visible.bind(this, true)}, "Show modal"),
//include the modal anywhere it makes sense to
//its visibility is taken care by the modal itself
//positioning is controlled via CSS
modal.view(function() {
return m("p, "modal content goes here")
})
}
To make a modal dialog, you can either use the styles from one of the many CSS frameworks out there (e.g. Bootstrap), or style .modal with your own CSS
/*really contrived example to get you started*/
.modal {
background:#fff;
border:1px solid #eee;
position:fixed;
top:10px;
left:100px;
width:600px;
}
I don't know if I am just not quite getting MVC, but I simply set a view-model object that contains the detail of the popup, and then when generating the view if that is currently set I populate the div containing the popup. CSS controls the look and positioning.
So basically I am relying of Mithril's top-down re-render approach to conditionally build the view based on current application state -- it works really well and is immanently sensible to me.
I actually used a list of popup confirmation objects, so multiple confirmations can queue up.
In the controller, make a confirmation queue:
function Controller() {
...
this.confirmation =[];
...
}
In the view, create a confirmation view div if there's a confirmation queued, or an empty placeholder otherwise (Mithrils differencing works best if container elements don't appear and disappear from render to render):
function crtView(ctl) {
...
return m("div", [
...
crtConfirmationView(ctl),
...
]);
}
function crtConfirmationView(ctl) {
var cfm=ctl.confirmation[0];
return m("div#popup-confirm",(cfm ? muiConfirm.crtView(ctl,cfm.title,cfm.body,cfm.buttons) : null));
}
Then, whenever a confirmation is needed, just push a confirmation object into the queue and let Mithril's drawing system run and rebuild the view.
function deleteRecord(ctl,evt,row,idx,rcd) {
var cfm={
title : m("span","Delete Customer: "+rcd.ContactName),
body : [
m("p","Do you really want to delete customer "+rcd.CustomerId+" ("+rcd.ContactName+") and all associated appointments and addresses?"),
m("p.warning", "This action cannot be undone. If this is a duplicate customer, it should be merged with the other record."),
],
buttons : deleteButtons,
proceed : "delete",
index : idx,
record : rcd,
};
ctl.confirmation.push(cfm);
}
The confirmation object contains whatever properties that the confirm helper function crtView needs to create a confirmation view and then take action when the user clicks a button (or presses ENTER or ESCAPE, etc) -- just standard UI stuff that you abstract away into shared reusable components.
Note: Just in case anyone has questions about the array index, I have since moved away from using the array index to identify the record in the data model (when the delete is complete the array element should be removed). Instead I locate the affected record using database ID, which is resilient against intervening changes in the model, like sorting the list.

Using the same JQuery tokeninput box multiple times on a page

I am using Jquery TokenInput in my rails app to help users quickly input information. Each user has a profile with many items of the same class on it, call them college_items. Each college_item has its own edit link, which pops up a modal with the appropriate edit form for the modal.
I followed Ryan Bates's screencast and got TokenInput working properly using the following code:
In application.js:
$(function() {
$("#education_major_tokens").tokenInput("/majors.json", {
theme: "facebook"
})
});
In my view:
<%= f.text_field :major_tokens %>
In my model:
def major_tokens=(ids)
self.major_ids = ids.split(",")
end
The problem I'm running into is that this same field appears in each edit form, so in the edit form for the first item everything works perfectly, but in the edit form for any other item the javascript is not initialized. My question is how can I change the javascript to initialize each time this form element appears, not just the first?
EDIT:
I thought something like this might be the solution:
$(function() {
$("#education_major_tokens").each(function(){
$(this).tokenInput("/majors.json", {
theme: "facebook"
})
});
});
but it still isn't working for me. Anyone out there have any ideas?
EDIT 2:
Figured this out finally. See my edit above, only instead of using #education_major_tokens, I set each input to have :class => "major_input" and changed "#education_major_tokens" in the code to ".major_input"
I think this is a bit late, but try to assign a class to your token field
<input class="yourtokenfield" type="text" />
After that use this
$(function() {
$(".yourtokenfield").each(function(){
$(this).tokenInput("/majors.json", {
theme: "facebook"
})
});
});
I think your problem is due to improper name for class, and remember ID must only appear once in your HTML document.

Categories