Forbidden (CSRF cookie not set.): - asp.net

i am using ajax to post data from asp (as front) to Django rest api (as backend)
First, I had a problem in Accessing to different domain but it solved using CORS
then i had another error which is related to CSRF
and the error like above :Forbidden (CSRF cookie not set.)
i've used #csrf_exempt to pass this validation but i want a solution for use it without csrf exmption
i tried more than one solution but it's not working or maybe i dont understand the way
Is there any clearly solution to solve it in ajax
In Error 403 ,
'''
JQuery sends " xhr.send( options.hasContent && options.data || null );
'''
i'll include code of my .cshtml file bellow
'''
form id="std_form" class="mx-auto form-horizontal" method="POST" asp-antiforgery="false">
#Html.AntiForgeryToken()
<div class="box-body">
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="first">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="second">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="third">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer d-flex">
<button type="submit" id="save_btn" class="btn-success btn">Save</button>
</div>
<!-- /.box-footer -->
</form>
</div>
'''
'''
window.CSRF_TOKEN = "{% csrf_token %}";
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
'''
and this is ajax request
'''
$(document).on('submit', '#std_form', function (e) {
e.preventDefault();
let val1 = parseInt($('#first').val());
let val2 = parseInt($('#second').val());
let val3 = parseInt($('#third').val());
let x={val1,val2,val3};
$.ajax({
type: 'POST',
url: ('http://127.0.0.1:8000/Callfun/processdata/'),
data:{
First: val1,
Second:val2,
Third:val3,
csrfmiddlewaretoken: window.CSRF_TOKEN,
},
success: function (context) {
alert("Wooooooooowwwww");
$('#first').val(context.Max);
$('#second').val(context.Min);
$('#third').val(context.Avg);
},
error: function (context) {
alert("So Bad");
}
})
})
'''

Related

$(...).jqBootstrapValidation is not a function at HTMLDocument.<anonymous>

i am trying to implement a contact us page using bootstrap template. I am a really beginner in asp.net and its my first time using a template.
I cant really get it where is the problem that is causing the above error.
I want to when the user click the send Message button to send emails to a current business email.
Can anyone help me?
contact.cshtml
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Full Name:</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Phone Number:</label>
<input type="tel" class="form-control" id="phone" required data-validation-required-message="Please enter your phone number.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email Address:</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message:</label>
<textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
</form>
</div>
</div>
</div>
<script src="~/Content/vendor/jquery/jquery.min.js"></script>
<script src="~/Scripts/contact_me.js"></script>
<script src="~/Scripts/jqBootstrapValidation.js"></script>
<script src="~/Content/vendor/bootstrap/js/bootstrap.min.js"></script>
contact_me.js
$(function () {
$('#contactForm input,#contactForm textarea').jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
As my answer morphed through the comments:
the answer was that the OP added Jquery twice making a conflict in
file jqBootstrapValidation.js
Also, to help others based on the OP's post, this next part could be helpful as well:
Javascript files need to be loaded in the order of their dependence. Since your custom javascript file, contact_me.js depends on functions contained in the javascript file, jqBootstrapValidation.js, you need to load jqBootstrapValidation.js before contact_me.js, to fix this switch the order in which these files are loaded:
<script src="~/Content/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="~/Scripts/jqBootstrapValidation.js"></script>
<script src="~/Content/vendor/jquery/jquery.min.js"></script>
<script src="~/Scripts/contact_me.js"></script>

ASP.NET Core 2.1 File Upload Form doesn't reach controller

This is my controller
[ValidateAntiForgeryToken]
[HttpPost("Save")]
public async Task<ActionResult> SaveAsync(UploadDocumentViewModel Input)
{
var filePath = $"{this.hostingEnvironment.WebRootPath}/documents";
foreach(var item in Input.Files)
{
var fileName = ContentDispositionHeaderValue.Parse(item.ContentDisposition).FileName;
var fullFilePath = Path.Combine(filePath, fileName);
using(var stream = new FileStream(fullFilePath, FileMode.Create))
{
await item.CopyToAsync(stream);
}
}
return this.Ok();
}
This is the form that I am uploading from
#using (Html.BeginForm("Save", #ViewContext.RouteData.Values["controller"].ToString(), FormMethod.Post, new { enctype = "multipart/form-data",id = "form" }))
{
#Html.AntiForgeryToken()
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.LabelFor(m => m.Categories)
#Html.DropDownListFor(m => m.Categories, (SelectList)Model.Categories, "", new { #class = "form-control col-sm-12" })
#Html.ValidationMessageFor(m => m.Categories)
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input id="Files" type="file" name="Files" multiple />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div class="clearfix">
<div class="pull-right">
<input type="submit" id="submit" value="Save" class="btn btn-primary" />
#Html.ActionLink("Cancel", "Index", #ViewContext.RouteData.Values["controller"].ToString(), new { }, new { #class = "btn btn-outline-secondary" })
</div>
</div>
</div>
</div>
</div>
</div>
}
When I am trying to upload my file, I get transferred to a 404 page. However, If I remove the async Task items from my controller, I can reach the controller just fine.
I am trying to follow this Microsoft tutorial but I can't seem to get it to work:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1
Your form is attempting to generate a route for a "Save" action, but you action name is actually SaveAsync. It worked when you removed the async stuff, because you likely changed the method name to Save as well at that point.
It's not traditional to name actions with the Async suffix, even if they are async (unlike other types of methods). As a result, I'd recommend simply removing the Async part of the method name, and you'll be fine. Otherwise, you need to change the reference in your form from "Save" to "SaveAsync" to match the name of the action.
FWIW, you're killing yourself using the HtmlHelper methods here. Use the tag helpers instead. For example, your from could be as simple as:
<form method="post" asp-action="Save" enctype="multipart/form-data">
...
</form>

How to update document of particular user id

Basically what I want to do is, just update user details.so when
I input user ID all the other details of user are displayed in
textbox. Then I can edit anything.
Below is my js code:
Template.body.onCreated(function() {
this.currentTextBox = new ReactiveVar();
});
Template.body.events({
"keyup .new-task1"(event, instance) {
instance.currentTextBox.set(event.target.value);
}
});
Template.body.helpers({
dbs() {
const instance = Template.instance();
return Dbs.find({'user_id':instance.currentTextBox.get()});
}
});
Template.temp.events({
"submit .sub"(event) {
const target= event.target;
const name1 =target.name.value;
const add1 =add.value;
const r1 = target.r.value;
const const1 = target.const.value;
console.log(doc_id1);
Dbs.update({"user_id" : "pid"},{"name" : "name1","r" : "r1","const"
: "const"});
}
});
Now the problem is I am not able to update the edited field, though the value of edited field is sent to js file from html.anyone help me to solve this issue as I am new to meteor and mongo db.
Html code:
<head>
<title>eg1</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
</head>
<body>
<nav class="#e57373 red lighten-2">
<div class="container">
<div class="nav-wrapper">
hello
<ul id="nav-mobile" class="right hide-on-med-and-down">
</ul>
</div>
</div>
</nav>
<div class="row">
<div class="col s2">
<form class="new-task">
<input type="text" name="pid" placeholder="patient_id" class="new-
task1"/>
</form>
</div>
<div class="col s4">
<ul class="collection">
{{#each dbs}}
{{>temp}}
{{/each}}
</ul><br><br>
</div>
</div>
</body>
<template name="temp">
<li class="collection-item">
<form class="sub">
<input type="text" name="user_id" value=" {{user_id}}"/>
<input type="text" name="addd" value=" {{add}}"/>
<input type="text" name="r" value=" {{r}}"/>
<input type="text" name="const" value=" {{const}}"/>
<center><input type="submit" value="Submit" class="waves-effect
#607d8b grey btn"></center>
</form>
</li>
</template>
Welcome to Meteor :)
You have to use $set attribute when you are updating document,
use as below and let me know.
Dbs.update({"user_id" : "pid"},{$set:{"name" : "name1","r" : "r1","const" : "const"}});
For more info on Collection.update Click Here.
Also go through Mongo Update Query example to know how to update a document when you directly use mongo shell.
Remember there are few differences when you directly use Mongo Shell commands and Meteor Collections.

HTTP Status 500 - Expected session attribute 'consent'

this is my html form of consents. after posting the inputs i get error on the browser
<form th:object="${consent}" action="../users/userDetails.html" th:action="#{${#httpServletRequest.servletPath}}" method="post">
<fieldset>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Service Provider</label>
<select id="provider" name="provider" class="form-control" th:onchange="'javascript:showPIIDoc(this.value);'">
<option th:value="0" >Select a Service Provider</option>
<option th:each="provider : ${user.providers}" name="name" th:value="${user.id} +','+ ${provider.id}" th:text="${provider.name}" >[name]</option>
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">PII Document</label>
<select id ="documentdiv" class="form-control">
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Share with</label>
<select class="form-control">
<option th:value="0" >Select a user you want share the document to</option>
<option name="name" th:each="user : ${users}" th:value="${user.id}" th:text="${user.firstName} + ' ' + ${user.lastName}">[name]</option>
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Consent</label>
<div style="clear:both"></div>
<input type="checkbox" name="share" th:value="1" th:text="Share" />
</div>
<div style="clear:both"></div>
<div style="margin-top:10px;margin-left:10px" class="form-actions">
<button class="btn btn-primary" type="submit">Add Consent</button>
</div>
</fieldset>
</form>
this is my controller
#RequestMapping(value = "/users/{userId}/providers/{providerId}/documents/{documentId}/consents/new", method = RequestMethod.POST)
public String processNewConsentForm(#PathVariable("userId") int userId, #PathVariable("providerId") int providerId,
#PathVariable("documentId") int documentId, #ModelAttribute("consent") Consent consent, BindingResult result, SessionStatus status) {
User user = this.clinicService.findUserById(userId);
Provider provider = this.clinicService.findProviderById(providerId);
System.out.println("daghade");
System.out.println(provider);
Document doc = this.clinicService.findDocumentById(userId);
Consent c =new Consent();
c.setProvider(provider);
c.setDocument(doc);
c.setUser(user);
c.setStatus(c.getStatus());
c.setFriend(c.getFriend());
System.out.println(c);
if (result.hasErrors()) {
return "providers/createOrUpdateConsentForm";
} else {
this.clinicService.saveConsent(c);
status.setComplete();
return "redirect:/users/{userId}";
}
}
I get this error on the browser
HTTP Status 500 - Expected session attribute 'consent'
after submitting the form
This is the code of Controller for GET Method. it used to call the consent form
#RequestMapping(value = "/users/{userId}/providers/{providerId}/documents/{documentId}/consents/new", method = RequestMethod.GET)
public String initNewConsentForm(#PathVariable("userId") int userId,#PathVariable("providerId") int providerId,#PathVariable("documentId") int documentId, Model model) {
User user = this.clinicService.findUserById(userId);
Provider provider = this.clinicService.findProviderById(providerId);
Document document = this.clinicService.findDocumentById(documentId);
Collection<User> users = this.clinicService.AllUsers();
Consent consent = new Consent();
model.addAttribute("provider",provider);
model.addAttribute("document", document);
model.addAttribute("user", user);
model.addAttribute("users", users);
return "providers/createOrUpdateConsentForm";
}
add model.addAttribute("consent", consent); in your GET method.

Form validation in meteorjs

I am doing simple validation of inputs in meteorjs, after first tour it works, and every next time it doesn't work (until I reload the page) – it means error messages are not displayed.
//main.js//
Template.addMealForm.events({
'click #submitNewMeal': function (ev) {
ev.preventDefault();
var query = {
name: $("#name").val().trim(),
price: $("#price").val(),
calories: $("#calories").val(),
category: $("#category").val()
};
areInputsValid(query);
}
});
var areInputsValid = function (query) {
if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("All fields are required");
}
else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("To Price and Calories fields please enter a number");
}
else {
console.log('it works');
$('.dn').hide();
}
};
//main.html//
<template name="addMealForm">
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
</div>
<div class="form-group">
<label for="price">Price</label>
<input class="form-control input_form" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="calories">Calories</label>
<input class="form-control input_form" id="calories" placeholder="Calories">
</div>
<div id="warningLabel" class="form-group has-error dn">
<label class="control-label warningLabel"></label>
</div>
<button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
</form>
</template>
The problem is that you are calling $('.dn').hide() in the success case. Because #warningLabel has a class of dn it will not be displayed again on subsequent errors.
One solution is to add $('.dn').show() to the top of areInputsValid.
You already have Tracker as part of Meteor, so I put a little tutorial and JSfiddle together on how to use it to implement a typical form validation scenario.
http://bit.ly/meteor-form-validation-video
http://bit.ly/meteor-form-validation-fiddle

Resources