75 lines
2.3 KiB
JavaScript
75 lines
2.3 KiB
JavaScript
'use strict';
|
|
|
|
exports = module.exports = {
|
|
verifyOwnership: verifyOwnership,
|
|
getAll: getAll,
|
|
get: get,
|
|
add: add,
|
|
del: del
|
|
};
|
|
|
|
var assert = require('assert'),
|
|
BoxError = require('../boxerror.js'),
|
|
HttpError = require('connect-lastmile').HttpError,
|
|
HttpSuccess = require('connect-lastmile').HttpSuccess,
|
|
tokens = require('../tokens.js');
|
|
|
|
function verifyOwnership(req, res, next) {
|
|
assert.strictEqual(typeof req.user, 'object');
|
|
assert.strictEqual(typeof req.params.id, 'string');
|
|
|
|
tokens.get(req.params.id, function (error, result) {
|
|
if (error) return next(BoxError.toHttpError(error));
|
|
|
|
if (result.identifier !== req.user.id) return next(new HttpError(403, 'User is not owner'));
|
|
|
|
req.token = result;
|
|
|
|
next();
|
|
});
|
|
}
|
|
|
|
function getAll(req, res, next) {
|
|
assert.strictEqual(typeof req.user, 'object');
|
|
|
|
tokens.getAllByUserId(req.user.id, function (error, result) {
|
|
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.token, 'object');
|
|
|
|
next(new HttpSuccess(200, { token: req.token }));
|
|
}
|
|
|
|
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'));
|
|
|
|
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
|
|
|
|
tokens.add(tokens.ID_SDK, req.user.id, expiresAt, { name: req.body.name }, function (error, result) {
|
|
if (error) return next(BoxError.toHttpError(error));
|
|
|
|
next(new HttpSuccess(201, { token: result }));
|
|
});
|
|
}
|
|
|
|
function del(req, res, next) {
|
|
assert.strictEqual(typeof req.user, 'object');
|
|
assert.strictEqual(typeof req.token, 'object');
|
|
|
|
tokens.del(req.token.id, function (error) {
|
|
if (error) return next(BoxError.toHttpError(error));
|
|
|
|
next(new HttpSuccess(204, {}));
|
|
});
|
|
}
|