2020-02-07 16:20:05 +01:00
'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' ) ;
2020-02-07 16:42:15 +01:00
next ( new HttpSuccess ( 200 , { token : req . token } ) ) ;
2020-02-07 16:20:05 +01:00
}
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' ) ) ;
2020-02-07 16:42:15 +01:00
if ( 'expiresAt' in req . body && typeof req . body . expiresAt !== 'number' ) return next ( new HttpError ( 400 , 'expiresAt must be number' ) ) ;
2020-02-07 16:20:05 +01:00
2020-02-07 16:42:15 +01:00
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
2020-02-07 16:20:05 +01:00
2020-02-07 16:42:15 +01:00
tokens . add ( tokens . ID _SDK , req . user . id , expiresAt , { name : req . body . name } , function ( error , result ) {
2020-02-07 16:20:05 +01:00
if ( error ) return next ( BoxError . toHttpError ( error ) ) ;
2020-02-07 16:42:15 +01:00
next ( new HttpSuccess ( 201 , { token : result } ) ) ;
2020-02-07 16:20:05 +01:00
} ) ;
}
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 , { } ) ) ;
} ) ;
}