Friday, 6 September 2013

Why are my admin and user logins being treated differently in this express.js code?

Why are my admin and user logins being treated differently in this
express.js code?

req.body.currentUser is being correctly set in both cases, but doesn't
survive res.redirect in the second:
app.post '/sessions', (req, res) ->
console.log(req.session.currentUser)
redis.hgetall "Trainer:#{process.env.NODE_ENV}", (err, objects) ->
redis.hgetall "User:#{process.env.NODE_ENV}", (err, objects1) ->
req.session.currentUser = ''
req.session.currentUser = req.body.user if ('admin' is
req.body.user) and ('123' is req.body.password)
res.redirect '/admin/trainers'
return if req.session.currentUser isnt ''
trainers = (JSON.parse(value) for key,value of objects)
req.session.currentUser = tr.name for tr in trainers when
(tr.name is req.body.user) and (tr.password is
req.body.password)
res.redirect "/account"
return
The redirected handlers look something like:
app.namespace '/admin', ->
app.all '/*', (req, res, next) ->
console.log(req.session.currentUser)
...
app.namespace '/trainers', ->
app.get '/', (req, res) ->
app.namespace '/account', ->
app.all '/*', (req, res, next) ->
console.log(req.session.currentUser)
...
While .currentUser is 'admin' when admin logs on, the .currentUser is
always empty when a trainer logs on. Any help would be appreciated.
Thanks, John
Edit: I switched the order and it's always the bottom one that has a
problem. Admin doesn't work if it's not first. I don't know if this is a
timing problem with the callbacks or what, but I'm sure there must be some
sort of standard answer.
Edit - solved: It works when I only .redirect() once, when .currentUser is
actually set. I guess I posted my question a little too quick, though I'd
been beating my head against the wall for better than a day.

No comments:

Post a Comment