admin管理员组文章数量:1435510
I am trying to use res.locals.user
to show the user
object in the frontend.
Below you can see in my main app.js
file the middleware I have created:
...
const passport = require('passport')
const auth = require('./routes/auth')
const index = require('./routes/index')
const app = express()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())
app.use(session({
secret: 'super-mega-hyper-secret',
resave: false,
saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use((req, res, next) => { //This middleware checks the local user
res.locals.user = req.user
next()
})
...
My passport file looks like the following:
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const serviceAuth = require('../service/auth')
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser(async(id, done) => {
const user = await serviceAuth.findById(id)
done(null, user)
})
// Sign in with username and Password
passport.use('local', new LocalStrategy({
usernameField: 'username',
}, async(username, password, done) => {
const user = await serviceAuth.signin(username, password)
done(null, user)
}))
/**
* Login Required middleware.
*/
exports.isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
res.locals.user = req.session.user
return next()
}
res.redirect('/')
}
However, I get the following error, when trying to display in my pug view the user
object:
TypeError: /home/ubuntu/workspace/src/views/includes/_sidebar.pug:6
4| .user-panel
5| .pull-left.info
> 6| p= user.name
7| p= user.role
8|
9| // Sidebar Menu
Cannot read property 'name' of undefined
Any suggestions why the user object is not available in the views AFTER I have properly logged in a user?
I am trying to use res.locals.user
to show the user
object in the frontend.
Below you can see in my main app.js
file the middleware I have created:
...
const passport = require('passport')
const auth = require('./routes/auth')
const index = require('./routes/index')
const app = express()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())
app.use(session({
secret: 'super-mega-hyper-secret',
resave: false,
saveUninitialized: true,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use((req, res, next) => { //This middleware checks the local user
res.locals.user = req.user
next()
})
...
My passport file looks like the following:
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const serviceAuth = require('../service/auth')
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser(async(id, done) => {
const user = await serviceAuth.findById(id)
done(null, user)
})
// Sign in with username and Password
passport.use('local', new LocalStrategy({
usernameField: 'username',
}, async(username, password, done) => {
const user = await serviceAuth.signin(username, password)
done(null, user)
}))
/**
* Login Required middleware.
*/
exports.isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
res.locals.user = req.session.user
return next()
}
res.redirect('/')
}
However, I get the following error, when trying to display in my pug view the user
object:
TypeError: /home/ubuntu/workspace/src/views/includes/_sidebar.pug:6
4| .user-panel
5| .pull-left.info
> 6| p= user.name
7| p= user.role
8|
9| // Sidebar Menu
Cannot read property 'name' of undefined
Any suggestions why the user object is not available in the views AFTER I have properly logged in a user?
Share Improve this question edited Nov 13, 2017 at 14:45 aydinugur 1,2062 gold badges14 silver badges22 bronze badges asked Nov 13, 2017 at 13:43 Carol.KarCarol.Kar 5,23538 gold badges148 silver badges298 bronze badges 2- Kindly verify field name which have used in template, passport staratergy. – Dipak Commented Nov 13, 2017 at 13:54
- @Dipakchavda Thx for your reply! Basically I am expecting to get the user object in the frontend. Or not? – Carol.Kar Commented Nov 13, 2017 at 15:12
2 Answers
Reset to default 1EDIT[1] You will need 2 entry views in your app:
- A
index
for the case a user is authenticated - A
loginPage
for the case user is not authenticated
You can also handle these both cases in the main view(index
) but you need to show/hide elements based on the presence of the currentUser
. But i find having separate views more clean.
Step 1 - add your authentication middleware:
const isAuthenticated = require('./path/to/isAuthenticated');
app.use(isAuthenticated)
Step 2 - render your app root /
(is very important to do this after you registered the auth middleware so that your res.locals.user
is populated):
app.get('/', function(req, res){
if(res.locals && res.locals.user){
res.render('index', { currentUser: res.locals.user });
} else {
res.render('loginPage');
}
});
Step 3 - Add the injected user to the window
in index.pug
:
if !!currentUser
script.
window.currentUser = !{currentUser}
In your isAuthenticated
function, the req.session.user
is undefined
Passport.js
store user
object in req.use
for each authenticated route, session only store userId.
Your middleware
in app.js
file is OK, but the isAuthenticated
overwrite res.locals.user
to undefined
.
In my opinion you need remove the middleware
(because it use in all routes) and change isAuthenticated
like this:
exports.isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
res.locals.user = req.user
return next()
}
res.redirect('/')
}
本文标签: javascriptUsing reslocalsuser to show user object in all frontend viewsStack Overflow
版权声明:本文标题:javascript - Using res.locals.user to show user object in all frontend views - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745621112a2666686.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论