Multiple Users Issues Node.js - javascript

I am working on a budgeting application and everything works great... or at least i thought it did. Test it out at http://budgeter.pattmorter.webfactional.com/! Now you can login and add stuff and edit your profile and it works great, the only problem is that if someone else logs in after you, and you refresh your page, it'll set your session to the person that logged in after you.
I'm not really sure why it happened but it has to do with my main app.js node. I think my problem is that when the user logs in i have a currentUser variable in app.js which is passed too all of the different routing but I don't think that is correct because it is causing these errors. Anyone suggest a better way of doing this?
My app.js file is here -- https://github.com/M-Porter/bearded-wookie/blob/master/production/app.js
Basically, I don't understand how to do what i want without a variable in the app.js space. Any push in the right direction would be great.

Node.js in Action (great book) suggests using built in session middleware for things like this. It uses signed cookies so you will also need the cookieParser middleware. It should look something like:
app.use(express.cookieParser('your secret'));
app.use(express.session());
Then you have access to req.session to keep track of your current user.
Edit 1: I just looked at your code more closely. Looks like you were already on track with cookieParser and session middleware. Just try storing your current user in session. It also sounds like passport can retrieve the username on subsequent request. Check out http://passportjs.org/guide/configure/

Related

Fastest redirects Javascript

My main function is I am creating a link-shortening app. When someone entered a long URL, it will give a short URL. If the user clicked on the short link it will search for the long URL on the DB and redirect it to the long URL.
Meantime I want to get the click count and clicked user's OS.
I am currently using current code :
app.get('/:shortUrl', async (req, res) => {
const shortUrl = await ShortUrl.findOne({short: req.params.shortUrl})
if (shortUrl == null) return res.sendStatus(404)
res.redirect(shortUrl.full)
})
findOne is finding the Long URL on the database using ShortID. I used mongoDB here
My questions are :
Are there multiple redirect methods in JS?
Is this method work if there is a high load?
Any other methods I can use to achieve the same result?
What other facts that matter on redirect time
What is 'No Redirection Tracking'?
This is a really long question, Thanks to those who invested their time in this.
Your code is ok, the only limitation is where you run it and mongodb.
I have created apps that are analytics tracker, handling billion rows per day.
I suggest you run your node code using AWS Beanstalk APP. It has low latency and scales on your needs.
And you need to put redis between your request and mongodb, you will call mongodb only if your data is not yet in redis. Mongodb has more read limitations than a straight redis instance.
Are there multiple redirect methods in JS?
First off, there are no redirect methods in Javascript. res.redirect() is a feature of the Express http framework that runs in nodejs. This is the only method built into Express, though all a redirect response consists of is a 3xx (often 302) http response status and setting the Location header to the redirect location. You can manually code that just as well as you can use res.redirect() in Express.
You can look at the res.redirect() code in Express here.
The main things it does are set the location header with this:
this.location(address)
And set the http status (which defaults to 302) with this:
this.statusCode = status;
Then, the rest of the code has to do with handling variable arguments, handling an older design for the API and sending a body in either plain text or html (neither of which is required).
Is this method work if there is a high load?
res.redirect() works just fine at a high load. The bottleneck in your code is probably this line of code:
const shortUrl = await ShortUrl.findOne({short: req.params.shortUrl})
And, how high a scale that goes to depends upon a whole bunch of things about your database, configuration, hardware, setup, etc... You should probably just test how many request/sec of this kind your current database can handle.
Any other methods I can use to achieve the same result?
Sure there are. But, you will have to use some data store to look up the shortUrl to find the long url and you will have to create a 302 response somehow. As said earlier, the scale you can achieve will depend entirely upon your database.
What other facts that matter on redirect time
This is pretty much covered above (hint, its all about the database).
What is 'No Redirection Tracking'?
You can read about it here on MDN.

How to get current logged in user in react js

just wondering how to access the data of a logged in authenticated user in a react js file with node js.
In the handlebar files I have I can see information like this:
{{#if user}}
I would like to know how to do things like that in a react js file so I can assign the name of the logged in user to a js variable. Something like
var name = {{# user.name }};
Thanks in advance and sorry if I've missed something out or said something a tad dense.
First of all you need to use a method for authentication, JWT is a good bet to do so. then in your main component (app.js) send a request to a specific route (like /auth/init) to check if the user is logged (means jwt is set).
you can approach this using middlewares if you are using express.js. if the user was logged in then send the user's credentials back to the client (react) and initialize your user state with the response.
To share user state between your components you have different options. based on your needs you can choose from redux, contextAPI, or just newly introduced API hooks. read this for further perspective.

Persist property to following middlewares in Express

My express app has some auth middleware which determines the current user from the session ID. I want to "persist" the user through to the following middlewares. I've tried attaching the user object to the res object, but this doesn't work (presumably because JS doesn't pass function arguments by reference).
I realise that something like Passport handles this specific scenario for you, but I'm interested in solving the general problem of persisting a value through to all subsequent middlewares.
The fact that I can't find any references to this on SO or elsewhere leads me to believe I'm trying to do something Fundamentally Wrong™ so please feel free to call me out. I'd love to hear alternative design approaches.
You can use something called locals
res.locals
for example in your case you can set
res.locals.id = 'something'
this value will persist throughout the request in all middlewares, until the response is sent.

With Sails.js how can I make /users/me a route that works with associations?

I have a main model Accounts, then I have a few Has Many models like Notifications and Friends
In my main.js
I'd like to be able to do things like:
socket.get('/users/me/notifications');
instead of like:
socket.get('/users/ + g_userAccountId + '/notifications');
^^ That works for right now, but it is set asynchronously so if any code loads before g_userAccountId is set it will try to use undefined instead which is bad.. Very bad..
I understand policies and all that I'm just wondering how I can make this work with the REST blueprints and what not. If I'm not clear please let me know
Is there a way to do this without setting findOne methods in each controller? Like to automatically fill in /me/ with 1
The easiest way I can imagine doing this without setting findOne methods in each controller would be to create a policy that matches the /users/me/notifications route, redirecting it to the current session's user id. You could potentially use something like the following, and update the /config/policy file.
if (session.authenticated) {
return res.redirect('/users/' + req.session.user.id + '/notifications');
}
If you wanted to do something to handle anytime the /users/me route is hit, you could modify this policy, tweak the req.url and redirect to the new one that uses the user ID, and apply it to all relevant routes in policy config file, or setup a custom middleware to handle the problem the same way.

Is it possible to use an existing Facebook Connect session with Facebooker?

Update: Working as designed once I cleared my cookies. Doh!
I'm working on an app that for various reasons uses the Facebook
Javascript API to initiate a Facebook connect session. I'd like to be
able to use that session in a few rails methods using Facebooker.
The basic workflow is like this:
User goes to non-rails page and logs in to FB Connect via JS
User goes to another non-rails page and can view FB data such as
name, profile pic
User goes to a rails based page - rails uses session created in
step 1 to do some processing
My problem is in step 3. Facebooker detects the session fine, but when
I try to call a method like facebook_session.user.name I get: Session
key invalid or no longer valid
If I go back to the url in step two, my session still works fine.
So is this a fundamental incompatibility, or is there some data I can
send to facebooker so that I can hook into the correct session? Maybe
my facebooker.yml needs tweaking?
Any thoughts are appreciated.
My facebooker.yml
development:
api_key: redacted
secret_key: redacted
canvas_page_name: blah_blah
callback_url: http://test.domain:3000
pretty_errors: true
set_asset_host_to_callback_url: true
tunnel:
public_host_username:
public_host:
public_port: 4007
local_port: 3000
server_alive_interval: 0
Gah! Always clear your cookies before posting on the interweb people.
The problem was with an existing facebooker-based session that was still around in my browser.
All working now.

Categories

Resources