1 node.js twitter-oauth locomotivejs passport.js
我正在尝试在我的机车项目中配置passport-twitter.
问题是在点击/ auth/twitter网址后没有任何反应.
编辑:我点击了控制器,但似乎没有调用twitter.
我做的是在routes.js上设置匹配/ auth/twitter并将其映射到auth_controller.js
类似下面的代码:
routes.js
this.match('auth/twitter/', 'auth#twitter');
this.match('auth/twitter/callback/', 'auth#callback');
Run Code Online (Sandbox Code Playgroud)auth_controller.js
var locomotive = require('locomotive')
, Controller = locomotive.Controller
, passport = require('passport');
var AuthController = new Controller();
AuthController.twitter = function() {
console.log('[##] AuthController.twitter [##]');
passport.authenticate('twitter'), function(req, res) {};
}
AuthController.callback = function() {
console.log('[##] AuthController.callback [##]');
passport.authenticate('twitter', { failureRedirect: '/show' }),
function(req, res) {
res.redirect('/list');
};
}
module.exports = AuthController;
Run Code Online (Sandbox Code Playgroud)我真的不知道这是否是用于机车的正确方法,任何帮助都将非常感激.
干杯,法比奥
需要先配置Passport.可以在此处找到有关如何执行此操作的示例.在LocomotiveJS的情况下,放置该配置的明显位置是初始化器:
// config/initializers/10_passport_twitter.js <-- you can pick filename yourself
module.exports = function(done) {
// At least the following calls are needed:
passport.use(new TwitterStrategy(...));
passport.serializeUser(...);
passport.deserializeUser(...);
};
Run Code Online (Sandbox Code Playgroud)
接下来,配置会话并初始化Passport:
// config/environments/all.js
module.exports = {
...
// Enable session support.
this.use(connect.cookieParser());
this.use(connect.session({ secret: YOUR_SECRET }));
// Alternative for the previous line: use express.cookieSession() to enable client-side sessions
/*
this.use(express.cookieSession({
secret : YOUR_SECRET,
cookie : {
maxAge : 3600 * 6 * 1000 // expiry in ms (6 hours)
}
}));
*/
// Initialize Passport.
this.use(passport.initialize());
this.use(passport.session());
...
};
Run Code Online (Sandbox Code Playgroud)
接下来,配置路由:
// config/routes.js
this.match('auth/twitter/', 'auth#twitter');
this.match('auth/twitter/callback/', 'auth#callback');
Run Code Online (Sandbox Code Playgroud)
因为passport.authenticate是中间件,所以before在控制器中使用钩子更容易:
// app/controllers/auth_controller.js
...
AuthController.twitter = function() {
// does nothing, only a placeholder for the following hook.
};
AuthController.before('twitter', passport.authenticate('twitter'));
AuthController.callback = function() {
// This will only be called when authentication succeeded.
this.redirect('/list');
}
AuthController.before('callback', passport.authenticate('twitter', { failureRedirect: '/auth/twitter' })};
Run Code Online (Sandbox Code Playgroud)
免责声明:我没有测试上面的代码,我基于我最近在项目中使用的代码,passport-local而不是使用代码passport-twitter.但是,除了不需要的回调URL之外,基础知识非常相似passport-local.
| 归档时间: |
|
| 查看次数: |
1407 次 |
| 最近记录: |