400 Bad Request when doing a Parse Unity cloud call to user.logIn in Parse.Cloud.Define - authentication

When trying to define a Parse Cloud Code server side function to handle login I get 400 Bad Request when I try to call it. When I look at the Parse logs it records the error "Failed with: ReferenceError: user is not defined". But the user is definitely defined!
Below is the definition of the cloud code for LogIn:
Parse.Cloud.define("LogIn", function(request, response)
{
user.logIn(request.params.username, request.params.password,
{
success: function(user)
{
response.success(
{
"success": "Log in successful."
});
},
error: function(user, error)
{
// We must respond with a success in order to access the
// result of the request inside Unity.
response.success(
{
"error": "Log in failed.",
"code": error.code,
"message": error.message
});
}
});
});
From Unity I make this call to the LogIn coud code function:
ParseCloud.CallFunctionAsync<Dictionary<string, object>> ("LogIn", userInfo).ContinueWith (t =>
{
etc.....
}
I get the following error logged in the server side Parse logs when I call the above from Unity using user sashas123 and also student123:
E2014-09-26T17:06:18.001Z] v8: Ran cloud function LogIn with: Input:
{"username":"sashas123","password":"test"} Failed with:
ReferenceError: user is not defined
at main.js:43:5
E2014-09-26T17:38:50.474Z] v10: Ran cloud function LogIn with:
Input: {"username":"student123","password":"test"} Failed with:
ReferenceError: user is not defined
at main.js:43:5
The following snapshot from the Data Browser shows that the above users are definitely defined:
![Parse User class][1]
Is there any issue with calling user.LogIn on the server side through Cloud Code or is this a Unity issue?

It looks like user.logIn should be request.user.logIn :)
I find it's best to handle the case where the function may be called without a logged in user too:
if (request.user.logIn != null)
{
...
}
else
{
response.error("This function must be called with a logged in user!");
}
Hope this help!

Related

How to send multiple Validation Errors to React using Flask and Marshmallow in Backend and Axios for React-Native in Frontend

I am using Marshmallow to validate incoming fields for a simple put request.
Now I am testing the error handling in the frontend to make sure I send the right error messages for the frontend.
I am usually sending data of type
{
password: string,
email: string
}
For now Marshmallow checks if the password is long enough and if the email is of format Email.
I collect all errors in a expect statement and send it to the frontend like this:
except ValidationError as err:
return make_response(
{"errors": err.messages}, status.HTTP_400_BAD_REQUEST
)
with Postman giving me e.g. this response:
{
"errors": {
"email": [
"Missing data for required field."
],
"password": [
"Missing data for required field."
],
}
}
All error messages are therefore collected within the field errors and sent back to the frontend.
When the error is sent back to the frontend I catch my error and all I get is this object:
Object {
"data": null,
"error": [Error: Request failed with status code 400],
}
How do I correctly send or receive the
errors: err.messages
field in the frontend within a make_response error response?
I found the solution to the problem I had here:
github.com/axios/axios/issues/960.
Apparently you have to access the response object or the error object that is send to axios. There is no interceptor needed. What I changed was this line, when resolving the promise to:
try {
resolved.data = await promise;
} catch (e) {
resolved.error = e.response.data;
}
before that I accessed the error with:
try {
resolved.data = await promise;
} catch (e) {
resolved.error = e;
}
The errors are stored within the response.data.

Handling errors if no network is available

I just implemented my first backend file where I fetch some user data, messages and so on.
Now I wanted to include error handling if there is no network available.
I don´t know if I did it right but this was my approach so far:
import axios from 'axios'
const host = process.env.VUE_APP_URL
export default {
person: async function (currentPerson) {
let params = {
currentPerson: localStorage.getItem("person"),
};
if (user) {
params['currentPerson'] = currentPerson;
}
return axios.get(`${host}/api/currentPerson`, {
params: params
})
//catching network errors
.catch (error => {
if (error.response) {
/*
* The request was made and the server responded with a
4xx/5xx error
*/
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/*
* The request was made but no response was received
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
console.log(error)
});
},
In my mounted() function of my main view I fetch the data from my backend file from above:
backend.matches().then(function (response) {
self.contacts = response.data.persons;
});
I tried to check in console if it is working but all I get is the following:
In the catch block I check for
response errors: like 4xx/5xx
request errors: if my network not responding in time
and any other errors
Would this be the right approach to check if a network is available or not? Or does it degrade the user experience when the user checks the error?
My backend file includes more methods.. do I have to write for each method these kind of requests?
In your backend file you don't react whether there is a network connection or not I think.
And only for reference: that is not the backend, but communicates with the backend - the backend is the part of your code what you communicate with, e.g. Laravel code, an API, ...
Try adding the following at the beginning of your catch part:
if (!error.response) {
//network error
console.log('No network connection');
} else if (error.response) {
//the rest of your code
This should print out No network connection in your console.
Run your application, turn off the internet connection and check the console.
These kind of code should always be located in your backend part.
My answer maybe different from your question.
When i create a .net core API with Angular i used three things to check is there network or not?
subscribe to windows's offline/online event
create signalR hub from layout component to API server
API request failed (it means lot of incident, but if 1. or 2. case is true i know what cause 3. case

MFPPush.registerDevice wrapped by obtainAccessToken failed

I'm trying to run MFP8's push sample app of GitHub. But MFPPush.registerDevice method failed and error message "Failed to register device:" was shown.
function registerDevice() {
WLAuthorizationManager.obtainAccessToken("push.mobileclient").then(
MFPPush.registerDevice(
null,
function(successResponse) {
navigator.notification.alert("Successfully registered");
enableButtons();
},
function(failureResponse) {
navigator.notification.alert("Failed to register");
console.log("Failed to register device:" +
JSON.stringify(failureResponse));
}
)
);
}
I read the MFP8 document and found the note below.
Note: Authenticated notifications are currently not supported in Cordova applications due to a defect. However a workaround is provided: each MFPPush API call can be wrapped by WLAuthorizationManager.obtainAccessToken("push.mobileclient").then( ... );. The provided sample application uses this workround.
The sample code is wrapped by WLAuthorizationManager.obtainAccessToken indeed. But I think MFPPush.registerDevice may be called before 'obtainAccessToken' completes because return value of MFPPush.registerDevice's method is specified as Promise.then() parameter instead of function that call MFPPush.registerDevice.
So I think the sample should be written as bellow,
function registerDevice() {
WLAuthorizationManager.obtainAccessToken("push.mobileclient").then(
function() {
MFPPush.registerDevice(
null,
function(successResponse) {
navigator.notification.alert("Successfully registered");
enableButtons();
},
function(failureResponse) {
navigator.notification.alert("Failed to register");
console.log("Failed to register device:" +
JSON.stringify(failureResponse));
}
)
);
}
}
Could anyone give me some advice about that?
There is additional information. In device log these messages were logged.
Of course, I registered UserLogin security check to MobileFirst Server and UserLogin challengeHandler is created in UserLoginChallengeHandler.js
(I have not changed except bundleId)
2018-02-10 19:42:47.271015+0900 PushNotificationsCordova[1273:1500711] Failed to register device:"Error Domain=com.ibm.mfp.push Code=5 \"Error authenticating client. Error is 'Challenge handler does not exist. There is no registered challenge handler with key UserLogin'.\" UserInfo={networkMetadata={\n \"$bytesSent\" = 120;\n \"$category\" = network;\n \"$outboundTimestamp\" = 1518259366869;\n \"$path\" = \"http://192.168.0.105:9080/mfp/api/preauth/v1/preauthorize\";\n \"$requestMethod\" = POST;\n \"$trackingid\" = \"F8FD4A96-B046-4DAD-87F6-7441E8426C2E\";\n}, NSLocalizedDescription=Error authenticating client. Error is 'Challenge handler does not exist. There is no registered challenge handler with key UserLogin'.}"

Authentication testing with Meteor

I'm writing meteor tests that require authentication, and having a series of problems.
This is my code:
MochaWeb?.testOnly ->
describe "Login", ->
describe "security", ->
it 'should take you to /login/ if you are not logged in', ->
Meteor.flush()
chai.assert.equal Router.current().url, '/login/'
it 'should allow logins and then take us to /', ->
Meteor.flush()
Accounts.createUser username: 'test', password: 'test'
Meteor.loginWithPassword 'test', 'test', (err) ->
console.log err
chai.expect(err).to.be undefined
chai.assert.equal Router.current().url, '/'
My tests pass, even though I get console messages such as Exception in delivering result of invoking 'login': TypeError: object is not a function
My console.log call gives me
{error: 403, reason: "User not found", details: undefined, message: "User not found [403]", errorType: "Meteor.Error"…}
on the console, and nothing on the velocity log window
My user doesn't authenticate as I'd expect. One cause could be that my app doesn't have the accounts-password package, because I don't want it (I just want google apps users to be able to login). However I want an easy way to handle authentication in meteor tests, as most of my tests involve authenticated users.
I'm not sure whether the assert equal would work or I'd have to set some sort of timeout to wait for the redirection. In this case it wouldn't be a problem, but do I have to nest every test method I have inside loginWithPassword? I'd find this a bit uncomfortable.
Any help and suggestions much appreciated!
Best,
Are you sure you have user already created? I think you should create it in your fixture.js.
MochaWeb.testOnly(function() {
describe("Client", function() {
describe("firstTest", function() {
// Meteor.users.remove({});
before(function(done) {
Accounts.createUser(currentUser, function(err, success) {
Meteor.loginWithPassword(currentUser, function(err) {
console.log("This works");
// done();
});
});
});
});
});
});
Here is the source file, in which I have implemented the same
https://github.com/trinisofttechnologies/mocha-test/blob/master/tests/mocha/client/client.coffee
and this is the repo where the code resides
https://github.com/trinisofttechnologies/mocha-test

Google Apps API (Calendar v3) returns 404 error

I had been working with the Google API (Calendar v3) for a while without problems until I started to receive error messages a week ago. I can still authorize but any request I make returns a 404 error. I also tried to use another Google Apps account and had the same issue.
// Load the API and make an API call.
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
console.log (resp);
});
});
}
The console log is:
code: 404
data: Array[1]
error: Object
message: "Not Found"
proto: Object