XMLHttpRequest 401 (Unauthorized) - ajax

I am trying to Create Post in user interface.
When I logged in as Admin and insert
createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);
to the below code, Create Post success. But I don't want to use nonce, I want use user and password, but I got this error: 401 (Unauthorized). I tried to replace btoa to Decode64 but it not work. Do I miss anything?
var createPost = new XMLHttpRequest();
createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/posts", true);
createPost.withCredentials = true;
createPost.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
createPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
createPost.send(JSON.stringify(ourPostData));
createPost.onreadystatechange = function() {
if (createPost.readyState == 4) {
if (createPost.status == 201) {
document.querySelector('.admin-quick-add [name="title"]').value = '';
document.querySelector('.admin-quick-add [name="content"]').value = '';
} else {
alert("Error - try again.");
}
}
}

Related

React native: How to validate username and password while submitting

I have validate username and password,if username and password is wrong ,then i want through error like 'Invalid username/password'.if any one know,pls let me know.
async submit() {
//Validating username and password
const { username, password } = this.state;
if(username == ''){
this.setState({error:'Username is required'});
} else if(password == ''){
this.setState({error:'Password is required'});
} else {
this.setState({error: null})
let collection={};
collection.username=this.state.username;
collection.password=this.state.password;
// console.warn(collection);
var url = 'my url';
try {
let response = await fetch(url,
{
method: 'POST', // or 'PUT'
body: JSON.stringify(collection), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
});
let res = await response.text();
// console.warn(res);
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
console.log(accessToken);
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
// console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
//Handle error
console.log('Success:',response);
let error = res;
throw error;
}
} catch(error) {
console.log("error " + error);
}
}
}
response after giving invalid username/password:
0 {…}
field :password
message :Incorrect username or password.
I have written code like this based on status to validated username/password is correct/wrong.so here am posting code if it is useful for anyone in future.below code is,
if (response.status >= 200 && response.status < 300) {
//Handle success
let accessToken = res;
//On success we will store the access_token in the AsyncStorage
this.storeToken(accessToken);
console.warn(accessToken);
//After storing value,it will navigate to home
this.props.navigation.navigate('Home');
} else {
console.log('Success:',response);
this.setState({error:'Invalid username/password'});
let error = res;
throw error;
}

Django REST, sudden 403 error in ajax call

I have a basic view
#api_view(['POST'])
def test(request):
id = request.POST.get("id")
response = {}
try:
obj = MyModel.objects.get(id=id)
response['can'] = False
except MyModel.DoesNotExist:
response['can'] = True
return Response(response)
In urls
url(r'^test', test),
And simple call in template:
$.ajax({
type : "POST",
data : {id:id},
url : "/test/",
success: function(data) {
if(data['can']){
$("#Test").show();
} else{
$("#Test").hide();
}
},
error: function(error) {
console.log(error);
}
});
And it has worked recently. But today, when I've tested this app I get error:
[22/Feb/2016 15:09:02] "POST /test/ HTTP/1.1" 403 58
which means "Forbidden access". I have no idea what's going on. Maybe you can help with that.
EDIT
I've just noticed that it happens on firefox browser. On ubuntu's "browser" and google chrome I don't have this 403 error.
EDIT 2 Oh, when I run firefox as private/incognito window I don't have this 403 error. I get this error only when I use 'normal' firefox.
Possible issue: It could be the previous user session is still in the browser cookie. try clearing the cookie of your firefox browser.
On the next try, you may encounter the issue again, so then you trace why certain user are not given permission.
There is no users or any permissions. This is app for 'not-login' users.
I've just added csrf protecion befor ajax call. (from django docs)
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
And it's work. Do I think right? This error was caused by a lack of csrf protection?

Return user id along with Ajax Success response

I have Ajax login submit that works just fine. Now i need to send the $user_id back to the login page on success. But cant figure out how.
Below is what i have.
This is the php page
<?
if (!securePage($_SERVER['PHP_SELF'])){die();}
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
//Forms posted
if(!empty($_POST))
{
$errors = array();
$username = sanitize(trim($_POST["user"]));
$password = trim($_POST["password"]);
//Perform some validation
//Feel free to edit / change as required
if($username == "")
{
$response['success'] = false;
}
if($password == "")
{
$response['success'] = false;
}
if(count($errors) == 0)
{
//A security note here, never tell the user which credential was incorrect
if(!usernameExists($username))
{
$response['success'] = false;
}
else
{
$userdetails = fetchUserDetails($username);
//See if the user's account is activated
if($userdetails["active"]==0)
{
$response['success'] = false;
}
else
{
//Hash the password and use the salt from the database to compare the password.
$entered_pass = generateHash($password,$userdetails["password"]);
if($entered_pass != $userdetails["password"])
{
//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
$response['success'] = false;
}
else
{
//Passwords match! we're good to go'
$response['success'] = true;
}
}
}
}
}
//$user_id = $loggedInUser->user_id;
echo json_encode($response);
?>
Here is the ajax that calls the php page. And also where i need to retrieve the ID from php page.
<script type="text/javascript">
//login ajax to send over user and pass LS
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var e = $("#user", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
var str = form.serialize();
//McDOn(str);
$.ajax({
type: 'POST',
url: 'http://vsag.actualizevps.com/loginmobile.php',
crossDomain: true,
data: {user: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
if (response.success) {
//alert("you're logged in");
window.localStorage["user"] = e;
//window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location = "create.html";
}
else {
alert("Your login failed");
//window.location("main.html");
location.reload();
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter user and password");
}
return false;
}
</script>
the $response value is just true or false at the moment, you could return an array:
$response = array("Success" => true, "UserId" => $user_id);
and on you AJAX response, the response variable
response.UserId
will contain the user id

django with ssl redirect and ajax post gives a 301 error

I am using this django snippet [1] to redirect to my https website. I know it does not work with POST requests so I did not add the {'SSL': True } in the all the url POST requests in my urls.py. However I always get a 301 error (in my access logs), although the view does what it is asked to do.
The view is 'called' by an ajax request and returns a json object.
def confirm(request, username):
if username == request.user.username:
user = get_object_or_404(User, username=username)
if request.method == 'POST':
response_dict = {
'status': True,
'added_total': count,
'username': username,
'message': message
}
return HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript')
else:
return HttpResponseRedirect('/fx/%s?page=%s' % (username, '1'))
else:
raise Http404(u'Not a valid user')
I also tried to add the {'SSL': True} argument but I still get the 301 error.
for ajax post requests I also use this snippet:
$.ajaxSetup({
beforeSend:function (xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != "") {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
What am I doing wrong?
EDIT: This is my action from urls.py
url(r'^confirm/(\w+)/$', confirm),
[1] http://djangosnippets.org/snippets/85/

AJAX to submit to page using POST method

I have this piece of AJAX that validates the login credentials by sending the username and password via GET method. I want to update this code to use POST method, but I don't know where to start or what to change.
The reason I'm doing this is the data that will be sent to another page will be big and GET doesn't send it all.
This is the code I have:
function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var usr;
var psw;
function login()
{
usr = encodeURI(document.getElementById('username').value);
psw = encodeURI(document.getElementById('password').value);
http.open('get', 'login.php?user='+usr+'&psw='+psw);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply()
{
if(http.readyState == 4)
{
var response = http.responseText;
if(response == 0)
{
alert('Login failed! Verify user and password');
}
else
{
alert('Welcome ' + usr);
document.forms["doSubmit"].elements["usr"].name = "usr";
document.forms["doSubmit"].elements["usr"].value = usr;
document.forms["doSubmit"].elements["pwd"].name = "pwd";
document.forms["doSubmit"].elements["pwd"].value = psw;
document.forms["doSubmit"].action = location.pathname + "user/";
document.forms["doSubmit"].submit();
}
}
}
This code uses GET and send the parameters in the URL and waits for the reply. I want to send the parameters via POST due to size.
The data that will be sent is for a <textarea name='taData' id='taData'></textarea>
Change the line of code as described below:
From:
http.open('get', 'login.php?user='+usr+'&psw='+psw);
To:
http.open('post', 'login.php');
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send('user=' + usr + '&psw=' + psw + '&tboxName=' + yourTextBoxValue);
More on the topic:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849(v=vs.85).aspx

Resources