Number of visitors to my webpage - javascript

I am trying to create a webpage using meteor which records the number of visitors to the webpage. The webpage should record and display the number of people who visited the webpage.I am just a beginner to meteor and web design ,i have no experience whatsoever in using meteor and this is my first attempt. So any help is appreciated. Thank you in advance.

You can also run AWstats
http://awstats.sourceforge.net/
and install tutorial here:
http://www.youtube.com/watch?v=dOF4MDn_TI0

you can have something like this
collections\system.js
this.System = new Meteor.Collection('system');
Meteor.methods({
pageViewInc: function() {
System.update({ config: true }, { $inc: { 'stats.pageviews': 1 } });
}
});
if (Meteor.isServer) {
isSystemExist = System.findOne({ config: true });
if (!isSystemExist) {
options = {
stats: {
pageviews: 0
},
config: true
};
System.insert options
}
}
and somewhere you can have a function use to Meteor.call 'pageViewInc'
if u use Meteor-Iron-Router
you can have call in 'after' callback
Meteor.call('pageViewInc');
you can make similar method to Posts Collection.
or there's a meteor-collection-hooks packages
it has after findOne hook you can do it by server side.

Related

Managing browser permissions with Laravel Dusk

Total Laravel Dusk noob here (started using it today). I wanted to test a "copy link" on the Web app I'm working on and I ran into browser permissions issues when trying to access the clipboard content while testing. Of course, that default behavior makes sense, because Google Chrome prompts the user and ask for permission to access the clipboard. However, I haven't found a way to tell Dusk to enable specific permissions. I found the following Cypress example that is probably the appropriate way of doing it, but I don't know if there's a Dusk equivalent.
cy.wrap(Cypress.automation('remote:debugger:protocol', {
command: 'Browser.grantPermissions',
params: {
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
origin: window.location.origin,
},
}))
Thanks in advance!
You can add this function to your DuskTestCase class.
use Facebook\WebDriver\Chrome\ChromeDevToolsDriver;
//
protected function grantPermission(Browser $browser, $permissions)
{
try {
$driver = $browser->driver;
$devtools = new ChromeDevToolsDriver($driver);
$result = $devtools->execute('Browser.grantPermissions', [
"permissions" => $permissions,
]);
return $result;
} catch (\Exception) {
return null;
}
}
And use it globally in a real test case like this
public function testClipboard()
{
$this->browse(function (Browser $browser) {
$this->grantPermission($browser, ["clipboardReadWrite", "clipboardSanitizedWrite"]);
// Your test flow and assertion
});
}
Hope my answer can help.

Meteor: Limiting DDP Connections with ddp-rate-limiter package

I am trying to prevent a user to be able to call a Meteor method too often with the Meteor package ddp-rate-limiter (For example to prevent spamming or a DOS attack), but I can not get it to work.
Does anybody have an idea?
server/ddpRateLimiter.js:
Meteor.methods({
dosAttack: function() {console.log("dos");}
});
var preventDosAttack= {
userId: function() {return true;},
type: 'method',
method: 'dosAttack'
}
DDPRateLimiter.addRule(preventDosAttack, 5, 1000);
With this code I can still run the method from the client console as often as I want to. (Tested with a for loop 100 times)
You can find the entire sourcecode here: opensource project
And this certain commit here: commit
Thank you very much for your help,
Max
My mistake is simple: It is not 'method': 'dosAttack' but 'name': 'dosAttack'. Seems like the example in the documentation MeteorDoc DDPRateLimiter does the same mistake. I created an issue on the meteor GitHub page
Rate limiting is now offered as a vendor-supported Meteor package. I've recently used it to create Meteor Candy, the admin panel for Meteor. Here's how I did it.
First, add the package:
meteor add ddp-rate-limiter.
Second, define the method:
Meteor.methods({
myFancyMethod: function () {
return true;
}
})
Finally, define the rate limiting rules for it:
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
var requestLimit = 5;
var requestTimeout = 5000;
DDPRateLimiter.addRule({
type: "method",
name: "myFancyMethod",
}, requestLimit, requestTimeout);

Where to add role based authentication to MeanJS app?

I have a meanjs starter template (with yeoman generator).
Where can I add specific permissions to my modules? For instance,
'use strict';
// Configuring the Articles module
angular.module('adminpanel').run(['Menus',
function(Menus) {
// Set top bar menu items
//Menus.addMenuItem('topbar', 'admin panel', 'adminpanel/', 'adminpanel');
Menus.addMenuItem('topbar', 'Admin Panel', 'adminpanel', 'dropdown', '/buildings(/create)?');
Menus.addSubMenuItem('topbar', 'adminpanel', 'List Collections', 'adminpanel/collections');
}
]);
and the routes like so
'use strict';
//Setting up route
angular.module('adminpanel').config(['$stateProvider',
function($stateProvider) {
// Adminpanels state routing
$stateProvider.
state('listCollections', {
url: '/adminpanel/collections',
templateUrl: 'modules/adminpanels/views/list-collections.client.view.html'
}).
state('showCollection', {
url: '/adminpanel/collections/:collectionName',
templateUrl: 'modules/adminpanels/views/show-collection.client.view.html'
}).
state('showCollectionItem', {
url: '/adminpanel/collections/:collectionName/:itemId',
templateUrl: 'modules/adminpanels/views/show-item.client.view.html'
});
}
]);
Are these the correct places to add role-based authentication (on the client side), with added measure on the serverside (I've already done that)?
Does anybody know how I can add an option to the Menus.(some function), such as 'admin.hasPermission', without breaking it? Any resources on this sort of thing?
Thanks for the help!
I don't believe it is right practice to put your authentication, authorization code at the client side as well as server side. They should be on the server side only.
The point is, you have to replicate your authentication and authorization code in the client, anyone can read your mechanism to handle these situation and once a loophole is discovered, it would simply be followed by your server code as well.
I believe authentication and authorization logic should be restricted to server side only. If I am up against someone professional, it would at least make his task tougher.
In case you insist, you can create a wrapper around $http service, maintain a key value pair of what role can do what, and ensure all AJAX request go through your wrapper service where you can check whether it should be allowed. If yes, you can simply forward the request using $http and if not, throw an error.
Not sure about any previous version, but with version 0.4.0 there are parameter in the client config to control the visibility:
If you set isPublic: false and add a roles array you can set the user that can see the menu entry:
// Add the dropdown listCollentcions item
Menus.addSubMenuItem('topbar', 'adminpanel', {
title: 'listCollections',
isPublic: false,
roles:['admin'],
state: 'adminpanel.listCollections'
});
The implementation is in the core module (menu.client.services.js):
// A private function for rendering decision
var shouldRender = function(user) {
if (user) {
if (!!~this.roles.indexOf('*')) {
return true;
} else {
for (var userRoleIndex in user.roles) {
for (var roleIndex in this.roles) {
if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
return true;
}
}
}
}
} else {
return this.isPublic;
}
return false;
};
Maybe you can give version 0.4.0 a try or have a look at the code and try to implement it urself.

Running background tasks in Meteor.js

This is my scenario:
1. Scrape some data every X minutes from example.com
2. Insert it to Mongodb database
3. Subscribe for this data in Meteor App.
Because, currently I am not very good at Meteor this is what I am going to do:
1. Write scraper script for example.com in Python or PHP.
2. Run script every X minutes with cronjob.
3. Insert it to Mongodb.
Is it possible to do it completely with Meteor without using Python or PHP? How can I handle task that runs every X minutes?
There are Cron like systems such as percolate:synced-cron for Meteor. There, you could register a job using Later.js syntax similar to this example taken from the percolate:synced-cron readme file:
SyncedCron.add({
name: 'Crunch some important numbers for the marketing department',
schedule: function(parser) {
// parser is a later.parse object
return parser.text('every 2 hours');
},
job: function() {
var numbersCrunched = CrushSomeNumbers();
return numbersCrunched;
}
});
If you want to rely on an OS level cron job, you could just provide an HTTP endpoint in your Meteor.js application that you could then access through curl at the chosen time.
I can suggest Steve Jobs, my new package for scheduling background jobs in Meteor.
You can use the register, replicate, and remove actions
// Register the job
Jobs.register({
dataScraper: function (arg) {
var data = getData()
if (data) {
this.replicate({
in: {
minutes: 5
}
});
this.remove(); // or, this.success(data)
} else {
this.reschedule({
in: {
minutes: 5
}
})
}
}
})
// Schedule the job to run on Meteor startup
// `singular` ensures that there is only pending job with the same configuration
Meteor.startup(function () {
Jobs.run("dataScraper", {
in: {
minutes: 5
},
singular: true
})
})
Depending on your preference, you can store the result in the database, as part of the jobs history, or remove it entirely.

How to push notifications with angular.js?

I have been building a simple application to learn angular.js. So far I hooked up all the pieces in the MEAN stack and I am able to save and retrieve data from Mongo.
The app is essentially a todo list. The user can create a project and inside the project create "cards" with "todos" which can then be moved from state to state ("backlog", "in progress", "complete", etc.)
I would like to be able to push the notifications to all the people who are connected to tell their apps that a refresh is needed to get the latest todos. In other words, let's say that user A adds a new card to project A, I would like to send a message out to all users who are currently watching project A so that their application issues a project refresh to get the latest and greatest.
Any suggestions on how to proceed? Which technology, if any, I need to add to the MEAN stack to be able to do something like this?
Thanks in advance
Since you're on the MEAN stack, the standard recommendation in Node would be to use the Socket.IO API.
They provide the following example of two way messaging (which would facilitate your push messages very easily):
Client
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Server
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
It will use websockets where possible, and fallback to AJAX long polling or Flash polling in browsers where there is no websocket support.
As for integrating with Angular, here's a good blog post on Socket.IO and Angular:
I'll be writing about how to integrate Socket.IO to add real-time
features to an AngularJS application. In this tutorial, I'm going to
walk through writing a instant messaging app.
If you're already working with Express, you should check out express.io.
It has a bunch of cool features like Session support and the ability to forward normal HTTP routes to realtime routes.
Here is a module we have written for getting AngularJS push notifications working in PhoneGap / Cordava (with full instructions):
http://www.scorchsoft.com/blog/free-angularjs-cordova-push-notification-plugin/
Simply download the example code and install. There is also code included for setting up the pushing component in PHP.
Why not with HTML5 Notification API....
export default class NotificationService {
/**
* Constructor of the class.
*
*/
constructor() {}
showPushNotification(title: string = '', message: string, iconPush) {
if (window.Notification && Notification.permission !== "denied") {
Notification.requestPermission(function(status) {
var n = new Notification(title, {
body: message,
icon: iconPush
});
});
}
}
}

Categories