message: Simplify token endpoint
diff: @@ -6,18 +6,28 @@ import { EventType } from '../../log/types';
  import { InvalidRequest, serializeError, UnsupportedGrantType } from '../errors';
  import parseBasicAuth from '../parse-basic-auth';
  import * as oauth2Service from '../service';
  -import { OAuth2Token } from '../types';
  class TokenController extends BaseController {
  - async post(ctx: Context) {
  + post(ctx: Context) {
  const supportedGrantTypes = ['client_credentials', 'authorization_code'];
  - let oauth2Client;
  - if (!supportedGrantTypes.includes(ctx.request.body.grant_type)) {
  + switch(ctx.request.body.grant_type) {
  + case 'client_credentials' :
  + return this.clientCredentials(ctx);
  + case 'authorization_code' :
  + return this.authorizationCode(ctx);
  + default :
  throw new UnsupportedGrantType('The "grant_type" must be one of ' + supportedGrantTypes.join(', '));
  }
  +
  + }
  +
  + async clientCredentials(ctx: Context) {
  +
  + let oauth2Client;
  +
  const basicAuth = parseBasicAuth(ctx);
  if (!basicAuth) {
  throw new Unauthorized('Basic Auth is missing or malformed', 'Basic');
  @@ -36,14 +46,39 @@ class TokenController extends BaseController {
  throw new Unauthorized('Client id or secret incorrect', 'Basic');
  }
  - let token: OAuth2Token;
  + const token = await oauth2Service.generateTokenForClient(oauth2Client);
  - switch (ctx.request.body.grant_type) {
  + ctx.response.type = 'application/json';
  + ctx.response.body = {
  + access_token: token.accessToken,
  + token_type: token.tokenType,
  + expires_in: token.accessTokenExpires - Math.round(Date.now() / 1000),
  + };
  +
  + }
  +
  + async authorizationCode(ctx: Context) {
  +
  + let oauth2Client;
  +
  + const basicAuth = parseBasicAuth(ctx);
  + if (!basicAuth) {
  + throw new Unauthorized('Basic Auth is missing or malformed', 'Basic');
  + }
  + try {
  + oauth2Client = await oauth2Service.getClientByClientId(basicAuth[0]);
  + } catch (e) {
  + if (e instanceof NotFound) {
  + throw new Unauthorized('Client id or secret incorrect', 'Basic');
  + } else {
  + // Rethrow
  + throw e;
  + }
  + }
  + if (!await oauth2Service.validateSecret(oauth2Client, basicAuth[1])) {
  + throw new Unauthorized('Client id or secret incorrect', 'Basic');
  + }
  - case 'client_credentials' :
  - token = await oauth2Service.generateTokenForClient(oauth2Client);
  - break;
  - case 'authorization_code' :
  if (!ctx.request.body.code) {
  throw new InvalidRequest('The "code" property is required');
  }
  @@ -54,10 +89,7 @@ class TokenController extends BaseController {
  log(EventType.oauth2BadRedirect, ctx);
  throw new InvalidRequest('This value for "redirect_uri" is not recognized.');
  }
  - token = await oauth2Service.generateTokenFromCode(oauth2Client, ctx.request.body.code);
  - break;
  -
  - }
  + const token = await oauth2Service.generateTokenFromCode(oauth2Client, ctx.request.body.code);
  ctx.response.type = 'application/json';
  ctx.response.body = {
  