'use strict'; exports = module.exports = { add: add, get: get, del: del, getAllByUserId: getAllByUserId, validateTokenType: validateTokenType, // token client ids. we categorize them so we can have different restrictions based on the client ID_WEBADMIN: 'cid-webadmin', // dashboard oauth ID_SDK: 'cid-sdk', // created by user via dashboard ID_CLI: 'cid-cli' // created via cli tool }; let assert = require('assert'), BoxError = require('./boxerror.js'), hat = require('./hat.js'), uuid = require('uuid'), tokendb = require('./tokendb.js'); function validateTokenName(name) { assert.strictEqual(typeof name, 'string'); if (name.length > 64) return new BoxError(BoxError.BAD_FIELD, 'name too long', { field: 'name' }); return null; } function validateTokenType(type) { assert.strictEqual(typeof type, 'string'); const types = [ exports.ID_WEBADMIN, exports.ID_CLI, exports.ID_SDK ]; if (types.indexOf(type) === -1) return BoxError(BoxError.BAD_FIELD, `type must be one of ${types.join(',')}`); return null; } function add(clientId, userId, expiresAt, options, callback) { assert.strictEqual(typeof clientId, 'string'); assert.strictEqual(typeof userId, 'string'); assert.strictEqual(typeof expiresAt, 'number'); assert.strictEqual(typeof options, 'object'); assert.strictEqual(typeof callback, 'function'); const name = options.name || ''; let error = validateTokenName(name); if (error) return callback(error); const token = { id: 'tid-' + uuid.v4(), accessToken: hat(8 * 32), identifier: userId, clientId: clientId, expires: expiresAt, scope: 'unused', name: name }; tokendb.add(token, function (error) { if (error) return callback(error); callback(null, { accessToken: token.accessToken, tokenScopes: 'unused', identifier: userId, clientId: clientId, expires: expiresAt }); }); } function get(id, callback) { assert.strictEqual(typeof id, 'string'); assert.strictEqual(typeof callback, 'function'); tokendb.get(id, function (error, result) { if (error) return callback(error); callback(null, result); }); } function del(id, callback) { assert.strictEqual(typeof id, 'string'); assert.strictEqual(typeof callback, 'function'); tokendb.del(id, function (error, result) { if (error) return callback(error); callback(null, result); }); } function getAllByUserId(userId, callback) { assert.strictEqual(typeof userId, 'string'); assert.strictEqual(typeof callback, 'function'); tokendb.getByIdentifier(userId, function (error, result) { if (error) return callback(error); callback(null, result); }); }