Here is the complete error info:
"stack": [
"InternalOAuthError: Failed to fetch user profile",
" at C:\\node\\XKsite\\node_modules\\_passport-github2@0.1.10@passport-github2\\lib\\strategy.js:96:19",
" at passBackControl (C:\\node\\XKsite\\node_modules\\_oauth@0.9.15@oauth\\lib\\oauth2.js:132:9)",
" at IncomingMessage.<anonymous> (C:\\node\\XKsite\\node_modules\\_oauth@0.9.15@oauth\\lib\\oauth2.js:157:7)",
" at emitNone (events.js:91:20)",
" at IncomingMessage.emit (events.js:185:7)",
" at endReadableNT (_stream_readable.js:974:12)",
" at _combinedTickCallback (internal/process/next_tick.js:80:11)",
" at process._tickCallback (internal/process/next_tick.js:104:9)"
]
Lately, I want to register account in my application through the info from third party website(mine is GitHub), but I encounter a error like above. What could be the root of the problem?
Here is my index.js file:
var path = require('path');
var express = require('express');
var passport = require('passport');
var GitHubStrategy = require('passport-github2').Strategy;
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var config = require('config-lite');
var webRouter = require('./web_router');
var pkg = require('./package');
var winston = require('winston');
var expressWinston = require('express-winston');
var GITHUB_CLIENT_ID = "~~~~";
var GITHUB_CLIENT_SECRET = "~~~~";
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new GitHubStrategy({
clientID: GITHUB_CLIENT_ID,
clientSecret: GITHUB_CLIENT_SECRET,
callbackURL: "http://127.0.0.1:3000/auth/github/callback"
},
function(accessToken, refreshToken, profile, done) {
profile.accessToken = accessToken;
done(null, profile);
}
));
var app = express();
// 设置模板目录
app.set('views', path.join(__dirname, 'views'));
// 设置模板引擎为 ejs
app.set('view engine', 'ejs');
app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
// 设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));
// session 中间件
app.use(session({
name: config.session.key,// 设置 cookie 中保存 session id 的字段名称
secret: config.session.secret,// 通过设置 secret 来计算 hash 值并放在 cookie 中,使产生的 signedCookie 防篡改
resave: false,// 强制更新 session
saveUninitialized: false,// 设置为 false,强制创建一个 session,即使用户未登录
cookie: {
maxAge: config.session.maxAge// 过期时间,过期后 cookie 中的 session id 自动删除
},
store: new MongoStore({// 将 session 存储到 mongodb
url: config.mongodb// mongodb 地址
})
}));
// flash 中间件,用来显示通知
app.use(flash());
// 处理表单及文件上传的中间件
app.use(require('express-formidable')({
uploadDir: path.join(__dirname, 'public/img'),// 上传文件目录
keepExtensions: true// 保留后缀
}));
// 设置模板全局常量
app.locals.blog = {
title: pkg.name,
description: pkg.description
};
// 添加模板必需的三个变量
app.use(function (req, res, next) {
res.locals.user = req.session.user;
res.locals.success = req.flash('success').toString();
res.locals.error = req.flash('error').toString();
next();
});
// 正常请求的日志
app.use(expressWinston.logger({
transports: [
new (winston.transports.Console)({
json: true,
colorize: true
}),
new winston.transports.File({
filename: 'logs/success.log'
})
]
}));
// 路由
app.use('/', webRouter);
// 错误请求的日志
app.use(expressWinston.errorLogger({
transports: [
new winston.transports.Console({
json: true,
colorize: true
}),
new winston.transports.File({
filename: 'logs/error.log'
})
]
}));
// error page
app.use(function (err, req, res, next) {
res.render('error', {
error: err
});
});
if (module.parent) {
module.exports = app;
} else {
// 监听端口,启动程序
const port = process.env.PORT || config.port;
app.listen(port, function () {
console.log(`${pkg.name} listening on port ${port}`);
});
}
Here is my web_router.js file(my router file)
var express = require('express');
var router = express.Router();
var passport = require('passport');
var uuid = require('node-uuid');
var github = require('./controllers/github');
var UserModel = require('./models/users');
router.get('/userinfo', function(req, res){
res.render('userinfo', { user: req.user });
});
router.get('/login', function(req, res){
res.render('login', { user: req.user });
});
router.get('/auth/github',
passport.authenticate('github', { scope: [ 'user:email' ] }));
router.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/login' }),
github.callback);
router.get('/auth/github/new', github.new);
router.post('/auth/github/create', github.create);
router.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
module.exports = router;
Here is my github.js file(I encounter problems in these code):
(my github.js file is in the "controllers" folder)
var UserModel = require('../models/users');
var authMiddleWare = require('../middlewares/auth');
exports.callback = function (req, res, next) {
var profile = req.user;
var email = profile.emails && profile.emails[0] && profile.emails[0].value;
UserModel.getUserByGitHubId({ githubId: profile.id }, function (err, user) {
if (err) {
return next(err);
}
//当用户已经是 myblog 用户时,通过 github 登陆将会更新他的资料
if (user) {
user.githubUsername = profile.username;
user.githubId = profile.id;
user.githubAccessToken = profile.accessToken;
user.avatar = profile._json.avatar_url;
user.save(function (err) {
if (err) {
if (err.message.indexOf('duplicate key error') !== -1) {
if (err.message.indexOf('loginname') !== -1) {
return res.status(500)
.send('您 GitHub 账号的用户名与之前在 N-blog 注册的用户名重复了!!!')
}
}
return next(err);
}
authMiddleWare.gen_session(user, res);
return res.redirect('/');
});
} else {
// 如果用户还未存在,则建立新用户
//**code can't execute to the line, that makes me confused**
req.session.profile = profile;
return res.redirect('/auth/github/new');
}
})
}
exports.new = function (req, res, next) {
res.render('sign/new_oauth', { actionPath: '/auth/github/create' });
};
via Jupiter
No comments:
Post a Comment