I am a new bee in AngularJs,below is the policy code created by Meanjs yo generator ,for learning purpose have created a library management system ,The problem what i am facing is when i am testing my server code i.e the API through browser URL...I am getting the result for
http://localhost:3000/api/searchbooks/bookname/davincicode as JSON Object
but for below url it's giving me {message: 'User is not authorized'}
http://localhost:3000/api/searchbooks/bookname/davincicode/bookName
exports.invokeRolesPolicies = function () {
acl.allow([
{
roles: ['user'],
allows: [{
resources: '/api/searchbooks',
permissions: ['get']
}, {
resources: '/api/searchbooks/bookname/:searchbookName',
permissions: ['get']
}]
},
{
roles: ['user'],
allows: [{
resources: '/api/searchbooks/bookname',
permissions: ['get']
}, {
resources: '/api/searchbooks/bookname/:searchbookName/:action',
permissions: ['get']
}]
}
])};
exports.isAllowed = function (req, res, next) {
var roles = (req.user) ? req.user.roles : ['guest'];
// If an Searchbook is being processed and the current user created it then allow any manipulation
if (req.searchbook && req.user && req.searchbook.user && req.searchbook.user.id === req.user.id) {
return next();
}
// Check for user roles
acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
if (err) {
// An authorization error occurred
return res.status(500).send('Unexpected authorization error');
} else {
if (isAllowed) {
// Access granted! Invoke next middleware
return next();
} else {
return res.status(403).json({
message: 'User is not authorized'
});
}
}
});
};
I checked my role it's going as user only ,unable to find so specific question elsewhere pls help or provide some pointers.
I have got the issue made mistake in routing part :
app.route('/api/searchbooks/bookname/:searchbookName/:actionValue').all(searchbooksPolicy.isAllowed)
.get(searchbooks.read)
Here in policy url its action and i have to give actionValue as the parameter name.
so passing incorrect parameter name was an issue..
Related
I am trying to set resource records in AWS route 53 via the SDK and I am getting an Invalid Request error(InvalidInput). Can you double check my params to make sure that I have them set correctly?
function testw () {
var params = {
ChangeBatch: {
Changes: [
{
Action: 'CREATE',
ResourceRecordSet: {
Name: 'example.com',
Type: 'A',
AliasTarget: {
DNSName: 's3-website-us-east-1.amazonaws.com',
EvaluateTargetHealth: false,
HostedZoneId: 'Z1YU6G6WEXAMP'
},
}
},
],
Comment: 'This is a test and it should be working.'
},
HostedZoneId: 'Z1YU6G6WEXAMP'
};
route53.changeResourceRecordSets(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
Thanks for any help!!
Can you try removing the TTL? When you use aliases, you do not specify the TTL as Route 53 will use the target's TTL. Also, per the documentation, your alias target zone id should be Z3AQBSTGFYJSTF.
I have a collections for Errors that displays to the user. I want to insert into this collection whenever a user receives an error, so it can be displayed in a template.
I have a few hooks on my collections that will reject it.
// only admins can create and update plans
Plans.allow({
insert: function(userId, doc) {
return Roles.userIsInRoles(userId, 'admin');
},
update: function(userId, doc) {
return Roles.userIsInRoles(userId, 'admin');
}
});
// Can only have one active plan currently
Plans.deny({
update: function(userId, doc) {
var now = new Date();
Plans.find({
active: true,
_id: { $in: doc.planIds },
dateStart: { $gt: now },
dateEnd: { $lt: now }
}).count() > 0;
}
});
My question is; can I listen to these events and, when rejected, take a particular action on the client and server?
You can insert on the collection via the callback function on whatever insert/update/remove you have.
If you want to do to on the server way (sing Meteor.methdos/Meteor.call), this is the workflow.
JS
//server
Meteor.method({
insertDoc:function(doc){
Plans.insert(doc)
}
})
//Client
Errors = new Mongo.Collection(null) //client side only
Meteor.call('insertDoc',{test:doc},function(err,result){
if(err){
Error.insert({error:err.reason}) //if there is a error lets insert it
}
})
//and the helper to show the error.
Template.example.helpers({
showError:function(){
return Error.find();
}
})
HTML
<template name="example">
<span>Sorry there was an error: {{error}}</span>
</template>
You got the idea.
I am trying to insert events via the Google Calendar API with a service account. The goal is to have one calendar that all users view: a server-to-server setup.
As of now, I can properly call the calendar API and list the events on said calendar:
var moment = require("moment"),
googleapis = require("googleapis"),
googleCal = googleapis.calendar("v3");
serviceEmail = "********#developer.gserviceaccount.com",
serviceKeyFile = "./key.pem";
var authClient = new googleapis.auth.JWT(
serviceEmail,
serviceKeyFile,
null,
["https://www.googleapis.com/auth/calendar"]
);
authClient.authorize(function (err, tokens) {
if (err) {
console.log(err);
} else {
googleCal.events.list({
auth: authClient,
calendarId: "********#gmail.com",
fields: {
items: ["end","start","summary"]
}
}, function (err, CL) {
if (err) {
console.log(err);
} else {
console.log(CL);
}
});
}
})
This properly returns a JSON object that lists all the different objects on the calendar. However, when I try to insert an event directly below the googleCal.events.list call:
googleCal.events.insert({
auth: authClient,
calendarId: "primary",
resources: {
start: {
dateTime: "2014-07-23T18:25:00.000-07:00",
timeZone: "America/New_York"
},
end: {
dateTime: "2014-07-23T19:25:00.000-07:00",
timeZone: "America/New_York"
},
summary: "winning # life",
description: "winning # life description"
}
}, function (err, something) {
if (err) {
console.log(err);
} else {
console.log(something);
// do something else
}
})
The following 400 is returned:
{ errors:
[ { domain: 'global',
reason: 'required',
message: 'Missing end time.' } ],
code: 400,
message: 'Missing end time.'}
How do I go about fixing this? The authorization is clearly working—I know because I've used up my unauthorized requests for the day and because I can list all the events. I have also specified an endTime. Why is the google calendar API telling me that I haven't?
I think the problem is in the keyword "resources" on line 4 of your second snippet. Based on the documentation, it should be a "resource":
* #param {object} params.resource - Request body data
How to get all contacts of a loggedin user,i added request permission to access google contacts
requestPermissions: {
facebook: ['email', 'user_friends','read_friendlists'],
google:['https://www.google.com/m8/feeds']
},
I don't know how to access contacts,i tried to google it but i'm confused with the results.
Does anyone know how to do this?
can anyone point me to the answer?
I really appreciate any help
I Just used google-contacts atmosphere package and write the following function in server side and it worked for me
var opts= { email: Meteor.user().services.google.email,
consumerKey: "APIKEY",
consumerSecret: "APPSECRET",
token: Meteor.user().services.google.accessToken,
refreshToken: Meteor.user().services.google.refreshToken};
gcontacts = new GoogleContacts(opts);
gcontacts.refreshAccessToken(opts.refreshToken, function (err, accessToken)
{
if(err)
{
console.log ('gcontact.refreshToken, ', err);
return false;
}
else
{
console.log ('gcontact.access token success!');
gcontacts.token = accessToken;
gcontacts.getContacts(function(err, contact)
{
\\here i am able to access all contacts
console.log(contact);
})
}
});
To do this,you need a refreshToken from google,by default meteor will not get it for you.
Add the following code in client side to get the refreshtoken(requestOfflineToken)
Accounts.ui.config({
requestPermissions: {
facebook: ['email', 'user_friends','read_friendlists'],
google:['https://www.google.com/m8/feeds']
},
requestOfflineToken: {
google: true
},
passwordSignupFields: 'USERNAME_AND_EMAIL'
});
NOTE: To work with contacts API you need to enable contacts api in your google console.
Hope it may help someone out there.
i need to provide something like an association in my Model. So I have a Model called Posts with an userid and want to get the username from this username and display it.
So my ForumPosts.js Model looks like the following:
module.exports = {
schema: true,
attributes: {
content: {
type: 'text',
required: true
},
forumTopicId: {
type: 'text',
required: true
},
userId: {
type: 'integer',
required: true
},
getUsername: function(){
User.findOne(this.userId, function foundUser(err, user) {
var username = user.username;
});
console.log(username);
return username;
}
}
};
I know that this return will not work because it is asynchronus... But how can i display it in my view? At the Moment i retrive the value with:
<%= forumPost.getUsername() %>
And for sure get an undefined return...
So the question is: How can I return this value - or is there a better solution than an instanced Model?
Thanks in advance!
Off the top of my head, you can just load associated user asynchronously before rendering:
loadUser: function(done){
var that = this;
User.findOne(this.userId, function foundUser(err, user) {
if ((err)||(!user))
return done(err);
that.user = user;
done(null);
});
}
then in your controller action:
module.exports = {
index: function(req, res) {
// Something yours…
forumPost.loadUser(function(err) {
if (err)
return res.send(err, 500);
return res.view({forumPost: forumPost});
});
}
}
and in your view:
<%= forumPost.user.username %>
This is kind of a quick and dirty way. For a more solid and long-term solution (which is still in development so far) you can check out the alpha of Sails v0.10.0 with the Associations API.
So this particularly case of associations between your models. So here you have a User model and ForumPost model and you need the user object in place of your user_id as user_id works as a relationship mapping field to your User model.
So if your are using sails V0.9.8 or below you need to handle this logic in your controller where ever you want to access User model attributes in your view.
In your controller write your logic as:
model.export = {
//your getForumPosts method
getForumPosts : function(req,res){
var filters = {};
forumPost.find(filters).done(function(err,posts){
if(err) return res.send(500,err);
// Considering only one post obj
posts = posts[0];
postByUser(posts.user_id,function(obj){
if(obj.status)
{
posts.user = obj.msg;
delete posts.user_id;
res.view({post:posts});
}
else
{
res.send(500,obj.msg);
}
});
}
}
}
function postByUser(user_id,cb){
User.findOne(user_id).done(function(err,user){
if(err) return cb({status:false, msg:err});
if(user){
cb({status:true, msg:user});
}
}
}
and then you can access your post object in your view.
Or else you can keep watch (at GitHub) on next version of sails as they have announced associations in V0.10 n it is in beta testing phase as if now.