From 28172607c6ef2d3459e6222617ffeb6580162ffd Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Tue, 17 Oct 2017 15:22:34 +0200 Subject: [PATCH] feat(token.create): expiresIn param (#611) Fixes vatesfr/xo-web#1769 --- src/api/token.js | 15 ++++++++++++--- src/xo-mixins/authentication.js | 12 ++++++++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/api/token.js b/src/api/token.js index 40df4be70..9ac647318 100644 --- a/src/api/token.js +++ b/src/api/token.js @@ -1,12 +1,21 @@ // TODO: Prevent token connections from creating tokens. // TODO: Token permission. -export async function create () { - const userId = this.session.get('user_id') - return (await this.createAuthenticationToken({userId})).id +export async function create ({ expiresIn }) { + return (await this.createAuthenticationToken({ + expiresIn, + userId: this.session.get('user_id') + })).id } create.description = 'create a new authentication token' +create.params = { + expiresIn: { + optional: true, + type: [ 'number', 'string' ] + } +} + create.permission = '' // sign in // ------------------------------------------------------------------- diff --git a/src/xo-mixins/authentication.js b/src/xo-mixins/authentication.js index 7ad4614ae..66277b718 100644 --- a/src/xo-mixins/authentication.js +++ b/src/xo-mixins/authentication.js @@ -1,3 +1,4 @@ +import ms from 'ms' import { noSuchObject } from 'xo-common/api-errors' import { ignoreErrors } from 'promise-toolbox' @@ -151,11 +152,18 @@ export default class { // ----------------------------------------------------------------- - async createAuthenticationToken ({userId}) { + async createAuthenticationToken ({ + expiresIn = ONE_MONTH, + userId + }) { const token = new Token({ id: await generateToken(), user_id: userId, - expiration: Date.now() + ONE_MONTH + expiration: Date.now() + ( + typeof expiresIn === 'string' + ? ms(expiresIn) + : expiresIn + ) }) await this._tokens.add(token)