Logout from site cause error: 400 - Bad Request - javascript

I am using vibed.org framework. When I am processing logout function, I am getting strange error.
Here is my App.d code:
void main()
{
auto router = new URLRouter;
router.any("/checkAuthorization", &checkAuthorization);
router.any("/login", &login);
router.any("/logout", &logout);
// ..
}
...
void logout(HTTPServerRequest req, HTTPServerResponse res)
{
logInfo("Logout section");
Json request = req.json;
Json answerJSON = Json.emptyObject;
if (req.session) // if user have active session
{
res.terminateSession();
answerJSON["status"] = "success";
answerJSON["isAuthorized"] = false;
res.writeJsonBody(answerJSON);
logInfo(answerJSON.toString);
logInfo("User %s logout", request["username"]); //
}
else
{
answerJSON["status"] = "fail"; // user do not have active session?
logInfo("User do not have active session");
}
}
And Vue.JS code:
function logout()
{
var loginData = new Object();
//data that we take from user input
loginData["username"] = this.username; // username more then enough
console.log("Logout username -> " + loginData["username"]);
this.$http.post('http://127.0.0.1:8080/logout', loginData["username"]).then(function (response) {
console.log("server response: ", response.data)
if(response.data["isAuthorized"] == false)
{
console.log("Logout from site success");
App.topMenuView = 'guestmenu' //Change current view!
userLoginNotification("Goodbye, " + loginData["username"], "User Logout"); // notificate user
}
});
}
But I am getting in Chrome console error:
Uncaught (in promise) Object {request: Object, data: "400 - Bad Request Bad Request Internal error information: std.json.JSONException#C:\vibe-d-0.7.27-alpha.1\source\vibe\data\json.d(1100): (0): Error: Expected 'true', got 'test'. ---------------- 0x0044ABF0 in pure #safe bool std.exception.enforceEx!(std.json.JSONException).enforceEx!(bool).enforceEx(bool, lazy immutable(char)[], immutable(char)[], uint) core.thread.Fiber.run()", status: 400, statusText: "Bad Request", ok: false}
And I can't understand what's wrong. It's look like it's issue on server side, because logInfo("Logout section"); is unreachable.

Your're sending string as loginData["username"] instead of {username:loginData["username"]} василий

Related

AWS.ApiGatewayManagementApi BadRequestException: Invalid connectionId

I am having Websocket API Gateway and I trying to send message to connections using the ApiGatewayManagementApi.
First I configure it:
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: "2018-11-29",
endpoint: connectionsUrl
});
And this is the code for postToConnection()
try {
const params = {
ConnectionId: connection.connectionId,
Data: JSON.stringify(data.payload)
};
console.log(params, connectionsUrl);
//THIS PRINTS: { ConnectionId: 'ckd609nog0009sgp847cj3lgy', Data: '{}' }
https://xxxxxxxx.execute-api.xxxxxx.amazonaws.com/socket-test
await apigwManagementApi.postToConnection(params).promise();
} catch (e) {
console.error('APIGW Post To Connection ERROR:', e);
if (e.statusCode == 410) {
let res = await this.DisconnectConnection(connection.connectionId);
if (res.isError()) {
return ServiceResponse.Error(res.error)
}
return ServiceResponse.Error(res.error)
} else {
return ServiceResponse.Error({message: e.message});
}
}
The ERROR I am getting in the catch where I am logging it is:
**APIGW Post To Connection ERROR: BadRequestException: Invalid connectionId: ckd609nog0009sgp847cj3lgy
**
This is not stale connection. This use case is where I am connected to the WebSocket and I send message to socket, it does something and returns results vie postToConnection Method.
What is the problem ?

ApiRTC token authentication

I am trying to use token authentication with no success. I am wondering if anyone succeed in doing so, as the official ApiRTC documentation is weak on that topic.
1) I have activated secret key below from - Credentials screen
2) For token validation I have setup a service from API - Token authentication screen
3) I have the below code to create the user agent
function createUserAgent(token) {
ua = new apiRTC.UserAgent({
uri: 'token:' + token
});
ua.register({
id : useragentId
}).then(uaRegistered)
.catch(function (error) {
console.log("Registration error");
});
}
function uaRegistered(session) {
console.log("Registration OK");
}
4) This initializes a request to below address. And it fails with HTTP 401
GET https://cloud.apizee.com/api/v2/checkToken?token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhNWQxN2M1ZTVjOWZkYmRiNDJhYTgzMTJlMWQxMmEwYiIsImF1ZCI6ImFwaVJUQyIsImp0aSI6ImE5ZjU4NmNlLTcxMDctNDgxMS04ODYwLTQ5MjY4ODY2NjhiYiIsImlhdCI6MTU1OTg5OTA5MSwiZXhwIjoxNTU5OTAyNjkxLCJncmFudHMiOnsiaWRlbnRpdHkiOiJjbGk5OTQxOTgxNTgifX0.ZfQs_HgUXOWhCAlXB6fTMKhbT-pFslb9MK_JvXu2U5A 401 (Unauthorized)
5) I have also seen that no requests are made to my token validation service.
Thanks
edit: updates according to the answer
function createUserAgent(token) {
apiRTC.setLogLevel(apiRTC.LOG_LEVEL_DEBUG);
var registerInformation = {};
registerInformation.id = useragentId;
registerInformation.token = token;
ua = new apiRTC.UserAgent({
uri: 'apzkey:a5d17c5e5c9fdbdb42aa8312e1d12a0b'
});
$("#sessionStatus").text("Waiting for register response ");
ua.register(registerInformation).then(uaRegistered)
.catch(function (error) {
debugger;
console.log("Registration error");
$("#sessionStatus").text("Failed to register UA");
});
}
function uaRegistered(session) {
debugger;
console.log("Registration OK");
connectedSession = session;
$("#useragentId").text(useragentId);
$("#sessionUsername").text(session.getUsername());
$("#sessionStatus").text("Connected");
debugger;
}
Thanks for pointing this issue in documentation, we have done a first update for using an external validation service here :
https://dev.apirtc.com/authentication/index
On client side, you need to use following code :
registerInformation.token = "myToken"
ua.register(registerInformation).then(function(session) {
// Save session
connectedSession = session;
}).catch(function(error) {
// error
console.error('User agent registration failed', error);
});
the usage of token in uri is for users authentication on Apizee offers

ParseError: 'bad or missing username'

So I have some cloud code I am trying to write to like a post.
My database is setup that users have a likedPosts array, which has object id's of all the posts that the user liked. Users also have a column coins, that should get incremented when users like their posts.
The post object has a likes column which is an integer that gets incremented with each like, and the post object also has a posterId column, which is the object id of the user that posted it.
Here is my function right now (I am not very good at javascript and cloud code, so if there is something horribly wrong, I'm sorry)
Parse.Cloud.define("likePost", function(request, response) {
Parse.Cloud.useMasterKey();
var senderId = request.params.senderId;
var postId = request.params.postId;
var post = new Parse.Object ({objectId: postId});
var posterId = post.posterId
var poster = new Parse.User ({objectId: posterId});
var sender = new Parse.User ({objectId: senderId});
sender.add("likedPosts", postId);
poster.increment("coins");
post.increment("likes");
poster.save(null, {useMasterKey:true, success:
function(poster) {
console.log("Successfully saved poster");
}, error: function(poster, error) {
console.error("Error saving poster: " + error.message);
response.error(error);
}
});
post.save(null,{useMasterKey:true, success:
function(post) {
console.log("Successfully saved post");
}, error: function(post, error) {
console.error("Error saving post: " + error.message);
response.error(error);
}
});
sender.save(null, {useMasterKey:true, success:
function(sender) {
console.log("Successfully saved sender");
}, error: function(sender, error) {
console.error("Error saving sender: " + error.message);
response.error(error);
}
});
response.success();
});
I call the function from swift like so:
PFCloud.callFunction(inBackground: "likePost", withParameters: ["senderId" : PFUser.current()!.objectId!, " postId": postObject!.objectId!], block: { (result, error) in
if (error != nil) {
print(error!)
} else {
print("success liking")
}
})
In my logs, however, I get the following error:
2017-06-21T21:47:59.499Z - Failed running cloud function likePost for user R4d8Zrcdhw with:
Input: {"senderId":"R4d8Zrcdhw"," postId":"XXbu55PdpR"}
Error: {"code":141,"message":{"code":200,"message":"bad or missing username"}}
2017-06-21T21:47:59.492Z - bad or missing username
My guess is that the request is missing a header to define the content-type. I've seen Parse return the "bad or missing username" error via the Parse REST API if the Swift URLSession was using an incorrect content-type header.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
or
Parse.Cloud.httpRequest({
url: 'http://www.example.com/',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})

Parse Cloud Code Error - 'Master Key is Required'?

Whenever I try to run this snippet of cloud code, I receive an error stating that:
Error generating response. ParseError {
code: 141, message: 'Push failed to send with error: master key is required'}
I've tried to follow some of the other solutions on the site such as using Parse.Cloud.useMasterKey() & useMasterKey: true but I haven't found success with any of these commands (possibly due to me using them incorrectly?).
Parse.Cloud.define("sendPushToUser", function(request, response) {
var senderUser = request.user;
var recipientUserId = request.params.recipientId;
var message = request.params.message;
var recipientUser = new Parse.User();
recipientUser.id = recipientUserId;
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("user", recipientUser);
Parse.Push.send({
where: pushQuery,
data: {
alert: message
}
}).then(function() {
response.success("Push was sent successfully.")
}, function(error) {
response.error("Push failed to send with error: " + error.message);
});
});
Swift function:
func testPush() {
PFCloud.callFunction(inBackground: "sendPushToUser", withParameters: ["recipientId": PFUser.current()?.objectId!, "message" : "Test notification"]) { (success, error) in
if error != nil {
print("error occurred")
}else {
print("Sent successfully")
}
}
}
As Gellert Lee suggested
Did you configure your masterKey in your index.js? masterKey : process.env.MASTER_KEY ||'your masterkey'

How to handle error in Angular Controller from MongoDB database update/delete in Express?

I am trying to figure out how to handle an error when deleting or updating a document in MongoDB in Angular JS?
I have the following route in Node/Express:
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
//log the reason for the error
res.status(code || 500).json({
"error": message
});
}
app.delete("/polls/:id", auth, function(req, res) {
db.collection(POLLS_COLLECTION).deleteOne({
_id: new ObjectID(req.params.id), userID: req.user.id
//userID must match the req.user.id from Passport to make sure the poll belongs to the user
}, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to delete poll");
} else {
res.status(204).end();
}
});
});
The following in an Angular JS controller:
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
alert("Error deleting poll");
console.log(response);
})
};
deleteThisPoll in the controller calls a deletePoll service that sends a a request to the route:
this.deletePoll = function(pollId){
var url = "/polls/" + pollId;
return $http.delete(url);
};
What I want is to alert "Error deleting poll" from the Angular controller when the database delete is not executed (because for example user is not authenticated or the poll doesnt belong to the user) and "Poll Deleted" when the delete was successfull.
However: the error callback is never used and the app always alerts "Poll deleted!" no matter if the document was deleted or not deleted.
Doesn't my route send an error response when the delete was not executed and will it not hit my Angular error callback?
You can do like code below
Put this HTML code where you want to show error message :
<div style="color:red;">
{{error}}
</div>
In your angular js controller :
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
$scope.error="Any error message you like to show";
console.log(response);
})
};
If your API return an error. you can catch it like this :
Polls.deletePoll($routeParams.pollId).then(function(response) {
//SUCCESS CODE
}).catch(function(error) {
//NOTIFY ERROR
//NotifyService.display(error);
console.log(error);
});
thanks guys. I found out that MongoDB for some reason always returns a result object even when there was no delete/update. I solved this by checking for the result.deletedCount propety that is set to 1 or 0. Like so:
if(err){
res.status(500).end();
}
if(result.deletedCount === 0){
res.status(404).end();
//error handling in Angular error callback
} else {
res.status(204).end();
//error handling in Angular success callback
}
});
});
this makes sure that not always a 204 is send whether or not the delete was successfull.

Categories

Resources