Location of Iron Router Code - meteor

I want to verify that I am placing my Iron Router code in the correct location. Right now I have it stored in lib/router.js, which means the code is shared on the client and server. Is that correct?
Also, some of my routes require admin status, such as:
Router.route('/manage', function () {
if ($.inArray('admin', Meteor.user().roles) > -1) {
this.render('manage');
} else {
this.render('403_forbidden');
}
});
Is that code safe in its current location? I am also interested in knowing how I can test these kinds of security holes so that I don't have to ask in the future.
Thanks

As to location of router.js ...
Yes, you want it to be available on both the client and server. So putting inside the /lib directory is fine. Really, you can put it anywhere other the the /client or /server directories.
FWIW, in most projects I've looked at, router.js is stored in the top-level project directory. Possibly this is to avoid load order issues (i.e. if the router has some dependencies on files in /lib, /client, or /server, which will generally be loaded before top-level files), or possibly its because everyone I've looked at is working off the same boilerplate code. Check out the Meteor official docs if you want to know more about load order.
As for your admin question, that route should be OK. You can test it by opening up a client side console like firebug and trying something like :
Meteor.users.update(Meteor.userId(), {$set: {roles: ['admin']}});
I believe users can only update fields in the Meteor.users.profile, so this should fail. If it doesn't, you can just add the following deny rule (in client + server);
Meteor.users.deny({
update: function() {
return true;
}
});

Related

Service worker caches files but doesn't load offline

This is my first time experimenting with service workers, and I'm sure I'm doing something stupid.
I have a service worker set up for a WordPress theme I'm working on. It's located at /public_html/wp-content/themes/framework/assets/scripts/service-worker.js.
I have set the header Servie-Worker-Allowed: "/" via the .htaccess file.
I'm using sw-toolbox to make things easier. My script is below.
Script:
toolbox.precache(["/", "../media/logo.svg", "../media/spritesheet.svg", "../scripts/modern.js", "../styles/modern.css"]);
toolbox.router.get("../media/*", toolbox.cacheFirst);
toolbox.router.get("/wp-content/uploads/*", toolbox.cacheFirst);
toolbox.router.get("/*", toolbox.networkFirst, {NetworkTimeoutSeconds: 5});
The service worker properly registers, and no errors are thrown. All files set to precache show up under Cache > Cache Storage in Chrome's developer tools correctly. For some reason these cached files aren't being served when offline.
I know there's issues with the scope of the service worker, but the Service-Worker-Allowed header should correct for that. Given that the files do in fact show up in cache without issue, I'd think that this is all working correctly.
What am I missing?
Note: I'd like to keep service-worker.js and the files I'm caching where they are and with relative paths; it becomes problematic moving them to the root or giving them absolute paths because this WordPress theme gets re-used on builds and has its name changed every time, making absolute paths a pain. I tested out rewriting to the root with .htaccess, which did work, but had it's own issues. I don't understand why that would work but what I'm currently trying wouldn't.
I think I was going about this wrong. There doesn't appear to be a need to manually specify to cache my theme assets as long as I've enabled caching in general. To that end, I've instead set up a rewrite rule so that service-worker.js lives at the root (i.e. https://www.example.com/service-worker.js), thus giving it correct scope. This has enabled my project to work offline. Code for this is below.
((global) => {
// disable the service worker for post previews
global.addEventListener("fetch", (event) => {
if (event.request.url.match(/preview=true/)) {
return;
}
});
// ensure the service worker takes over as soon as possible
global.addEventListener("install", event => event.waitUntil(global.skipWaiting()));
global.addEventListener("activate", event => event.waitUntil(global.clients.claim()));
// set up the cache
global.toolbox.precache(["/", "/offline/"]);
global.toolbox.router.get("/wp-content/uploads/*", toolbox.cacheFirst);
global.toolbox.router.get("/*", toolbox.networkFirst, {NetworkTimeoutSeconds: 5});
// redirect offline queries to offline page
self.toolbox.router.get("/(.*)", function (req, vals, opts) {
return toolbox.networkFirst(req, vals, opts).catch((error) => {
if (req.method === "GET" && req.headers.get("accept").includes("text/html")) {
return toolbox.cacheOnly(new Request("/offline/"), vals, opts);
}
throw error;
});
});
})(self);

Need to call the meteor js function from php

Is it possible to call the meteor functions from php. i need to call like this for integrate the new package on my site. the package in meteor js.
If it is possible please give the example for this
This is quite a simple one! In php you can do something with a http call such as file_get_contents("http://yoursite.com/api/yourfunction?variableOne=1");
Or even curl if you want
And in Meteor (assuming you understand Iron Router and server side routes) do something like
Router.route( "/api/yourfunction", function() { var variableOne = this.request.header.variableOne;
this.response.statusCode = 200; //Post your status code
this.response.end();}, { where: "server" });
If you are making a CORS request, remember to allow access to cross servers (don't use the wildcard *)
this.response.setHeader( 'access-control-allow-origin', '*' );
Edit: Did this answer help? If so please rate it

Meteor: what code goes on the client side and server side?

I just don't know exactly what I should put on the server side and what on the client side. I understand that the templates goes on the client side. But what about the javascript code? Can you give me an example of some code going on the server side?
You can write all your business logic and complex database operations in your server side code. Typically the code you don't want to serve to the client.
For example.
Method calls
# client-side
Template.post.events({
"click #add-post": function(e) {
var post, post_object;
post = $("#post-message").val().trim();
post_object = {
user_id: Meteor.userId(),
post: post
};
Meteor.call("create_post", post_object,(function(error, response) {
if(error){
..do something
}else{
.. do something else
});
);
}
});
# server-side
Meteor.methods({
create_post: function(post_object) {
return Posts.insert(post_object);
}
});
publish / subscribe
# common
Posts = new Mongo.Collection("posts");
# client-side
Meteor.subscribe("posts");
# server-side
Meteor.publish("posts", function(limit) {
return Posts.find({
user_id: this.userId
});
});
Html, css and Template managers should go into the client-side code. Meteor methods and publishers should go into the server-side code. Read more about structuring the app and data security in official docs.
Here is an example for a collection: Declare, publish and subscribe to it.
Server and client (any directory except private, client, or server, don't use public for that too), declare the collection:
Rocks = new Meteor.Collection('rocks');
Server-side (server directory or in a Meteor.isServer condition) ,publish the collection:
Meteor.publish('allRocks', function()
{
return Rocks.find();
}
Client-side (client directory or in a Meteor.isClient condition), subscribe to the publication:
Meteor.subscribe('allRocks');
You can find a lot of examples in the documentation or in this blog (Discover Meteor).
Edit: For more precision according to OP's question... All code is shared by default (executed by both the server and the client). However, files in the server and private directory will never be sent to the client.
if create a directory named client that goes only to client.
if you create a directory named server that goes only to server.
every thing else you code goes to client and server both. (even if
you use Meteor.isServer check)
you can read more about directory structure here.
You use Meteor.isClient and Meteor.isServer to load the code in the proper place.
Using the folder:
server - goes to the server duh!
client - goes to the client duh!
both - shared code
Everything that is placed outside client or server, is loaded on both places.
When you create Meteor package you've to add manually the files and specify where it should be loaded, example:
api.add_files(['my-packages.js', 'another-file.js'], 'client');
api.add_files(['server/methods.js'], 'server');
On this example althouhg you have a server folder, it doesn't mean that it be placed in the server, in the package scenario.
Something you've code that is going to run on the client and server but some functionalities might only be present at server or client.
Example:
ImageManager = {
uploadImageToAmazonS3 : function(){
if(Meteor.isServer){
//your code goes here
//YOU DON'T WANT TO SEND YOUR AMAZON PRIVATE KEY TO THE CLIENT
//BAD THINGS CAN HAPPEN LIKE A HUGE BILL
var amazonCredentials = Config.amazon.secretKey;
}
else{
throw new Error("You can't call this on the client.");
}
}
}
This a scenario where you can add functions that the client can do like: resizeImage, cropImage, etc and the server can also do this, this is shared code. Send a Private API KEY to the client is out of question but this file will be shared by the server and client.
Documentation: http://docs.meteor.com/#/basic/Meteor-isServer
According to the documentation this doesn't prevent the code from being sent to client, it simply won't run.
With this approach an attack knows how things work at the server and might try an attack vector based on the code that you sent to the him.
The best option here is extend the ImageManager only on the server. On the client this function shouldn't even exist or you can simply add a function throwing an error: "Not available".

How do I access Request Parameters in Meteor?

I am planning to use Meteor for a realtime logging application for various
My requirement is pretty simple, I will pass a log Message as request Parameter ( POST Or GET) from various application and Meteor need to simply update a collection.
I need to access Request Parameters in Meteor server code and update Mongo collection with the incoming logMessage. I cannot update Mongo Collection directly from existing applications, so please no replies suggesting the same.I want to know how can I do it from Meteor framework and not doing it by adding more packages.
EDIT: Updated to use Iron Router, the successor to Meteor Router.
Install Iron Router and define a server-side route:
Router.map(function () {
this.route('foo', {
where: 'server',
action: function () {
doSomethingWithParams(this.request.query);
}
});
});
So for a request like http://yoursite.com/foo?q=somequery&src=somesource, the variable this.request.query in the function above would be { q: 'somequery', src: 'somesource' } and therefore you can request individual parameters via this.request.query.q and this.request.query.src and the like. I've only tested GET requests, but POST and other request types should work identically; this works as of Meteor 0.7.0.1. Make sure you put this code inside a Meteor.isServer block or in a file in the /server folder in your project.
Original Post:
Use Meteorite to install Meteor Router and define a server-side route:
Meteor.Router.add('/foo', function() {
doSomethingWithParams(this.request.query);
});
So for a request like http://yoursite.com/foo?q=somequery&src=somesource, the variable this.request.query in the function above would be { q: 'somequery', src: 'somesource' } and therefore you can request individual parameters via this.request.query.q and this.request.query.src and the like. I've only tested GET requests, but POST and other request types should work identically; this works as of Meteor 0.6.2.1. Make sure you put this code inside a Meteor.isServer block or in a file in the /server folder in your project.
I know the questioner doesn't want to add packages, but I think that using Meteorite to install Meteor Router seems to me a more future-proof way to implement this as compared to accessing internal undocumented Meteor objects like __meteor_bootstrap__. When the Package API is finalized in a future version of Meteor, the process of installing Meteor Router will become easier (no need for Meteorite) but nothing else is likely to change and your code would probably continue to work without requiring modification.
I found a workaround to add a router to the Meteor application to handle custom requests.
It uses the connect router middleware which is shipped with meteor. No extra dependencies!
Put this before/outside Meteor.startup on the Server. (Coffeescript)
SomeCollection = new Collection("...")
fibers = __meteor_bootstrap__.require("fibers")
connect = __meteor_bootstrap__.require('connect')
app = __meteor_bootstrap__.app
router = connect.middleware.router (route) ->
route.get '/foo', (req, res) ->
Fiber () ->
SomeCollection.insert(...)
.run()
res.writeHead(200)
res.end()
app.use(router)
Use IronRouter, it's so easy:
var path = IronLocation.path();
As things stand, there isn't support for server side routing or specific actions on the server side when URLs are hit. So it's not easy to do what you want. Here are some suggestions.
You can probably achieve what you want by borrowing techniques that are used by the oauth2 package on the auth branch: https://github.com/meteor/meteor/blob/auth/packages/accounts-oauth2-helper/oauth2_server.js#L100-109
However this isn't really supported so I'm not certain it's a good idea.
Your other applications could actually update the collections using DDP. This is probably easier than it sounds.
You could use an intermediate application which accepts POST/GET requests and talks to your meteor server using DDP. This is probably the technically easiest thing to do.
Maybe this one will help you?
http://docs.meteor.com/#meteor_http_post

Subscribing to a collection error

I'm really not sure what the issue is here. Maybe I don't understand the publish/subscribe docs enough.
In my server directory:
Meteor.publish("kudos", function () {
return Kudos.find({});
});
In my client directory:
Meteor.startup(function(){
Meteor.subscribe("kudos");
});
Template.launchsection.kudos = function () {
return Kudos.find({});
};
When I run this, I get an error of Kudos is not defined for the line that returns Kudos.find({});.
What am I missing?
Specifically, you need to write Kudos = new Meteor.Collection("kudos") in both your client and server directory.
Make sure that you define the Schema in a js file which is executed on both, client and server. A file Schema.js in the root folder of your meteor app should do the trick. Have a look at this question.
Hope that helps! :)

Resources