我克隆了https://github.com/beeman/loopback-angular-admin
我使用环回资源管理器创建了几个新角色但是如何为我创建的用户分配角色
我有一个用户模型,它在环回中从User模型扩展而来 和模型文件是这样的 -
{
"name": "user",
"plural": "users",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {
"accessTokens": {
"type": "hasMany",
"model": "accessToken",
"foreignKey": "userId"
},
"identities": {
"type": "hasMany",
"model": "userIdentity",
"foreignKey": "userId"
},
"credentials": {
"type": "hasMany",
"model": "userCredential",
"foreignKey": "userId"
},
"roles": {
"type": "hasMany",
"model": "Role",
"foreignKey": "principalId",
"through": "RoleMapping"
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW"
},
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$unauthenticated",
"permission": "DENY"
},
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW"
}
],
"methods": {}
}
和我的user.js就像 -
module.exports = function (user) {
// Set the username to the users email address by default.
user.observe('before save', function setDefaultUsername(ctx, next) {
if (ctx.instance) {
if(ctx.isNewInstance) {
ctx.instance.username = ctx.instance.email;
}
ctx.instance.status = 'created';
ctx.instance.created = Date.now();
}
next();
});
};
现在,我想基于我从客户端传递的属性ctx.instance.type
为用户分配角色和主体
答案 0 :(得分:5)
假设您已经在Role表中创建了一组有限的角色,请使用after save hook为刚刚创建的User分配一个特定的角色:
User.observe('after save', function setRoleMapping(ctx, next) {
if (ctx.instance) {
if(ctx.isNewInstance) {
var RoleMapping = User.app.models.RoleMapping;
// var roleId = based on type lookup or static?
RoleMapping.create({
principalType: "USER",
principalId: ctx.instance.id,
roleId: roleId
}, function(err, roleMapping) {
if (err) {return console.log(err);}
// success stuff
}):
}
}
next();
});
代码没有经过测试,只是一个大致的想法。您不能使用之前的保存挂钩,因为您不会知道要用于RoleMapping表中的principalId的用户的ID。
更新:版本,包括按传入的类型查找角色:
user.observe('after save', function setRoleMapping(ctx, next) {
if (ctx.instance) {
if(ctx.isNewInstance) {
// look up role based on type
//
Role.find({where: {name: ctx.instance.type}}, function(err, role) {
if (err) {return console.log(err);}
RoleMapping.create({
principalType: "USER",
principalId: ctx.instance.id,
roleId: role.id
}, function(err, roleMapping) {
if (err) {return console.log(err);}
console.log('User assigned RoleID ' + role.id + ' (' + ctx.instance.type + ')');
}):
});
}
}
next();
});
查询文档位于:https://docs.strongloop.com/display/public/LB/Querying+data