request.user not set in Cloud Code function - parse-cloud-code

I'm calling a Cloud Code function from a JavaScript application with a logged-in user, like this:
if (Parse.User.current()) { // just to assert there is a logged-in user
Parse.Cloud.run('foo').then(...);
}
In the Cloud Code function I want to access the current user (i.e. the user from whose context the function is called):
Parse.Cloud.define('foo', (req, res) => {
var user = req.user;
//...
}
Unfortunately, user is undefined. Is this code supposed to work, or is there an obvious mistake?
P.S.: Using parse-server 2.2.7 (based on parse-server-example) and parse-SDK-JS 1.8.3.

1-> Make sure you update to the latest version of the Parse Server.
sudo npm install parse-server#latest -g
At the time of this writing, this should be 2.2.7.
ref: https://github.com/ParsePlatform/parse-server/releases
2-> Make sure the User has a valid session.
#hramos: "request.user will only point to a _User object when the function is triggered by an authenticated user."
ref: https://github.com/ParsePlatform/parse-server/issues/1619
In other words...., logout and then log back in.

Related

How to verify a user is authenticated and present in firebase, when doing read/write operations on the rest-api, in nodejs, UI is in flutter?

I have built a rest-api using Nodejs and mongodb for the flutter app, works completely fine and i am authenticating user using firebase phone authentication and I have some complex work, cannot be handled by the firebase, so setup a restapi for the work, so when user hits that api, i want to make sure that user is present and authenticated by the firebase before reading and writing from the db, on the server(api) side, written in node js. How to achieve this, any ideas?
P.S : I am open for ideas, and thanks for the help in advance :)
If anything wrong in doing this or with question, suggest for the edit
Just use the currentUser method of FirebaseAuth to verify if the user is logged in
FirebaseUser user = await FirebaseAuth.instance.currentUser();
if(user!=null){
// do your thing
}
Edit
In case you want to verify user on your server, use Firebase Admin SDK in your Nodejs server. You will have to pass some identifier like UID, email or phone number; whichever applicable.
admin.auth().getUser(uid)
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log('Successfully fetched user data:', userRecord.toJSON());
})
.catch(function(error) {
console.log('Error fetching user data:', error);
});
Reference to the docs for more details : https://firebase.google.com/docs/auth/admin/manage-users

Run a function once per user for any endpoint in nodejs

My backend is written in NodeJS. I would like to push some real time data for my firestore database. My question how can i run a function once when a user is connected to my server. Also, this function will extract info from a cookie stored in the browser. I tried the singleton design pattern, but it is totally wrong because it runs for one user only.
This will involve storing some state per user (presumably you could do this in Firestore). As each user request comes in, you just need to check for said state and if it's not been set yet, invoke the function and set the state.
For example, here's how it might look if you were using Express:
app.use((req, res, next) => {
// assume user is deserialized with state from store
if (!req.user.hasRunFunc) {
// run some function
// update store setting 'hasRunFunc' state
}
})
As long as the state is set, then subsequent requests from the same user would be skipped.

firebase.auth().currentUser is returning null when i re-execute a script in node.js cli

I m creating a node cli and i m using firebase auth in it
everything is working fine
there is a command to login and when the user executes it asks for credentials. after the submission i get a custom auth token from an api and then i use signinwithcustomtoken and i get value of 'currentUser' as expected.
According to this page Access Firebase in your app i can use firebase client sdk in a node.js app for auth
Problem
but as when i execute another command to show profile data and in that when i try to access firebase.auth().currentUser it returns null :(
I m not creating any kind of server.
I think firebase is recreating a new instance every time i run a command
but why doesn't firebase loose instance in angular ?
In Node.js deployments, the default Auth state persistence mode is firebase.auth.Auth.Persistence.NONE for security reasons as mentioned at the bottom of the Modifying the ASP section. This means that the user state is cleared whenever you close your script.
Prior to logging in with your authentication token, you will need to use the following code to change the mode to match a browser:
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL) // <-- this bit
.then(function() {
// Users will now be logged in until they explicitly log out
return firebase.auth().signInWithCustomToken(token);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});

Debug Node.js & Express App - Intermittently using 100% CPU

I'm developing an app using NGinx + Node.js + Express + Firebase that simply takes input from a mobile app and stores it to Firebase, optionally uploading files to S3.
In its simplest terms, the "create" function does this
Validates input
Formats the input Checks if there is a file uploaded
(via the multer plugin) and stores it
If there was a file, upload
to Amazon S3 and delete the source file (it's important to note I was
encountering this issue before the inclusion of S3).
Create the item
by pushing into the items reference on Firebase
Create the item for
the user by pushing into the user_items reference on Firebase.
There are a few other functions that I have implemented as an API.
My trouble is coming from an intermittent spike in CPU usage, which is causing the nginx server to report a gateway timeout from the Node.js application.
Sometimes the server will fall over when performing authentication against a MongoDB instance, other times it will fall over when I'm recieving the input from the Mobile app. There doesn't seem to be any consistency between when it falls over. Sometimes it works fine for 15+ various requests (upload/login/list, etc), but sometimes it will fall over after just one request.
I have added error checking in the form of:
process.on('uncaughtException', function(err) {
console.error(err.stack);
});
Which will throw errors if I mistype a variable for example, but when the server crashes there are no exceptions thrown. Similarly checking my logs shows me nothing. I've tried profiling the application but the output doesn't make any sense at all to me. It doesn't point to a function or plugin in particular.
I appreciate this is a long winded problem but I'd really appreciate it if you could point me in a direction for debugging this issue, it's causing me such a headache!
This may be a bug in the Firebase library. What version are you using?
I've been having a very similar issue that has had me frustrated for days. Node.js + Express + Firebase on Heroku. Process will run for a seemingly random time then I start getting timeout errors from Heroku without the process ever actually crashing or showing an error. Higher load doesn't seem to make it happen sooner.
I just updated from Firebase 1.0.14 to latest 1.0.19 and I think it may have fixed the problem for me. Process has been up for 2 hours now where it would only last for 5-30 min previously. More testing to do, but thought I'd share my in-progress results in case they were helpful.
It seems the answer was to do with the fact that my Express app was reusing one Firebase connection for every request, and for some reason this was causing the server to lock up.
My solution was to create some basic middleware that provides a new reference to the Firebase on each API request, see below:
var Middleware = {
/*
* Initialise Firebase Refs per connection
*/
initFireBase: function(req, res, next) {
console.log('Intialising Firebase for user');
// We need a authToken
var authToken = req.param('authToken');
// Validate the auth token
if(!authToken || authToken.length === 0) {
return res.send(500, {code: 'INVALID_TOKEN', message: 'You must supply an authToken to this method.'});
}
else {
// Attempt to parse the auth token
try {
var decodedToken = JWTSimple.decode(authToken, serverToken);
}
catch(e) {
return res.send(500, {code: 'INVALID_TOKEN', message: 'Supplied token was not recognised.'});
}
// Bail out if the token is invalid
if(!decodedToken) {
return res.send(500, {code: 'INVALID_TOKEN', message: 'Supplied token was not recognised.'});
}
// Otherwise send the decoded token with the request
else {
req.auth = decodedToken.d;
}
}
// Create a root reference
var rootRef = new Firebase('my firebase url');
// Apply the references to each request
req.refs = {
root: rootRef,
user: rootRef.child('users'),
inbox: rootRef.child('inbox')
};
// Carry on to the calling function
next();
}
};
I then simply call this middleware on my routes:
/*
* Create a post
*/
router.all('/createPost', Middleware.initFireBase, function(req, res) {
var refs = req.refs;
refs.inbox.push({}) // etc
....
This middleware will soon be extended to provide Firebase.auth() on the connection to ensure that any API call made with a valid authToken would be signed to the user on Firebase's side. However for development this is acceptable.
Hopefully this helps someone.

Meteor - Check if user is logged in as administrator (Client - Side)

I'm currently developing an app which needs users and administrators. What I do right now is, I create an admin account on the client with username 'admin' and a default password that should be changed over the accounts-ui.
I do this because creating a user like this:
Accounts.createUser({
username : 'admin',
email : 'test#test.com',
password : 'changethispasswordovertheuserinterface',
profile : { type : 'admin' }
});
doesn't work for me on server side. That means I just create the admin in my client.js and just use this code to check if the admin is logged in.
Template.admin.isAdmin = function () {
var currentUser = Meteor.user();
// Is this hackable?
if (null !== currentUser) {
if ('admin' === currentUser.username) {
return true;
}
}
};
Is this the best way to approach this? And most importantly, is my site hackable like this (Could somebody fake it)?
Yes this is hackable, one could pull up the chrome inspector and modify this quite easily. Or even faster, by typing something like Template.admin.isAdmin = function () { return true; } into Chrome's web console
The best approach would be to only provide the information to the client from the servers end if the user is an admin. So this would mean using Meteor.allow to ensure the database can only be changed by an administrative user, if peforming ops from the client end.
It also depends a bit on what you want to use 'isAdmin' for too. If its content, you could generate the html on the server's end and send it down to the client in a Meteor.methods. At the moment the templating system doesn't provide for locking down the UI on the clients end depending on what the user's document contains.
For any administrative commands, you could use a Meteor.call at which point the user is vetted on the server's and and the transaction is performed there.
The answer on this thread works too AND the top-voted answer has code for a server side, Meteor method call.

Resources