i need to delete a user form parse sdk with javascript, i tried loading the user query and then calling the destroy() but it gives me:
[HTTP/1.1 400 Bad Request]
my code is here
var query = new Parse.Query("User");
query.equalTo("email", 'wathmal#hotmail.com');
query.find().then(function(results) {
console.log(results[0]);
results[0].destroy();
});
this won't destroy the user. can anybody help?
with the help of Bjorn's answer i figured out a way doing it. i had to use REST api of parse sdk and generate a DELETE request with a proper session key of the user.
var CurrentUser = Parse.User.current();
console.log(CurrentUser);
var sessiontoken;
Parse.User.logIn(CurrentUser.attributes.username, document.getElementById("curpassword").value, {
success: function (user) {
user.set("StayLoggedIn", "false");
console.log(user._sessionToken);
sessiontoken = user._sessionToken;
user.save();
$.ajax({
url: 'https://api.parse.com/1/users/' + user.id,
type: 'DELETE',
headers: {'X-Parse-Application-Id': APP_ID, 'X-Parse-REST-API-Key': REST_KEY, 'X-Parse-Session-Token': sessiontoken},
success: function (result) {
// Do something with the result
alert("you have successfully deleted your account.");
Parse.User.logOut();
window.location.href = "index.html";
}
});
// location.reload();
},
error: function (user, error) {
//alert(error);
alert("incorrect username or password");
}
});
Related
Hi All,
I got a scenario in which i am supposed to call a REST api that is secured by a AZURE ACTIVE DIRECTORY. Most of the code runs fine and i am able to get the token using myMSALObj.acquireTokenSilent function too.
401 ERROR COMES WHEN I SEND AJAX CALL USING THAT TOKEN, YOU CAN SEE FOLLOWING CODE
User is there in Active Directory for which i get proper token, i dont know why my ajax call fails when i send that token to rest-api, please help
<script type="text/javascript">
const msalConfig = {
auth: {
clientId: "94edf294-08ae-489f-8621-c6d98009afa8",
authority: "https://login.microsoftonline.com/c483b3c4-21a6-4c93-95ea-7436cf318a68",
redirectUri: "https://localhost:44334/",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
function CallApi() {
// Add scopes for the id token to be used at Microsoft identity platform endpoints.
const loginRequest = {
scopes: ["User.Read"],
};
myMSALObj.loginPopup(loginRequest)
.then((loginResponse) => {
const accessTokenRequest = {
scopes: ["api://8c2b0253-f9e8-442c-bccf-b4a8bbe73b59/access_as_user"]
};
myMSALObj.acquireTokenSilent(accessTokenRequest).then((accessTokenResponse) => {
var accessToken = accessTokenResponse.accessToken;
var apiEndpoint = "https://localhost:44387/api/hello";
var bearer = "Bearer " + accessToken;
console.log("accessToken = ", accessToken);
$.ajax({
url: apiEndpoint,
type: "GET",
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", bearer) }
}).done(function (response) {
alert("SUCCESS");
console.log("response = ", JSON.stringify(response));
}).fail(function (err) {
console.error("Error Occurred");
console.log("error = ", JSON.stringify(err));
});
})
}).catch(function (error) {
console.log(error);
});
}
</script>
Screenshot of a NEW API Code
Screenshot of JWT.ms (Access Token)
New Screenshot of JWT Token
You should not set the client ID in the appsettings.json file to the client id of your api app. It should be the client id of your client app. According to the jwt analysis diagram you provided, I think it should be: 94edf294- 08ae-489f-8621-c6xxxxxxx.
My bad, Following call was missing in my startup.cs file
app.UseAuthentication();
thanks for your help guys
Specially - #Carl Zhao, #Purushothaman #Rass Masood
When I login and logout from my application, my username and password are stored into chrome browser memory. When I create a dump file from the task manager for that particular process Id and open that file in WinHex tool and search for username or password field I'm able to see my password in clear text and now I want to encrypt or clear that password field.
function onLogin(btnName) {
var parameters = getFormValues();
//if (!validateParameter(parameters.userName, parameters.password))
// return;
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader(parameters.antiForgeryTokenName, parameters.antiForgeryToken);
}
});
var getSecuritySettingsUrl = getVirtualDirectoryUpdatedURL("/login/GetSecuritySettings");
$.ajax({
url: getSecuritySettingsUrl,
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function (result) {
try {
var response;
if (result.IsHashed) {
var decryptedData = decryptWithDefaultSetting(result.viewData);
if (decryptedData.isError) {
alert(decryptedData.result);
return;
}
response = JSON.parse(decryptedData.result);
}
else {
response = JSON.parse(result.viewData);
}
if (response.IsPasswordHashed) {
if (isNullOrUndefined(response.SaltText)) {
throw new Error("Please refresh the page and try again");
}
encriptPass = encryptByInputKey(parameters.form["Password"].value, response.SaltText).result;
}
$('#btnType').val(btnName);
$('form input[name="Password"]').val(encriptPass);
$('#loginForm').submit();
} catch (error) {
console.log(error);
if (!isNullOrUndefined(error)) {
if (!isNullOrUndefined(error.message)) {
alert(error.message);
}
else if (!isNullOrUndefined(error.Message)) {
alert(error.Message);
}
else {
alert("Some error has occurred. Please refresh the page and try again");
}
}
}
},
error: function (xhr, textStatus, error) {
console.log(xhr);
alert("Please refresh the page and try again : " + xhr.statusText);
}
});
}
I have solved this problem earlier by salting and hashing the user entered password in the UI and passing both the salted value and hash to server for authentication. The same salt has to be applied during the server side password validation.
I have a REST API running and I am posting some data to it using JQuery.
This is how my JQuery code looks:
$(document).ready(function () {
$('#login-form').submit(function () {
var user = $('#uname').val();
var pass = $('#pwd').val();
alert('username = ' + user);
alert('password = ' + pass);
var JSONObject = { 'userName': user, 'password': pass };
var jsonData = JSON.parse(JSONObject);
$.ajax({
url: 'http://127.0.0.1:8080/user/login',
method: 'POST',
data: { userName: user, password: pass },
dataType: 'JSON',
contentType: 'application/json',
success: function (data, status, jqXHR) {
//Do something
console.log('data = ' + data);
},
error: function (jqXHR, status, errorThrown) {
alert('error ' + errorThrown);
}
});
});
});
However, this code is unable to access the API. I do not get the expected message in the server log.
When the Submit button of the form is clicked, the browser gets reloaded and it shows the form inputs in the url. That is all.
My API is written using Java and this is the relevant method.
#RequestMapping(value = "/user/login", method = RequestMethod.POST)
public ResponseEntity<User> logUser(#RequestBody User user){
User loggedUser = loginService.authenticateUser(user);
if(loggedUser != null){
System.out.println("User found");
return new ResponseEntity<User>(loggedUser, HttpStatus.ACCEPTED);
}else{
//user does not exsits
System.out.println("User not found");
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
I really can't understand what is wrong. No any error is shown. Can somebody point me out why this happens and how to fix this issue.
The issue is that the browser is reloading on submit event.
You need to add preventDefault() method like this
$("#login-form").submit(function (event) {
event.preventDefault()
//further code here
This will prevent the browser from reloading
I am attemting to add an item to a sharepoint list from an Apache Cordova application. It first prompts the user to login then it will make a HTTP Post to so the data entry.
I have the following code:
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(FormatAndUpload(authResult, data), errorCallback);
}
function FormatAndUpload(authResponse, data) {
var token = authResponse.accessToken;
var expiry = authResponse.expiresOn;
console.log("Token acquired: " + authResponse.accessToken);
console.log("Token will expire on: " + authResponse.expiresOn);
$.ajax({
url: "https://my.sharepoint.com/_api/web/lists/getbytitle('" + Test + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"Authoriztion":"Bearer " + token
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
The problem I am having is that the FormatAndUpload method is being called before acquireTokenAsync has completed, so the authResponse variable passed into the FormatAndUpload method is null.
I'm not too familiar with the promise framework in Javascript/JQuery but I was under the impression that the event should only fire on completion of the previous method.
Does anyone have any pointers in how I can correctly wait for the login to complete before attempting the POST?
what you did FormatAndUpload(authResult, data); is wrong the correct way to pass a callback is
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
so your saveToSharepoint will be like this
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
}
Thanks for the answer Newbee Dev, you were correct in that I didn't formulate the then method correctly.
For any others who see this regarding SharePoint, I actually reformatted the code for it to work as expected, so the saveToSharepoint method looks like so:
function saveToSharepoint(data) {
var AuthenticationContext = Microsoft.ADAL.AuthenticationContext;
AuthenticationContext.createAsync("https://login.microsoftonline.com/common/")
.then(function (authContext) {
authContext.acquireTokenAsync(
"https://my.sharepoint.com", // Resource URI
"4be098f8-2184-4831-9ef7-3d17dbbef6a0", // Client ID
"http://localhost:4400/services/office365/redirectTarget.html" // Redirect URI
).then(function (authResult) {
FormatAndUpload(authResult, data);
}, function (err) {
console.log(err);
});
}, function (err) {
console.log(err);
});
}
The main thing to note is creating the AuthenticationContext asynchronously and this way, the FormatAndUpload calls after the whole login process is complete. Just thought I would post this for other people who see this regarding Sharepoint and are stuck.
When the session is expired, User cant log back in without a page refresh because the _token in ajax headers is expired(AKA TokenMismatchException). I cant handle the exception by redirecting user to a log in page because the login is an overlay modal and the request is handled via ajax.
I thought i could catch the mismatch exception in Handler.php and return a json response with a session token. and on the client side, use the new token to continue the intended process. However, when i use the new token passed from server, the session token will be changed again on server side which results another TokenMismatchException.
So how should i handle the exception in a secured way without refreshing a page?
Here's what i have right now:
setup csrf_token in a global js file:
$(function () {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content') }
});
});
render method in app/exceptions/handler.php:
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else if ($e instanceof TokenMismatchException)
{
if ($request->ajax()) {
return response()->json([
'message' => 'TokenMismatchException',
'token' => csrf_token()
]);
}
}
else
{
return parent::render($request, $e);
}
}
in authentication.js:
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked')
},
success: function(response) {
if (response.message === 'TokenMismatchException') {
console.log(response); //message and token exist
//if catch the exception, use the new token to set up the ajax headers and login again
$.ajaxSettings.headers["X-CSRF-TOKEN"] = response.token;
console.log($.ajaxSettings.headers["X-CSRF-TOKEN"]);
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked'),
},
success: function(res) {
console.log(res);
},
error: function(err) {
console.log(err);
}
});
}
console.log('logged in');
},
error: function(xhr, status, err) {
}
});
thanks in advance.
In your render function, you've to check for a specific TokenMismatchException. So may be you can try something like this:
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json('msg', 'Your session has expired. Please try again.');
}
You may also pass a new csrf_token along with the json so that you can replace the old one with the new one and send the form request again.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json(['msg'=> 'Your session has expired. Please try again.', 'token'=> csrf_token()]);
}
I haven't tested this code. But this should get you started.
Also, if you want, you can use a package: https://github.com/GeneaLabs/laravel-caffeine