6 Policies - Atlantis-Software/synapps GitHub Wiki

Overview

Policies functions are functions for authorization and access control. they let you execute some logic before a route is run, to determine whether or not to continue processing the request. The most common use-case for policies is to restrict certain routes to logged-in users only.

Example

Here is an example of a simple “Hello World” Synapps application. The remainder of this article will define and add policy function to the application called afterMidday that allow request every day after midday.

var synapps = require('@synapps/core');
var app = synapps();

var timeMiddleware = function(req, next) {
  req.time = new Date();
  next();
};

app.use(timeMiddleware);

app.route('/', function(req) {
  req.resolve('hello world');
});

app.listen(3000);

Policy function afterMidday

Here is a simple example of a policy function called “afterMidday”. This function allow request every day after midday. The policy function is assigned to a variable named afterMidday.

var afterMidday = function(req, next) {
  if (req.time.getHours() > 12) {
    return next();
  }
  next('retry later !');
};

Notice the call above to next(). Calling this function invokes the next policy function in the app. The next() function is not a part of the Node.js or Synapps API, but is the second argument that is passed to the policy function. The next() function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.

To load the policy function, call app.policy(), specifying the name of policy and the policy function.

var synapps = require('@synapps/core');
var app = synapps();

var timeMiddleware = function(req, next) {
  req.time = new Date();
  next();
};

app.use(timeMiddleware);

var afterMidday = function(req, next) {
  if (req.time.getHours() > 12) {
    return next();
  }
  next('retry later !');
};

app.policy('afterMidday', afterMidday);

// add policy option to route
app.route('/', {
    policy: 'afterMidday'
  }, function(req) {
  req.resolve('hello world');
});

app.listen(3000);

Note that you can pass an array of policies names / functions or directly a policy function in route policy option.