Javascript field editable only to admins - javascript

I have a field called ProductName that has a specific product name in it. When logged in any user can update the product name by clicking on the text and hitting save.
The code came from http://www.appelsiini.net/projects/jeditable for this to be possible.
I have roles set up in ASP.net VB for admins and non-admins and was wondering if there is any way in the Javascript to state that only admins are allowed to edit that field.
This is the Javascript code for the editable field:
$('.productName.edit').editable(function (value, settings) {
var ProductID = $('input#body_ProductID').val();
var result = SubmitProductName(ProductID, value);
return (value);
}, {
width: '350',
submit: 'Save Changes',
cancel: 'Cancel',
onBlur: 'ignore'
});
Here is the field itself in ASP:
<asp:FormView ID="fvProduct" runat="server" DataSourceID="dsProduct">
<ItemTemplate>
<h1 class="productName edit"><%# Eval("ProductName")%></h1>
</ItemTemplate>
</asp:FormView>
I would really appreciate any help. Thanks.

You could do this in javascript, but this will be bypass-able for anyone disabling/hacking javascript (which is very easily doable). You should do this on server-side.
If you really want to do this in javascript, just check permission through an ajax call.

You should do this on server side but still if you want to do this on client side then when a user logs in you can store a cookie that keeps track of whether he is an admin or non-admin.Now when someone tries to edit the field check whether that cookie you stored says he is an admin or not. If he is admin then allow editing otherwise not.

Related

How to dynamically set email recipient on wordpress contact form 7 plugin

I would like to dynamically set the email recipient of a wpcf7 contact form.
The step by step process of the user journey is as follows:
The website provides multiple law services. A user goes into one of these service pages and within each service page there is an element which generates a loop for a custom post type called 'Solicitor'. Each solicitor which provides this service is displayed in a grid.
The user clicks on a call to action on the solicitor they wish to contact.
This triggers a popup (I'm using the Popup Maker plugin) This popup contains a simple wpcf7 form with inputs such as name, email, message, etc. The user fills in the form and sends the contact form.
I want the contact form input to be emailed to the solicitor which the user clicked on.
My approach has been to get all contact solicitor call to actions and loop through them. Each of these call to actions have a data-id attribute with the corresponding solicitor post-id.
const solicitorContactBtns = document.querySelectorAll('.cta');
solicitorContactBtns.forEach(solicitorContactBtn => {
solicitorContactBtn.addEventListener('click', () => {
// Was planning on getting the data-id attribute (post-id) and somehow setting the recipient email to the 'email' custom field of this post-id. Not sure how to do this or if this is event possible?
});
});
I may be using the wrong approach any help is much appreciated.
I faced exactly the same problem on a recent project. The solution is to make each solicitor a page of their own. Perhaps "/contact-solicitor-bob" for example. Useful anyway since they can display info personal to them on said page. Then the clever part. On this personal page you add a meta-data called (say) "form_recipient" and to that you add their email address.
In your functions file you add this:
add_filter( 'wpcf7_before_send_mail', 'md_before_send_mail_function', 10, 3 );
function md_before_send_mail_function( $contact_form, $abort, $submission ) {
$postId = $_POST['_wpcf7_container_post'];
$formID = $_POST['_wpcf7'];
$emailFromCustomField = get_post_meta($postId, "mail_recipient", true);
if(!empty($emailFromCustomField)) {
$properties = $contact_form->get_properties();
$properties['mail']['recipient'] = $emailFromCustomField;
$contact_form->set_properties($properties);
return $contact_form;
}
...that's it.
A work around of the 'wpcf7_before_send_mail' hook is to create a new email input, make that shortcode the 'To' field in the mail tab like so:
And then hide the input with some CSS, e.g.
input[name="admin-email"] {
display: none;
}
Then use something like this below.
Get the dynamic email however you like, in this case, I'm just declaring it:
<?php $admin_email = 'email#yourdomain.com'; // get your email address ?>
Then using some jQuery to set the value of the admin email input.
<script type="text/javascript">
(function($) {
$('input[name="admin-email"]').val('<?php echo $admin_email; ?>');
})( jQuery );
</script>

How do I prevent users without admin access from saving a form with a certain status in faces

I'm trying to prevent users without Administrative access from saving a form with the "complete" status selected, if it was not already selected (e.g. users are allowed to open up forms and make edits to their data, even if the status is set to complete, they just cannot initially mark their documents as complete).
The reason users are allowed to make changes to 'completed' documents is that the electronic record is just a reflection of a behinds the scenes work process. In order for an item to be marked as complete, several other processes have to have been completed. The information can be edited after the fact to account for errors in transcription or verbiage.
I'm thinking that it would be sufficient to just utilize an onChange event that re-selects the previous selection if a user tries to change the status to complete . I'm looking for an elegant way to do it, hopefully without storing the previous selection in a separate field on the page, as it is already stored elsewhere.
the grantBacking.editGrant.statusCode is the saved/current status code for the form. Also, there are at least three different role types including just read access, 'Add', and 'Administrator'. Read - self explanatory, Add - Can make changes to the form but should not be able to complete a form, and Administrator - can make changes and can mark a form status as "complete".
This is what I have so far:
<t:panelGroup>
<sec:authorize ifNotGranted="ADMINISTRATOR">
<h:selectOneMenu id="grantStatus" onchange="#checkGrantStatusPermissions(this,grantBacking.editGrant.statusCode)" onmouseover="Tip('#{msg_bundle.grant_status_help}')" value="#{grantBacking.editGrant.statusCode}">
<f:selectItems value="#{grantBacking.grantSelectStatusForNonAdmin}" />
</h:selectOneMenu>
</sec:authorize>
<sec:authorize ifAnyGranted="ADMINISTRATOR">
<h:selectOneMenu id="grantStatusForAdmin" onmouseover="Tip('#{msg_bundle.grant_status_help}')" value="#{grantBacking.editGrant.statusCode}">
<f:selectItems value="#{grantBacking.grantSelectStatus}" />
</h:selectOneMenu>
</sec:authorize>
<sec:authorize ifAnyGranted="ADD">
<a4j:commandLink id="qsave2" render="#all" onmouseover="Tip('Click to quick save')" action="#{grantBacking.saveGrant}">
<h:graphicImage title="Click this to quick save the grant/contract" style="border-style:none;" height="20px" width="15px" library="default" name="img/icons/disk.png" />
</a4j:commandLink>
</sec:authorize>
<script type="text/javascript">
function checkGrantStatusPermissions(field, originalValue){
if(originalValue.equalsIgnoreCase("complete")){
return
}
else{
document.getElementByID(field).value = originalValue.value;
}
}
</script>
Prior to the item being marked as complete you can disable the option by building your selectItems like so:
<f:selectItems value="#{grantBacking.grantSelectStatusForNonAdmin}" var="v"
itemDisabled="#{grantBacking.shouldDisableOption(v)}"/>
If your version of the EL doesn't include the ability to pass parameters you can accomplish the same by using an inner class that holds your value, label, and has a parameterless method for shouldDisable.
When it comes to submitting a completed form if the user can't change it from Complete to some other status, then just make the selectMenu readonly. If they can, then your shouldDisable logic should return false in this case.
Doing something like this prevents the users from selecting known bad values and avoids you coding behavior that the users wouldn't expect leading to potential bug reports.

Disable HTML5 input using php

I gt a php form script that allow user to input data into database but then there is another script that allow the user to edit the data in database using the same form script. My problem is when i want to edit the data, i want to disable certain input field from the form script that don't allow user to make changes. Can anyone teach me how?
There are many solutions.
You can set a flag by start the EDIT and check of this flag by START-EDIT. Quick'n dirty.
But you can lock the TUPLES for everyone - when not remove the flag
In your database (setting table) make new column named "editmode".
And in your editor page you can define "editmode" value.
For users check "editmode" value from database:
while($row = mysqli_fetch_assoc($editmode_check))
{
$editmode= $row['editmode'];
}
if ($editmode==1) {
echo "Admin on Edit or ...";
} else {
... the page ...
}

Update database attribute from Javascript

In my ruby on rails app, I am trying to allow a user to change a field on the screen and as a result, update the database.
A user is promoted with the following screen:
<td id="sb_user-<%=server.id%>" ondblclick="changeUser(<%= server.id %>);"><%= server.sb_user %></td>
When they double click on the sb_user field, a javascript function is called and changes the field to a textbox with a simple go button:
<script type="text/javascript">
function changeUser(id) {
//Stop the auto refresh until user hits enter
clearInterval(refreshInterval);
$("#sb_user-"+id).html("<form name='user'><div class='input-append'><input name='user_input' class='span1' id='appendedInputButton' size='16' type='text'/><button class='btn' type='button'>Go!</button></form></div>");
}
</script>
When a user enters text into the textbox and clicks go, I need it so that the database field server.sb_user is updated to whatever the user entered in that field.
Anyone have suggestions on how to do this?
What you are searching for is in place editing. Theres a railscast for that:
http://railscasts.com/episodes/302-in-place-editing

Questions about cookies and sessions in ASP.net application

I am writing an ASP.Net application that allows anonymous people to post prayers and others to comment on/confirm to pray for these objects. Prayers are stored in a SQL Server 2008 database with a unique identifier.
They are displayed using a repeater control and a hidden field to store the ID of the row. Each item in the repeater contains a button that allows anonymous people to pray and this is incremented as a counter inside the database.
Basically, once a user has confirmed that he/she is praying for this item, I want to disable the button and display the total count for that row.
It is my understanding that I can store data in cookies/sessions so the only solution I could come up with so far would be to store the ID of the row into one of these objects and then use custom logic inside of my repeater control to check to see which are present.
Can anyone offer some insight as to what the most efficient way to accomplish something like this might be? If there are options other than cookie or session I'd be glad to hear that too.
EDIT:
I am trying to implement this solution using the following logic.
Codebehind:
protected bool IsPrayerInCookie(string prayerId)
{
if(Request.Cookies["prayers"][prayerId] != null)
{
return false;
}
else
{
return true;
}
}
ASPX:
<span class="confirmed_prayers"><span class="trans">
<asp:Label runat="server" ID="lblConfirmedPrayers" Text='<%# Eval("ConfirmedPrayers") %>' />
people have prayed for this.</span></span>
<% if(!IsPrayerInCookie(Eval("PrayerId").ToString()))
{
%>
<asp:LinkButton ID="btnPray" CssClass="but_styled" runat="server" TabIndex="8" CommandName="IncrementPrayer">
<span><span class="check">
Pray for This</span></span></asp:LinkButton>
<%
}
%>
This isn't working however. Can anyone help me figure out how to make the if statement work inside of the aspx file to properly call the code behind method with the correct ID?
Session will only last as long as the user is on the site. Therefore, if they close their browser and come back, it will be gone.
Cookies would be the better choice, and only if they clear their cookies will this data be gone.
If you don't require the user to log in, I'm thinking this is all you could do.
Heres the MSDN page on cookies:
http://msdn.microsoft.com/en-us/library/ms178194.aspx
For the actual cookie storage, I would do something like:
Response.Cookies["prayerlist"][CurrentPrayerItemID].Value = "something"; //All that matters is that they have the cookie with this ID.
Response.Cookies["prayerlist"].Expires = DateTime.MaxValue;
So when someone clicks to add that item, you will first want to check to see if they already have that id in their cookie, like so:
if(Response.Cookies["prayerlist"][CurrentPrayerItemID] != null)
{
Response.Cookies["prayerlist"][CurrentPrayerItemID].value = "something";
// Add prayer to Database
}
And likewise, you would check the cookie whenever you bind the repeater. If they have that cookie, you would disable the corresponding pray button.
I'm not sure how to approach this, since idk how your binding, but it will look something like this:
foreach(Item item in YourListOfItemsThatYouAreBindingToTheRepeater)
{
if(Response.Cookies["prayerlist"][CurrentPrayerItemID] != null)
{
//Disable Button - Set "HasPrayed" = true
}
}
To actually disable the button, what i would do is set a value in your list to false, and then in the aspx page, do something like this:
<asp:Button ID="button1" runat="server" Enabled='<%# !(bool)Eval("HasPrayed") %>' />
Using !(bool)Eval("HasPrayed") since you want to set enabled to false if HasPrayed is true.
You can use sessions to store the prayer items that the user has clicked on, but when they come back to your site it will forget all the previous items because the session has been lost.
In this case you can use a cookie to store all the prayer item ids that the user has clicked the "I'll pray for this" button. I'd go this route if you don't want to require user logins.
For the code you're describing, I think you could use an ASP.NET UpdatePanel which will allow you to update/show the number of people praying for the item and to disable the button.

Categories

Resources