Skip to content

Commit

Permalink
connect an access token from the query string to a authorized token f…
Browse files Browse the repository at this point in the history
…or the careportal
  • Loading branch information
jasoncalabrese committed Aug 1, 2016
1 parent 3d88bd3 commit f50e36d
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 27 deletions.
1 change: 1 addition & 0 deletions env.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ function setMongo() {
console.info('MQTT configured to use a custom client id, it will override the default: ', env.mqtt_client_id);
}
}
env.authentication_collections_prefix = readENV('MONGO_AUTHENTICATION_COLLECTIONS_PREFIX', 'auth_');
env.treatments_collection = readENV('MONGO_TREATMENTS_COLLECTION', 'treatments');
env.profile_collection = readENV('MONGO_PROFILE_COLLECTION', 'profile');
env.devicestatus_collection = readENV('MONGO_DEVICESTATUS_COLLECTION', 'devicestatus');
Expand Down
2 changes: 1 addition & 1 deletion lib/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function create (env, ctx) {
app.use('/', require('./verifyauth')(app, env));
app.use('/', require('./food/')(app, wares, ctx));
// Status
app.use('/', require('./status')(app, wares, env));
app.use('/', require('./status')(app, wares, env, ctx));
return app;
}

Expand Down
16 changes: 11 additions & 5 deletions lib/api/status.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

function configure (app, wares, env) {
function configure (app, wares, env, ctx) {
var express = require('express'),
api = express.Router( )
;
Expand All @@ -23,6 +23,7 @@ function configure (app, wares, env) {
, settings: env.settings
, extendedSettings: app.extendedClientSettings
};

var badge = 'http://img.shields.io/badge/Nightscout-OK-green';
return res.format({
html: function ( ) {
Expand All @@ -35,10 +36,15 @@ function configure (app, wares, env) {
res.redirect(302, badge + '.svg');
},
js: function ( ) {
var head = 'this.serverSettings =';
var body = JSON.stringify(info);
var tail = ';';
res.send([head, body, tail].join(' '));
var parts = ['this.serverSettings =', JSON.stringify(info), ';'];
if (req.query && req.query.token) {
var authorized = ctx.authorization.authorize(req.query.token);
if (authorized) {
parts = parts.concat(['this.authorized =', JSON.stringify(authorized), ';']);
}
}

res.send(parts.join(' '));
},
text: function ( ) {
res.send('STATUS OK');
Expand Down
40 changes: 26 additions & 14 deletions lib/authorization.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,33 +129,44 @@ function create (env, ctx) {
return check;
}

endpoints.get('/keys', isPermitted('authorization:keys:list'), function getTokens (req, res) {
res.json(_.map(keys, function eachKey (key) {
return _.pick(key, ['_id', 'sub', 'accessToken', 'roles']);
}));
});

endpoints.get('/roles', isPermitted('authorization:roles:list'), function getRoles (req, res) {
res.json(roles);
});

endpoints.get('/request/:accessToken', function authorize (req, res) {
var accessToken = req.params.accessToken;
function authorize (accessToken) {
var key = _.find(keys, {accessToken: accessToken});

var authorized = null;

if (key) {
var token = jwt.sign( { accessToken: key.accessToken }, env.api_secret, { expiresIn: '1h' } );

//decode so we can tell the client the issued and expired times
var decoded = jwt.decode(token);

res.json({
authorized = {
token: token
, sub: key.sub
, permissions: rolesToPermissions(key.roles)
, iat: decoded.iat
, exp: decoded.exp
});
};
}

return authorized;
}

endpoints.get('/keys', isPermitted('authorization:keys:list'), function getTokens (req, res) {
res.json(_.map(keys, function eachKey (key) {
return _.pick(key, ['_id', 'sub', 'accessToken', 'roles']);
}));
});

endpoints.get('/roles', isPermitted('authorization:roles:list'), function getRoles (req, res) {
res.json(roles);
});

endpoints.get('/request/:accessToken', function requestAuthorize (req, res) {
var authorized = authorize(req.params.accessToken);

if (authorized) {
res.json(authorized);
} else {
res.sendJSONStatus(res, consts.HTTP_UNAUTHORIZED, 'Unauthorized', 'Invalid/Missing');
}
Expand All @@ -169,6 +180,7 @@ function create (env, ctx) {

return {
isPermitted: isPermitted
, authorize: authorize
, endpoints: endpoints
};
}
Expand Down
20 changes: 16 additions & 4 deletions lib/client/careportal.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ function init (client, plugins, $) {
$('#profile').val(client.profilefunctions.activeProfileToTime());
$('#preBolus').val(0);
$('#notes').val('');
$('#enteredBy').val(storage.get('enteredBy') || '');
$('#enteredBy').val(client.authorized ? client.authorized.sub : storage.get('enteredBy') || '');
$('#nowtime').prop('checked', true);
setDateAndTime();
};
Expand Down Expand Up @@ -294,12 +294,24 @@ function init (client, plugins, $) {
data.relative = data.enteredinsulin * data.splitExt / 100 / data.duration * 60;
}

console.info('>>>client.authorized', client.authorized);

var headers;

if (client.authorized) {
headers = {
Authorization: 'Bearer ' + client.authorized.token
};
} else {
headers = {
'api-secret': client.hashauth.hash()
};
}

$.ajax({
method: 'POST'
, url: '/api/v1/treatments/'
, headers: {
'api-secret': client.hashauth.hash()
}
, headers: headers
, data: data
}).done(function treatmentSaved (response) {
console.info('treatment saved', response);
Expand Down
3 changes: 2 additions & 1 deletion lib/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var receiveDData = require('./receiveddata');

var client = { };

client.init = function init(serverSettings, plugins) {
client.init = function init(serverSettings, plugins, authorized) {

var UPDATE_TRANS_MS = 750 // milliseconds
, FORMAT_TIME_12 = '%-I:%M %p'
Expand Down Expand Up @@ -45,6 +45,7 @@ client.init = function init(serverSettings, plugins) {

client.now = Date.now();
client.ddata = require('../data/ddata')();
client.authorized = authorized;
client.forecastTime = times.mins(30).msecs;
client.entries = [];
client.browserUtils = require('./browser-utils')($);
Expand Down
2 changes: 1 addition & 1 deletion static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@
<audio src="/audio/alarm2.mp3" preload="auto" loop="true" class="urgent alarm2 mp3" type="audio/mp3"></audio>
</div>

<script src="/api/v1/status.js?v=0.9.0-beta3"></script>
<script src="/js/init.js"></script>
<script src="/public/js/bundle.js?v=0.9.0-beta3"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/bower_components/jQuery-Storage-API/jquery.storageapi.min.js"></script>
Expand Down
2 changes: 1 addition & 1 deletion static/js/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
if (serverSettings === undefined) {
console.error('server settings were not loaded, will not call init');
} else {
window.Nightscout.client.init(serverSettings, Nightscout.plugins);
window.Nightscout.client.init(serverSettings, Nightscout.plugins, authorized);
}
18 changes: 18 additions & 0 deletions static/js/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

var params = {};
if (window.location.search) {
window.location.search.substr(1).split('&').forEach(function(item) {
params[item.split('=')[0]] = item.split('=')[1].replace(/[_\+]/g, ' ');
});
}

var token = params.token;

var script = window.document.createElement('script');
var src = '/api/v1/status.js?t=' + new Date().getTime();
if (token) {
src += '&token=' + token;
}
script.setAttribute('src', src);
window.document.body.appendChild(script);

0 comments on commit f50e36d

Please sign in to comment.