使用github登录时,我一直得到user:null。
我不确定自己在做什么错,因为我可以看到用户登录
这周我一直在参考。我正在对数据库使用sequelize
Node + Express + Passport: req.user Undefined
还有这个
req.user undefined - node + express + passport-facebook
routes / users.js
router.get('/auth/github', passport.authenticate('github') );
router.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/'}),
function(req, res, done) {
console.log(`session ${req.session.passport.user} `); // renders the user id
const user = req.session.passport.user;
if(user){
const data = {
id: req.session.passport.user
};
models.User.findOne({
where: {
id: data.id,
},
}).then((user) => {
req.login(user, err => {
return res.redirect('http://127.0.0.1:8001/dashboard');
});
});
} else if(user == null) {
console.log(info.message);
res.status(403).send(info.message);
}
});
router.get("/current_user", (req, res) => {
if(req.user){
res.status(200).send({ user: req.user});
} else {
res.json({ user:null})
}
});
Passport-github.js
const passport = require("passport");
const GitHubStrategy = require('passport-github2').Strategy;
// const keys = require("../config/keys");
const models = require("../models/");
passport.serializeUser((user, done) => {
// push to session
done(null, user.id);
});
passport.deserializeUser((id, done) => {
models.User.findOne({
where: {
id,
},
}).then(user => done(null, user))
.catch(done);
});
passport.use(
new GitHubStrategy(
{
clientID: process.env.clientID,
clientSecret: process.env.secret,
callbackURL: 'http://127.0.0.1:8000/api/users/auth/github/callback',
},
async (accessToken, refreshToken, profile, done) => {
// console.log(req.user);
const { id, login } = profile._json;
const tempUser = { id, login, accessToken };
console.log(tempUser);
// console.log(accessToken);
done(null, tempUser);
}
)
);
// passport.serializeUser((user, done) => {
// // push to session
// done(null, user.id);
// });
// passport.deserializeUser((userId, done) => {
// // console.log('calling deserial' + userId);
// // // TODO: findByPk syntax? findById deprecated? Try later after sucessfully record data in DB
// models.User
// .find({ where: { id: userId } })
// .then(function(user){
// // console.log(user);
// return done(null, userId);
// }).catch(function(err){
// done(err, null);
// });
// // return done(null, id);
// });
// passport.deserializeUser((id, done) => {
// models.User.findOne({
// where: {
// id,
// },
// }).then(user => done(null, user))
// .catch(done);
// });
// passport.redirectIfLoggedIn = route => (req, res, next) =>
// req.user ? res.redirect(route) : next();
// passport.redirectIfNotLoggedIn = route => (req, res, next) =>
// req.user ? next() : res.redirect(route);
module.exports = passport;
app.js
var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
var models = require('./models/');
const port = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
// const allowOrigin = process.env.ALLOW_ORIGIN || '*'
// CORS Middleware
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
if (!process.env.PORT) {
require('dotenv').config()
}
if (!process.env.PORT) {
console.log('[api][port] 8000 set as default')
console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
console.log('[api][node] Loaded ENV vars from .env file')
console.log(`[api][port] ${process.env.PORT}`)
console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
app.use(cors({
origin: process.env.ALLOW_ORIGIN,
credentials:true,
allowedHeaders: 'X-Requested-With, Content-Type, Authorization, origin, X-Custom-Header',
methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS',
}));
require('./config/passport-github');
require('./config/passport');
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
secret : process.env.JWT_SECRET,
saveUninitialized: false,
maxAge: 1000 * 60 * 60 * 84,
resave: false,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:false}));
app.use('/api/users', userRoute );
app.use('/api/posts', postRoute );
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
app.all('*', function(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("http://127.0.0.1:8001/dashboard");
});
models.sequelize.sync().then(() => {
const server = app.listen(port, () => {
console.log(`Server is up and running on port ${port}`);
});
});