74 lines
2.6 KiB
JavaScript
74 lines
2.6 KiB
JavaScript
'use strict';
|
|
|
|
exports = module.exports = {
|
|
verifyOwnership,
|
|
list,
|
|
get,
|
|
add,
|
|
del
|
|
};
|
|
|
|
const assert = require('assert'),
|
|
BoxError = require('../boxerror.js'),
|
|
HttpError = require('connect-lastmile').HttpError,
|
|
HttpSuccess = require('connect-lastmile').HttpSuccess,
|
|
safe = require('safetydance'),
|
|
tokens = require('../tokens.js');
|
|
|
|
async function verifyOwnership(req, res, next) {
|
|
assert.strictEqual(typeof req.user, 'object');
|
|
assert.strictEqual(typeof req.params.id, 'string');
|
|
|
|
const [error, result] = await safe(tokens.get(req.params.id));
|
|
if (error) return next(BoxError.toHttpError(error));
|
|
if (!result) return next(new HttpError(404, 'Token not found'));
|
|
if (result.identifier !== req.user.id) return next(new HttpError(403, 'User is not owner'));
|
|
|
|
req.targetToken = result;
|
|
|
|
next();
|
|
}
|
|
|
|
async function list(req, res, next) {
|
|
assert.strictEqual(typeof req.user, 'object');
|
|
|
|
const [error, result] = await safe(tokens.listByUserId(req.user.id));
|
|
if (error) return next(BoxError.toHttpError(error));
|
|
|
|
next(new HttpSuccess(200, { tokens: result }));
|
|
}
|
|
|
|
function get(req, res, next) {
|
|
assert.strictEqual(typeof req.user, 'object');
|
|
assert.strictEqual(typeof req.targetToken, 'object');
|
|
|
|
next(new HttpSuccess(200, req.targetToken));
|
|
}
|
|
|
|
async function add(req, res, next) {
|
|
assert.strictEqual(typeof req.user, 'object');
|
|
assert.strictEqual(typeof req.body, 'object');
|
|
|
|
if (typeof req.body.name !== 'string') return next(new HttpError(400, 'name must be string'));
|
|
if ('expiresAt' in req.body && typeof req.body.expiresAt !== 'number') return next(new HttpError(400, 'expiresAt must be number'));
|
|
if ('scope' in req.body && typeof req.body.scope !== 'object') return next(new HttpError(400, 'scope must be an object'));
|
|
|
|
const expiresAt = req.body.expiresAt || (Date.now() + (100 * 365 * 24 * 60 * 60 * 1000)); // forever - 100 years TODO maybe we should allow 0 or -1 to make that explicit
|
|
const scope = req.body.scope || null;
|
|
|
|
const [error, result] = await safe(tokens.add({ clientId: tokens.ID_SDK, identifier: req.user.id, expires: expiresAt, name: req.body.name, scope }));
|
|
if (error) return next(BoxError.toHttpError(error));
|
|
|
|
next(new HttpSuccess(201, result));
|
|
}
|
|
|
|
async function del(req, res, next) {
|
|
assert.strictEqual(typeof req.user, 'object');
|
|
assert.strictEqual(typeof req.targetToken, 'object');
|
|
|
|
const [error] = await safe(tokens.del(req.targetToken.id));
|
|
if (error) return next(BoxError.toHttpError(error));
|
|
|
|
next(new HttpSuccess(204, {}));
|
|
}
|