Skip to content

Commit

Permalink
Add support for HTTP method.
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Perez committed Jun 13, 2015
1 parent 14cc5cf commit ddd3b27
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 5 deletions.
6 changes: 3 additions & 3 deletions lib/policy-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,18 @@ function PolicyManager(policies, defaultStrategies) {
}

_.extend(PolicyManager.prototype, {
policiesFor: function (path) {
policiesFor: function (path, method) {
let policies = [];
for (let policy of this._policies) {
if (policy.appliesTo(path)) {
if (policy.appliesTo(path, method)) {
policies.push(policy);
}
}
return policies;
},

applyPolicies: function *(context) {
let policies = this.policiesFor(context.path);
let policies = this.policiesFor(context.path, context.method);
let entities = {};
for (let policy of policies) {
if (entities[policy.scope]) {
Expand Down
7 changes: 6 additions & 1 deletion lib/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ function Policy(policy) {

_.extend(Policy.prototype, {
_assertValid: function () {
assert(_.isUndefined(this.methods) || _.isArray(this.methods),
'policy methods must be an array');
assert(_.isString(this.path) || _.isRegExp(this.path),
'policy path must be a string or a regex');
assert(_.isUndefined(this.scope) || _.isString(this.scope),
Expand All @@ -28,7 +30,10 @@ _.extend(Policy.prototype, {
return 'Path: ' + this.path + ', scope: ' + this.scope + ', enforce: ' + this.enforce;
},

appliesTo: function (path) {
appliesTo: function (path, method) {
if (this.methods && this.methods.indexOf(method.toUpperCase()) == -1) {
return false;
}
let m = path.match(this.path);
return !!m && m.index === 0 && m[0] === path;
},
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "koa-police",
"version": "0.1.1",
"version": "0.2.0",
"description": "Authentication framework for Koa",
"main": "lib/index.js",
"scripts": {
Expand Down
6 changes: 6 additions & 0 deletions test/unit/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ describe('Policy', function () {
expect(policy.appliesTo('/foo/dashboard')).to.be.false;
expect(policy.appliesTo('/dashboard')).to.be.false;
});

it('should respect method', function () {
let policy = new Policy({path: '/path', methods: ['GET']});
expect(policy.appliesTo('/path', 'GET')).to.be.true;
expect(policy.appliesTo('/path', 'POST')).to.be.false;
});
});

describe('toString', function () {
Expand Down

0 comments on commit ddd3b27

Please sign in to comment.