I have a loopback app with mongoDB as below:
when i login as Admin i cannot use post method on dishes. and i get authorization required error.
that becomes possible only when i change the dishes role to ALLOW everyone.
how can i acheive the wanted result with keeping everyone on DENY and only ALLOW certain users to certain operations?
thank you. here is my code..
app/server/model-config.json:
{
"_meta": {
"sources": [
"loopback/common/models",
"loopback/server/models",
"../common/models",
"./models"
],
"mixins": [
"loopback/common/mixins",
"loopback/server/mixins",
"../node_modules/loopback-ds-timestamp-mixin",
"../common/mixins",
"./mixins"
]
},
"User": {
"dataSource": "db"
},
"AccessToken": {
"dataSource": "db",
"public": false
},
"ACL": {
"dataSource": "MongoDB",
"public": false
},
"RoleMapping": {
"dataSource": "MongoDB",
"public": false
},
"Role": {
"dataSource": "MongoDB",
"public": false
},
"dishes": {
"dataSource": "MongoDB",
"public": true
},
"Customer": {
"dataSource": "MongoDB",
"public": true
},
"Comments": {
"dataSource": "MongoDB",
"public": true
}
}
app/common/modles/dishes.json:
{
"name": "dishes",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
},
"description": {
"type": "string",
"required": true
},
"category": {
"type": "string",
"required": true
},
"image": {
"type": "string",
"required": true
},
"label": {
"type": "string",
"required": true,
"default": "''"
},
"price": {
"type": "string",
"required": true,
"default": "0"
}
},
"mixins": {
"TimeStamp": true
},
"validations": [],
"relations": {
"comments": {
"type": "hasMany",
"model": "Comments",
"foreignKey": ""
},
"customers": {
"type": "hasMany",
"model": "Customer",
"foreignKey": ""
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW",
"property": "create"
},
{
"accessType": "WRITE",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW"
}
],
"methods": {}
}
app/common/modles/comments.json:
{
"name": "Comments",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"Rating": {
"type": "number",
"required": true,
"default": 5
},
"comment": {
"type": "string",
"required": true
}
},
"mixins": {
"TimeStamp": true
},
"validations": [],
"relations": {
"dishes": {
"type": "belongsTo",
"model": "dishes",
"foreignKey": ""
},
"customer": {
"type": "belongsTo",
"model": "Customer",
"foreignKey": "customerId"
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW",
"property": "create"
},
{
"accessType": "WRITE",
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW"
}
],
"methods": {}
}
app/common/modles/customer.json:
{
"name": "Customer",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {
"comments": {
"type": "hasMany",
"model": "Comments",
"foreignKey": "customerId"
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
}
],
"methods": {}
}
and app/server/boot/script.js:
module.exports = function(app) {
var MongoDB = app.dataSources.MongoDB;
MongoDB.automigrate('Customer', function(err) {
if (err) throw (err);
var Customer = app.models.Customer;
Customer.create([
{username: 'Admin', email: 'admin#admin.com', password: 'abcdef'},
{username: 'muppala', email: 'muppala#ust.hk', password: 'abcdef'}
], function(err, users) {
if (err) throw (err);
var Role = app.models.Role;
var RoleMapping = app.models.RoleMapping;
Role.find({ name: 'admin' }, function(err, results) {
if (err) { throw err; }
if (results.length < 1) {
// now we know the DB doesn't have it already, so do the Role creation...
//create the admin role
Role.create({
name: 'admin'
}, function(err, role) {
if (err) throw (err);
//make admin
role.principals.create({
principalType: RoleMapping.USER,
principalId: users[0].id
}, function(err, principal) {
if (err) throw (err);
});
});
}
});
});
});
};
Seeing your last question I imagine what happened.
Somehow the collection Role was created but not mapped to User.
I suggest you to change:
Role.find({ name: 'admin' }, function(err, results) {
if (err) { throw err; }
if (results.length < 1) {
// now we know the DB doesn't have it already, so do the Role creation...
//create the admin role
Role.create({
name: 'admin'
}, function(err, role) {
if (err) throw (err);
//make admin
role.principals.create({
principalType: RoleMapping.USER,
principalId: users[0].id
}, function(err, principal) {
if (err) throw (err);
});
});
}
});
By:
Role.create({
name: 'admin'
}, function(err, role) {
if (err) throw (err);
//make admin
role.principals.create({
principalType: RoleMapping.USER,
principalId: users[0].id
}, function(err, principal) {
if (err) throw (err);
});
});
Drop the Role collection:
db.Role.drop()
and execute Loopback again.
Note: I was doing the same assigment and worked for me.
I am also having the same trouble as I come through the same assignment. Mr Kike's answer works for mine.
First, from cmd, type
>mongo
>use conFusion (Note: conFusion is the name of database of this assignment)
>show collections (Note: to see all collections in database collections)
>db.Role.drop()
And then run the loopback with node . again
Related
Hello I'm new to loopback and I'm stucked on the Role creation and use.So basically what I'm trying to do is to create 2 roles and based on these roles I want to restrict some users to access some resources.The problem is that on every attempt to get some information from the api I'm getting this
{
"error": {
"statusCode": 401,
"name": "Error",
"message": "Authorization Required",
"code": "AUTHORIZATION_REQUIRED",
"stack": "Error: Authorization Required\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\loopback\\lib\\application.js:433:21\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\loopback\\lib\\model.js:359:7\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\loopback\\common\\models\\acl.js:536:16\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\async\\dist\\async.js:3888:9\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\async\\dist\\async.js:473:16\n at iteratorCallback (C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\async\\dist\\async.js:1064:13)\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\async\\dist\\async.js:969:16\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\async\\dist\\async.js:3885:13\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\loopback\\common\\models\\acl.js:518:17\n at C:\\Users\\HP\\Desktop\\battle-horse\\battle-horse\\node_modules\\loopback\\common\\models\\role.js:447:21\n at _combinedTickCallback (internal/process/next_tick.js:131:7)\n at process._tickCallback (internal/process/next_tick.js:180:9)"
}
}
In my application I have 2 models:
1.Client (which extends build in User Model) and has role ```bs_client```
2.Admin(which also extends the build in User Model)
Note that these models were created using loopback cli and has no relationship created yet.
lb model
I'm using Mongodb as database and here is my datasource file
"mongodb": {
"host": "",
"port": 0,
"url": "mongodb+srv://general:234234##/#####?retryWrites=true&w=majority",
"database": "database",
"password": "password",
"name": "mongodb",
"user": "general",
"useNewUrlParser": true,
"includeSubDomains": true,
"useUnifiedTopology": true,
"connector": "mongodb"
}
It seems that the data is being added correctly in my collections (Role, Rolemapping, Client and Access Token).
I'm assigning role to each client dynamically upon creation using this
Client.observe('after save', function setRole(ctx, next) {
if (ctx.instance) {
if (ctx.isNewInstance) {
// look up role based on type
//
app.models.Role.find({where: {name: 'bs_client'}}, function(err, role) {
if (err) { return console.log(err); }
if (role) {
app.models.RoleMapping.create({
principalType: app.models.RoleMapping.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();
});
and here is my model-config.json
{
"_meta": {
"sources": [
"loopback/common/models",
"loopback/server/models",
"../common/models",
"./models"
],
"mixins": [
"loopback/common/mixins",
"loopback/server/mixins",
"../common/mixins",
"./mixins"
]
},
"User": {
"dataSource": "mongodb",
"public": false
},
"AccessToken": {
"dataSource": "mongodb",
"public": false
},
"ACL": {
"dataSource": "mongodb",
"public": false
},
"RoleMapping": {
"dataSource": "mongodb",
"public": true,
"options": {
"strictObjectIDCoercion": true
}
},
"Role": {
"dataSource": "mongodb",
"public": true
},
"Email": {
"dataSource": "Email"
},
"Client": {
"dataSource": "mongodb",
"public": true
},
}
and in client.json
"acls": [
{
"accessType": "*",
"principalType": "CLIENT",
"principalId": "bs_client",
"permission": "DENY"
},
{
"accessType": "READ",
"principalType": "CLIENT",
"principalId": "bs_client",
"permission": "ALLOW"
},
{
"accessType": "EXECUTE",
"principalType": "CLIENT",
"principalId": "$authenticated",
"permission": "ALLOW",
"property": "create"
},
{
"accessType": "WRITE",
"principalType": "CLIENT",
"principalId": "bs_client",
"permission": "ALLOW"
}
],
Following https://loopback.io/doc/en/lb3/Model-property-reference.html, everything should be working fine, why I'm not able to retrieve "clients" using the configuration above.
Thanks in advance.
This line should look like this everywhere in "acls": "principalType": "ROLE",
example ACL:
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW"
}
],
I'm trying to build a simple blog with loopback. I want to extend get Posts with the amount of comments.
I have two possible ways in my mind.
1) Extend the response of the get-posts by a count of the comments, this would be my favorite way, but I have no idea how to extend the reposne.
2) I have tried to observe the comment saving and to get the posts-model, but I can't change it.
post.json
{
"name": "post",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"title": {
"type": "string",
"required": true
},
"content": {
"type": "string",
"required": true
}
"published": {
"type": "boolean",
"required": true,
"default": false
}
"commentCount": {
"type": "number",
"default": 0
}
},
"validations": [],
"relations": {
"user": {
"type": "belongsTo",
"model": "user",
"foreignKey": ""
},
"comments": {
"type": "hasMany",
"model": "comment",
"foreignKey": ""
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW"
},
{
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW",
"property": "find"
},
{
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW",
"property": "create"
},
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW"
},
{
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW",
"property": [
"__create__comments",
"__get__comments"
]
},
{
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW",
"property": "__delete__comments"
}
],
"methods": {}
}
comment.json
{
"name": "comment",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"content": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {
"user": {
"type": "belongsTo",
"model": "user",
"foreignKey": ""
},
"idea": {
"type": "belongsTo",
"model": "post",
"foreignKey": ""
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW"
},
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW"
}
],
"methods": {}
}
comment.js ##
var loopback = require('loopback');
module.exports = function(Comment) {
Comment.observe('after save', function(ctx, userInstance, next) {
var postId = ctx.instance.postId;
// loopback.getModel('post').definition.rawProperties.commentCount... something... something...
});
};
I'm still very new to loopback and I don't know what is the best way to achieve the solution. Maybe you have a third, better way? Or maybe anyone can help me to complete the comment.js.
Fisrt, in your comment.json, you've written idea instead of post:
"post": { //change here
"type": "belongsTo",
"model": "post",
"foreignKey": ""
}
Secondly, you simply add one commentCount in the post linked to your comment in your after save method and then update the attributes of your post:
'use strict';
var app = require('../../server/server');
var models = app.models;
var Post;
// pattern to get your models on start event
app.on('started', function () {
Post = models.post;
});
module.exports = function(Comment) {
Comment.observe('after save', function(ctx, next) {
// only add a commentCount if it's a new instance
if (ctx.instance && ctx.isNewInstance && ctx.instance.postId) {
Post.findOne({where: {id: ctx.instance.postId}}, function (err, post) {
if (!err) {
post.updateAttributes({commentCount: post.commentCount++});
}
});
}
next();
});
};
Another solution would be to create a customGet endpoint in your post.js file:
'use strict';
module.exports = function(Post) {
Post.customGet = function (postId, cb) {
Post.findOne({where: {id: postId}, include: 'comments'}, function (err, post) {
if(err){
return cb(err, {});
}
post.commentCount = post.comments.length;
return cb(err, post);
});
}
Post.remoteMethod('customGet', {
description: 'New endpoint with the commentCount',
accepts: {arg: 'postId', type: 'string'},
returns: {arg: 'post', type: 'object'},
http: {verb: 'get'}
});
};
You can improve this method a bit but you get the idea.
Member model based on User model
{
"name": "Member",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"nickname": {
"type": "string"
}
},
"validations": [],
"relations": {
"messages": {
"type": "hasMany",
"model": "Message",
"foreignKey": ""
},
"followers": {
"type": "hasMany",
"model": "Member",
"foreignKey": "followeeId",
"through": "Follow"
},
"followings": {
"type": "hasMany",
"model": "Member",
"foreignKey": "followerId",
"through": "Follow"
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW",
"property": "__get__followers"
},
{
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW",
"property": "__get__followings"
},
{
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW",
"property": "__get__messages"
}
],
"methods": {}
}
Follow model
{
"name": "Follow",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {
"follower": {
"type": "belongsTo",
"model": "Member",
"foreignKey": ""
},
"followee": {
"type": "belongsTo",
"model": "Member",
"foreignKey": ""
}
},
"acls": [],
"methods": {}
}
Example 1
With this data in the database I have the same error when I try to fetch following and followers with member 1.
Erreur non traitée pour la demande GET /api/Members/1/followers?access_token=t0oAVZM2CLJ7XLqQm2zxz8wj3fLmtUATHopDM40WYknLURbiObpVAlSD3DBEIOfv : Error: La relation "member" n'est pas définie pour le modèle Follow
at processIncludeItem (/home/thomas/Bureau/Projet/Project/node_modules/loopback-datasource-juggler/lib/include.js:289:10)
at /home/thomas/Bureau/Projet/Project/node_modules/loopback-datasource-juggler/lib/include.js:180:5
at /home/thomas/Bureau/Projet/Project/node_modules/async/dist/async.js:3025:16
at eachOfArrayLike (/home/thomas/Bureau/Projet/Project/node_modules/async/dist/async.js:940:9)
at eachOf (/home/thomas/Bureau/Projet/Project/node_modules/async/dist/async.js:990:5)
at Object.eachLimit (/home/thomas/Bureau/Projet/Project/node_modules/async/dist/async.js:3089:3)
at Function.Inclusion.include (/home/thomas/Bureau/Projet/Project/node_modules/loopback-datasource-juggler/lib/include.js:179:9)
at /home/thomas/Bureau/Projet/Project/node_modules/loopback-connector-postgresql/node_modules/loopback-connector/lib/sql.js:1203:44
at /home/thomas/Bureau/Projet/Project/node_modules/loopback-datasource-juggler/lib/observer.js:172:22
at doNotify (/home/thomas/Bureau/Projet/Project/node_modules/loopback-datasource-juggler/lib/observer.js:99:49)
at PostgreSQL.ObserverMixin._notifyBaseObservers (/home/thomas/Bureau/Projet/Project/node_modules/loopback-datasource-juggler/lib/observer.js:122:5)
at PostgreSQL.ObserverMixin.notifyObserversOf (/home/thomas/Bureau/Projet/Project/node_modules/loopback-datasource-juggler/lib/observer.js:97:8)
at cbForWork (/home/thomas/Bureau/Projet/Project/node_modules/loopback-datasource-juggler/lib/observer.js:162:14)
at /home/thomas/Bureau/Projet/Project/node_modules/loopback-connector-postgresql/node_modules/loopback-connector/lib/sql.js:428:7
at Query.<anonymous> (/home/thomas/Bureau/Projet/Project/node_modules/loopback-connector-postgresql/lib/postgresql.js:162:7)
at Query.handleReadyForQuery (/home/thomas/Bureau/Projet/Project/node_modules/pg/lib/query.js:124:10)
Example 2
With this data in the database here is the result when I try to fetch followers with member 1.
I don't understand why i'm not able to fetch data in these two examples. BTW i'm using PostgreSQL. Thanks.
You need to fix relations in Follow model according to Member.
{
"name": "Follow",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {
"follower": {
"type": "belongsTo",
"model": "Member",
"foreignKey": "followeeId"
},
"followee": {
"type": "belongsTo",
"model": "Member",
"foreignKey": "followerId"
}
},
"acls": [],
"methods": {}
}
And in member.json
...
"followers": {
"type": "hasMany",
"model": "Member",
"foreignKey": "followeeId",
"keyThrough": "followerId",
"through": "Follow"
},
"followings": {
"type": "hasMany",
"model": "Member",
"foreignKey": "followerId",
"keyThrough": "followeeId",
"through": "Follow"
}
...
I'm currently evaluating loopback.io for developing the API portion of a new project, and I'm having problems with setting the correct ACL entries.
What I wish to accomplish is given an auth token, the GET endpoints should only return objects owned by the user. For example, a request to /Shows?access_token=xxxxxx should return only objects owned by the user.
Below is my shows.json file, and my User model is named Podcaster. Any help would be appreciated.
{
"name": "Show",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"title": {
"type": "string",
"required": true
},
"description": {
"type": "string"
}
},
"validations": [],
"relations": {
"episodes": {
"type": "hasMany",
"model": "Episode",
"foreignKey": ""
},
"podcaster": {
"type": "belongsTo",
"model": "Podcaster",
"foreignKey": ""
}
},
"acls": [
{
"accessType": "WRITE",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW",
"property": "create"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
}
],
"methods": {}
}
It's not related to ACL's.
You want to change the business logic of the method. So the best practice is that you create a new method for getting shows owning by current user.
If you want to work your current owner ACl, you need to create a relation between user and show, and set ownerId in the show model.
{
"name": "Show",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"title": {
"type": "string",
"required": true
},
"description": {
"type": "string"
},
"description": {
"type": "string"
}
"ownerId": {
"type": "object"
}
},
"validations": [],
"relations": {
"owner": {
"type": "belongsTo",
"model": "user",
"foreignKey": "ownerId"
},
....
I'm fetching a user from a mongo database, but this user that I get, doesn't have any methods, neither all the properties I was expecting. Why would this happen?
This is the code:
app.models.MyUser.findOrCreate({where: {email: req.user.email}}, {
email: req.user.email,
password: sha1sum(JSON.stringify(req.user)),
firstName: req.user.displayName
}, function (err, user) {
if (err) throw err;
console.log(user.login); //undefined
res.json(user);
});
This is the code of my model:
{
"name": "MyUser",
"plural": "myusers",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"firstName": {
"type": "string"
}
},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
],
"methods": []
}
User.login is a static method, not a prototype method. See https://github.com/strongloop/loopback/blob/master/common/models/user.js#L164. You should be able to use user.constructor.login.