Skip to content

Instantly share code, notes, and snippets.

@brianhyder
Last active August 29, 2015 14:26
Show Gist options
  • Save brianhyder/de0abf069e566f36618d to your computer and use it in GitHub Desktop.
Save brianhyder/de0abf069e566f36618d to your computer and use it in GitHub Desktop.
Creating a Cross-Origin Resource Sharing (CORS) Controller in PencilBlue
/*
Copyright (C) 2015 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
module.exports = function(pb) {
//PB dependencies
var util = pb.util;
var BaseController = pb.BaseController;
var PluginService = pb.PluginService;
/**
* CORS Controller - A sample controller to demonstrate how open up API endpoints for cross domain requests
*
* @class CorsApiController
* @constructor
* @extends BaseController
*/
function CorsApiController(){}
util.inherits(CorsApiController, BaseController);
/**
* The handler for responding to the options request
* @method render
* @param {Function} cb
*/
CorsApiController.prototype.render = function(cb) {
var result = {
content: '',
headers: {
'Access-Control-Allow-Origin': "*"
}
};
cb(result);
};
/**
* Provides the routes that are to be handled by an instance of this prototype.
* The route provides a definition of path, permissions, authentication, and
* expected content type. In this particular case we are building a simple
* API with no special CRUD operations. Therefore, we can leverage the
* power of the BaseApiController and let it do the heavy lifting for us.
* All we have to do is define the routes.
* Method is optional
* Path is required
* Permissions are optional
* Access levels are optional
* Content type is optional
*
* @param cb A callback of the form: cb(error, array of objects)
*/
CorsApiController.getRoutes = function(cb) {
var routes = [
{
//opens up all endpoints
method: 'options',
path: "*",
handler: "render",
auth_required: false,
},
{
//opens up all endpoints under a the API prefix
method: 'options',
path: "/api/*",
handler: "render",
auth_required: false,
},
{
//opens up a specific end-point
method: 'options',
path: "/api/articles",
handler: "render",
auth_required: false,
},
];
cb(null, routes);
};
//exports
return CorsApiController;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment