我正在学习 mean.io,通过这个教程视频(链接),它展示了一个例子包(由mean package mymodule
创建)。文档中也有描述,可在“Packages”下找到(链接)。我需要帮助理解所给的认证/授权如何工作。
默认的样本包/模块具有简单的用户身份验证,在客户端上:
myapp/packages/mymodule/public/views/index.html 包含:
<li>
<a href="mymodule/example/anyone">Server route that anyone can access</a>
</li>
<li>
<a href="mymodule/example/auth">Server route that requires authentication</a>
</li>
<li>
<a href="mymodule/example/admin">Server route that requires admin user</a>
</li>
在服务器端,
myapp/packages/mymodule/server/routes/mymodule.js,包含:
// The Package is past automatically as first parameter
module.exports = function(Mymodule, app, auth, database) {
app.get('/mymodule/example/anyone', function(req, res, next) {
res.send('Anyone can access this');
});
app.get('/mymodule/example/auth', auth.requiresLogin, function(req, res, next) {
res.send('Only authenticated users can access this');
});
app.get('/mymodule/example/admin', auth.requiresAdmin, function(req, res, next) {
res.send('Only users with Admin role can access this');
});
...
};
不同身份验证的魔法取决于app.get()
的第二个参数,带有额外的身份验证回调:无、auth.requiresLogin
或auth.requiresAdmin
。
这就是身份验证的魔法(也可以在github上找到):
myapp/packages/access/server/config/authorization.js:
/**
* Generic require login routing middleware
*/
exports.requiresLogin = function(req, res, next) {
if (!req.isAuthenticated()) {
return res.send(401, 'User is not authorized');
}
next();
};
/**
* Generic require Admin routing middleware
* Basic Role checking - future release with full permission system
*/
exports.requiresAdmin = function(req, res, next) {
if (!req.isAuthenticated() || !req.user.hasRole('admin')) {
return res.send(401, 'User is not authorized');
}
next();
};
问题A:为什么在authorization.js中使用"exports.requiresLogin"和"exports.requiresAdmin",而不是使用"somethingelse.requiresLogin"和"somethingelse.requiresAdmin"?这个"exports"与myapp/packages/access/server/config/passport.js的exports
有关吗:module.exports = function(passport) { ...}
,github?如果是,我们在什么情况下可以使用这个"exports"?
由于认证授权规则是在"access"包中编写并在"mymodule"中使用,因此Mean.io包之间不是独立的。 "Access"包在
myapp/packages/access/app.js, github上注册:
var mean = require('meanio'),
Module = mean.Module,
passport = require('passport');
var Access = new Module('access');
Access.register(function(database) {
// Register auth dependency
var auth = require('./server/config/authorization');
require('./server/config/passport')(passport);
// This is for backwards compatibility
mean.register('auth', function() {
return auth;
});
mean.register('passport', function() {
return passport;
});
Access.passport = passport;
Access.middleware = auth;
return Access;
});
问题 B:Mean.io是否自动链接所有的包,还是需要某些代码来链接包?是由于下面显示的“这是为了向后兼容性”而链接吗?如果是这样,那么“auth”在哪里可以使用?所有的包都在myapp/packages/目录下吗?那么在mean.io基本应用程序目录myapp/中如何处理?
var auth = require('./server/config/authorization');
// This is for backwards compatibility
mean.register('auth', function() {
return auth;
});
问题C:为什么是“Access.passport = passport;”,而不是把“Access.middleware = auth;”改为“Access.auth = auth”会发生什么?