From 36a30315f16baeafde605c748f6e2c74063ffa65 Mon Sep 17 00:00:00 2001 From: hoyce mac work Date: Wed, 31 Aug 2016 16:21:08 +0200 Subject: [PATCH] Initial commit --- .gitignore | 7 +++ LICENSE | 8 ++++ README.md | 52 ++++++++++++++++++++- index.js | 125 +++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 29 ++++++++++++ 5 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 index.js create mode 100644 package.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ae67895 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# Idea specific files. +.idea +*.iml + +# Packages +node_modules + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..670855c --- /dev/null +++ b/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2016 KTH Royal Institute of Technology + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index f679aed..fd7b62f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,52 @@ # kth-node-api-key-strategy -A api key strategy for Node.js applications. +A api key strategy for Node applications. + +## Configure + +#### localSettings.js +``` +module.exports = { + secure: { + api_keys: [ + {name: 'devClient', apikey: '1234', scope: ['write', 'read']}, + {name: 'testClient', apikey: '123456', scope: ['read']} + ], + } +}; +``` +#### swagger.js + +**Setting security on a route** +``` +"/v1/some/route/{id}": { + "get": { + "operationId": "", + "summary": "", + "description": "", + "parameters": [], + "tags": [ + "v1" + ], + "responses": { ... }, + "security": { + "api_key": [ + "read" + ] + } + } + } +``` +**Defining security definition** +``` +"securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header", + "scopes": { + "read": "Read access to data", + "write": "Write access to data" + } + } + } +``` \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..884e07b --- /dev/null +++ b/index.js @@ -0,0 +1,125 @@ +/** + * ApiKey Strategy. + * Configure the keys to use in localSettings.js within secure: {}. + * Configure: api_keys: [{name: 'NAME of client', apikey: 'THE API key', scope: ['Name of scope']} + * Sample: api_keys: [{name: 'pontus', apikey: 'AAAA', scope: ['write']}, {name: 'ove', apikey: 'BBBB', scope: ['read']}, {name: 'jon', apikey: '1234', scope: ['write', 'read']}], + * client "pontus" has a key with scope 'write', client "ove" has a key with scope 'read' and finally client "jon" has a key with scopes 'read' and 'write' + */ +var passport = require('passport') +var util = require('util') +var log = { debug: console.log, + info: console.log, + warn: console.log, + error: console.log } + +/** + * Creates an instance of `Strategy` checking api keys. + */ +function Strategy (options, verify) { + if (typeof options === 'function') { + verify = options + options = {} + } else { + if (options && options.log) { + log = options.log + } + } + if (!verify) { + throw new Error('apikey authentication strategy requires a verify function') + } + + passport.Strategy.call(this) + + this._apiKeyHeader = options.apiKeyHeader || 'api_key' + this.name = 'apikey' + this._verify = verify + this._passReqToCallback = true // options.passReqToCallback +} + +/** + * Inherit from `passport.Strategy`. + */ +util.inherits(Strategy, passport.Strategy) + +/** + * Authenticate request. + * + * @param req The request to authenticate. + * @param options Strategy-specific options. + */ +Strategy.prototype.authenticate = function (req, options) { + options = options || {} + var apikey = req.header(this._apiKeyHeader) + if (!apikey) { + apikey = req.query[ this._apiKeyHeader ] // swagger compatible + } + + if (!apikey) { + return this.fail(new BadRequestError('Missing API Key')) + } + + var self = this + /* + * Verifies the user login add set error, fail or success depending on the result. + */ + var verified = function (err, user, info) { + if (err) { + return self.error(err) + } + if (!user) { + return self.fail(info) + } + self.success(user, info) + } + + if (self._passReqToCallback) { + this._verify(req, apikey, verified) + } else { + this._verify(apikey, verified) + } +} + +/** + * `BadRequestError` error. + * @api public + */ +function BadRequestError (message) { + this.name = 'BadRequestError' + this.message = message || null + this.stack = (new Error()).stack +} + +// inherit from Error +BadRequestError.prototype = Object.create(Error.prototype) +BadRequestError.prototype.constructor = BadRequestError + +function verifyApiKey (req, apikey, configuredApiKeys, done) { + // var authenticated = false + var err, user + + for (var i = 0; i < configuredApiKeys.length; i++) { + var client = configuredApiKeys[ i ] + if (client.apikey === apikey) { + log.debug('Authenticate ' + client.name) + for (var s = 0; s < client.scope.length; s++) { + var assignedScope = client.scope[ s ] + if (req.scope.indexOf(assignedScope) >= 0) { + user = client.name + // authenticated = true + + return done(null, user) + } + } + } + } + + err = '401' + return done(err) +} + +/** + * Expose `Strategy`. + * And verify function. + */ +exports.Strategy = Strategy +exports.verifyApiKey = verifyApiKey diff --git a/package.json b/package.json new file mode 100644 index 0000000..6f928ae --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "kth-node-api-key-strategy", + "version": "1.0.0", + "description": "A api key strategy for Node projects.", + "main": "index.js", + "scripts": { + "codecheck": "standard", + "preversion": "npm run codecheck", + "postversion": "git push && git push --tags" + }, + "dependencies": { + "passport": "0.3.2", + "kth-node-log": "git@github.com:KTH/kth-node-log.git#v1.0.0" + }, + "repository": { + "type": "git", + "url": "git@github.com:KTH/kth-node-api-key-strategy.git" + }, + "keywords": [ + "api", + "key", + "strategy" + ], + "author": "", + "license": "MIT", + "devDependencies": { + "standard": "^7.0.0" + } +}