Merged PR 611: 操作を特定できる文字列を追跡用のIDに追加する(IPアドレスもログに出力する)

## 概要
[Task3265: IPアドレスを追跡用のIDに追加する](https://paruru.nds-tyo.co.jp:8443/tfs/ReciproCollection/fa4924a4-d079-4fab-9fb5-a9a11eb205f0/_workitems/edit/3265)

- MiddlewareでUUIDを発行しリクエストのヘッダに追加する
- 各コントローラーではヘッダからUUIDとIPアドレスを取得する
  - 取得したUUIDとADB2Cの外部IDでトラッキングIDを作成する
  - 作成したトラッキングIDとIPアドレスの繋がりをログに出力する。

## レビューポイント
- ADB2Cの外部IDがない場合にUnauthorized Userという文字列を入れているがほかの表現のほうが良いか
  - 外部IDもオプショナルにして入れなくてもよくする?
-

## UIの変更
- Before/Afterのスクショなど
- スクショ置き場

## 動作確認状況
- ローカルで確認

## 補足
- 相談、参考資料などがあれば
This commit is contained in:
saito.k 2023-12-12 04:11:36 +00:00
parent 8fe649cb7f
commit f1583cf783
28 changed files with 2372 additions and 504 deletions

View File

@ -23,6 +23,8 @@ export const ErrorCodes = [
'E000107', // トークン不足エラー 'E000107', // トークン不足エラー
'E000108', // トークン権限エラー 'E000108', // トークン権限エラー
'E000301', // ADB2Cへのリクエスト上限超過エラー 'E000301', // ADB2Cへのリクエスト上限超過エラー
'E000401', // IPアドレス未設定エラー
'E000501', // リクエストID未設定エラー
'E010001', // パラメータ形式不正エラー 'E010001', // パラメータ形式不正エラー
'E010201', // 未認証ユーザエラー 'E010201', // 未認証ユーザエラー
'E010202', // 認証済ユーザエラー 'E010202', // 認証済ユーザエラー

View File

@ -12,6 +12,8 @@ export const errors: Errors = {
E000107: 'Token is not exist Error.', E000107: 'Token is not exist Error.',
E000108: 'Token authority failed Error.', E000108: 'Token authority failed Error.',
E000301: 'ADB2C request limit exceeded Error', E000301: 'ADB2C request limit exceeded Error',
E000401: 'IP address not found Error.',
E000501: 'Request ID not found Error.',
E010001: 'Param invalid format Error.', E010001: 'Param invalid format Error.',
E010201: 'Email not verified user Error.', E010201: 'Email not verified user Error.',
E010202: 'Email already verified user Error.', E010202: 'Email already verified user Error.',

View File

@ -1,8 +1,32 @@
import { Request } from 'express';
import { Context } from './types'; import { Context } from './types';
export const makeContext = ( export const makeContext = (
externalId: string, externalId: string,
requestId: string,
delegationId?: string, delegationId?: string,
): Context => { ): Context => {
return new Context(externalId, delegationId); return new Context(externalId, requestId, delegationId);
};
// リクエストヘッダーからrequestIdを取得する
export const retrieveRequestId = (req: Request): string | undefined => {
return req.header('x-request-id');
};
/**
* IPアドレスを取得します
* @param {Request}
* @return {string | undefined}
*/
export const retrieveIp = (req: Request): string | undefined => {
// ローカル環境では直近の送信元IPを取得する
if (process.env.STAGE === 'local') {
return req.ip;
}
const ip = req.header('x-forwarded-for');
if (typeof ip === 'string') {
return ip;
}
return undefined;
}; };

View File

@ -1,4 +1,4 @@
import { Context } from './types'; import { Context } from './types';
import { makeContext } from './context'; import { makeContext, retrieveRequestId, retrieveIp } from './context';
export { Context, makeContext }; export { Context, makeContext, retrieveRequestId, retrieveIp };

View File

@ -3,23 +3,32 @@ export class Context {
* APIの操作ユーザーを追跡するためのID * APIの操作ユーザーを追跡するためのID
*/ */
trackingId: string; trackingId: string;
/**
* APIの操作ユーザーのIPアドレス
*/
ip: string;
/**
* ID
*/
requestId: string;
/** /**
* APIの代行操作ユーザーを追跡するためのID * APIの代行操作ユーザーを追跡するためのID
*/ */
delegationId?: string | undefined; delegationId?: string | undefined;
constructor(externalId: string, delegationId?: string) { constructor(externalId: string, requestId: string, delegationId?: string) {
this.trackingId = externalId; this.trackingId = externalId;
this.delegationId = delegationId; this.delegationId = delegationId;
this.requestId = requestId;
} }
/** /**
* *
*/ */
getTrackingId(): string { getTrackingId(): string {
if (this.delegationId) { if (this.delegationId) {
return `${this.trackingId} by ${this.delegationId}`; return `${this.requestId}_${this.trackingId} by ${this.delegationId}`;
} else { } else {
return this.trackingId; return `${this.requestId}_${this.trackingId}`;
} }
} }
} }

View File

@ -1,11 +1,16 @@
import { Injectable, Logger, NestMiddleware } from '@nestjs/common'; import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import { v4 as uuidv4 } from 'uuid';
@Injectable() @Injectable()
export class LoggerMiddleware implements NestMiddleware { export class LoggerMiddleware implements NestMiddleware {
private readonly logger = new Logger(LoggerMiddleware.name); private readonly logger = new Logger(LoggerMiddleware.name);
use(req: Request, res: Response, next: () => void): void { use(req: Request, res: Response, next: () => void): void {
// ここで一意のリクエストIDを生成して、リクエストヘッダーに設定する
const requestId = uuidv4();
req.headers['x-request-id'] = requestId;
this.logger.log(this.createReqMsg(req)); this.logger.log(this.createReqMsg(req));
res.on('close', () => { res.on('close', () => {
@ -15,13 +20,17 @@ export class LoggerMiddleware implements NestMiddleware {
} }
private createReqMsg(req: Request): string { private createReqMsg(req: Request): string {
const message = `Request [url=${req.url}, method=${req.method}]`; const message = `[${req.header('x-request-id')}] Request [url=${
req.url
}, method=${req.method}]`;
return message; return message;
} }
private createResMsg(res: Response): string { private createResMsg(res: Response): string {
const message = `Response [statusCode=${res.statusCode}, message=${res.statusMessage}]`; const message = `[${res.req.header('x-request-id')}] Response [statusCode=${
res.statusCode
}, message=${res.statusMessage}]`;
return message; return message;
} }

View File

@ -9,6 +9,7 @@ import {
Param, Param,
Query, Query,
HttpException, HttpException,
Logger,
} from '@nestjs/common'; } from '@nestjs/common';
import { import {
ApiOperation, ApiOperation,
@ -77,14 +78,14 @@ import { RoleGuard } from '../../common/guards/role/roleguards';
import { retrieveAuthorizationToken } from '../../common/http/helper'; import { retrieveAuthorizationToken } from '../../common/http/helper';
import { AccessToken } from '../../common/token'; import { AccessToken } from '../../common/token';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { AuthService } from '../auth/auth.service'; import { AuthService } from '../auth/auth.service';
import { makeErrorResponse } from '../../common/error/makeErrorResponse'; import { makeErrorResponse } from '../../common/error/makeErrorResponse';
import { v4 as uuidv4 } from 'uuid';
@ApiTags('accounts') @ApiTags('accounts')
@Controller('accounts') @Controller('accounts')
export class AccountsController { export class AccountsController {
private readonly logger = new Logger(AccountsController.name);
constructor( constructor(
private readonly accountService: AccountsService, //private readonly cryptoService: CryptoService, private readonly accountService: AccountsService, //private readonly cryptoService: CryptoService,
private readonly authService: AuthService, private readonly authService: AuthService,
@ -109,6 +110,7 @@ export class AccountsController {
@ApiOperation({ operationId: 'createAccount' }) @ApiOperation({ operationId: 'createAccount' })
async createAccount( async createAccount(
@Body() body: CreateAccountRequest, @Body() body: CreateAccountRequest,
@Req() req: Request,
): Promise<CreateAccountResponse> { ): Promise<CreateAccountResponse> {
const { const {
companyName, companyName,
@ -123,7 +125,24 @@ export class AccountsController {
} = body; } = body;
const role = USER_ROLES.NONE; const role = USER_ROLES.NONE;
const context = makeContext(uuidv4()); const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.createAccount( await this.accountService.createAccount(
context, context,
@ -178,6 +197,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -186,7 +221,9 @@ export class AccountsController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const response = await this.accountService.getLicenseSummary( const response = await this.accountService.getLicenseSummary(
context, context,
body.accountId, body.accountId,
@ -232,6 +269,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -240,7 +293,9 @@ export class AccountsController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
//アカウントID取得処理 //アカウントID取得処理
const accountInfo = await this.accountService.getAccountInfo( const accountInfo = await this.accountService.getAccountInfo(
context, context,
@ -283,6 +338,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -291,7 +362,9 @@ export class AccountsController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const authors = await this.accountService.getAuthors(context, userId); const authors = await this.accountService.getAuthors(context, userId);
@ -330,6 +403,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -338,7 +427,9 @@ export class AccountsController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const typists = await this.accountService.getTypists(context, userId); const typists = await this.accountService.getTypists(context, userId);
@ -377,6 +468,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -385,7 +492,9 @@ export class AccountsController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const typistGroups = await this.accountService.getTypistGroups( const typistGroups = await this.accountService.getTypistGroups(
context, context,
@ -441,6 +550,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -450,7 +575,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const typistGroup = await this.accountService.getTypistGroup( const typistGroup = await this.accountService.getTypistGroup(
context, context,
@ -506,6 +632,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -514,7 +656,9 @@ export class AccountsController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.createTypistGroup( await this.accountService.createTypistGroup(
context, context,
userId, userId,
@ -572,6 +716,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -581,7 +741,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.updateTypistGroup( await this.accountService.updateTypistGroup(
context, context,
@ -637,6 +798,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -646,7 +823,8 @@ export class AccountsController {
} }
const { userId, tier } = decodedAccessToken as AccessToken; const { userId, tier } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.createPartnerAccount( await this.accountService.createPartnerAccount(
context, context,
@ -699,6 +877,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -708,7 +902,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const getPartnerLicensesResponse = const getPartnerLicensesResponse =
await this.accountService.getPartnerLicenses( await this.accountService.getPartnerLicenses(
@ -759,6 +954,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -768,7 +979,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const getOrderHistoriesResponse = const getOrderHistoriesResponse =
await this.accountService.getOrderHistories( await this.accountService.getOrderHistories(
@ -825,6 +1037,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -834,7 +1062,8 @@ export class AccountsController {
} }
const { userId, tier } = decodedAccessToken as AccessToken; const { userId, tier } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.issueLicense( await this.accountService.issueLicense(
context, context,
orderedAccountId, orderedAccountId,
@ -857,8 +1086,25 @@ export class AccountsController {
type: ErrorResponse, type: ErrorResponse,
}) })
@ApiOperation({ operationId: 'getDealers' }) @ApiOperation({ operationId: 'getDealers' })
async getDealers(): Promise<GetDealersResponse> { async getDealers(@Req() req: Request): Promise<GetDealersResponse> {
const context = makeContext(uuidv4()); const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
return await this.accountService.getDealers(context); return await this.accountService.getDealers(context);
} }
@ -907,6 +1153,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -916,7 +1178,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.cancelIssue( await this.accountService.cancelIssue(
context, context,
@ -957,6 +1220,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -966,7 +1245,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const worktypes = await this.accountService.getWorktypes(context, userId); const worktypes = await this.accountService.getWorktypes(context, userId);
return worktypes; return worktypes;
@ -1012,6 +1292,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1021,7 +1317,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.createWorktype( await this.accountService.createWorktype(
context, context,
userId, userId,
@ -1074,6 +1371,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1083,7 +1396,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.updateWorktype( await this.accountService.updateWorktype(
context, context,
@ -1136,6 +1450,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1145,7 +1475,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.deleteWorktype(context, userId, id); await this.accountService.deleteWorktype(context, userId, id);
return {}; return {};
@ -1191,6 +1522,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1200,7 +1547,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const optionItems = await this.accountService.getOptionItems( const optionItems = await this.accountService.getOptionItems(
context, context,
@ -1253,6 +1601,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1262,7 +1626,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.updateOptionItems( await this.accountService.updateOptionItems(
context, context,
@ -1314,6 +1679,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1323,7 +1704,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.updateActiveWorktype(context, userId, id); await this.accountService.updateActiveWorktype(context, userId, id);
return {}; return {};
@ -1372,6 +1754,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1381,7 +1779,8 @@ export class AccountsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const response = await this.accountService.getPartners( const response = await this.accountService.getPartners(
context, context,
userId, userId,
@ -1439,6 +1838,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1447,7 +1862,9 @@ export class AccountsController {
); );
} }
const { userId, tier } = decodedAccessToken as AccessToken; const { userId, tier } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.updateAccountInfo( await this.accountService.updateAccountInfo(
context, context,
@ -1499,6 +1916,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1507,7 +1940,9 @@ export class AccountsController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.accountService.deleteAccountAndData(context, userId, accountId); await this.accountService.deleteAccountAndData(context, userId, accountId);
return {}; return {};
@ -1532,8 +1967,25 @@ export class AccountsController {
@ApiOperation({ operationId: 'getAccountInfoMinimalAccess' }) @ApiOperation({ operationId: 'getAccountInfoMinimalAccess' })
async getAccountInfoMinimalAccess( async getAccountInfoMinimalAccess(
@Body() body: GetAccountInfoMinimalAccessRequest, @Body() body: GetAccountInfoMinimalAccessRequest,
@Req() req: Request,
): Promise<GetAccountInfoMinimalAccessResponse> { ): Promise<GetAccountInfoMinimalAccessResponse> {
const context = makeContext(uuidv4()); const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
// IDトークンの検証 // IDトークンの検証
const idToken = await this.authService.getVerifiedIdToken( const idToken = await this.authService.getVerifiedIdToken(
@ -1591,6 +2043,22 @@ export class AccountsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -1599,7 +2067,9 @@ export class AccountsController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const companyName = await this.accountService.getCompanyName( const companyName = await this.accountService.getCompanyName(
context, context,
body.accountId, body.accountId,

View File

@ -607,11 +607,7 @@ export class AccountsService {
const externalIds = typistUsers.map((x) => x.external_id); const externalIds = typistUsers.map((x) => x.external_id);
// B2Cからユーザー名を取得する // B2Cからユーザー名を取得する
const trackingId = new Context(context.trackingId); const adb2cUsers = await this.adB2cService.getUsers(context, externalIds);
const adb2cUsers = await this.adB2cService.getUsers(
trackingId,
externalIds,
);
const typists = typistUsers.map((x) => { const typists = typistUsers.map((x) => {
const user = adb2cUsers.find((adb2c) => adb2c.id === x.external_id); const user = adb2cUsers.find((adb2c) => adb2c.id === x.external_id);

View File

@ -3,6 +3,7 @@ import {
Controller, Controller,
HttpException, HttpException,
HttpStatus, HttpStatus,
Logger,
Post, Post,
Req, Req,
UseGuards, UseGuards,
@ -25,8 +26,7 @@ import {
DelegationAccessTokenResponse, DelegationAccessTokenResponse,
} from './types/types'; } from './types/types';
import { retrieveAuthorizationToken } from '../../common/http/helper'; import { retrieveAuthorizationToken } from '../../common/http/helper';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { v4 as uuidv4 } from 'uuid';
import { Request } from 'express'; import { Request } from 'express';
import { AuthGuard } from '../../common/guards/auth/authguards'; import { AuthGuard } from '../../common/guards/auth/authguards';
import { RoleGuard } from '../../common/guards/role/roleguards'; import { RoleGuard } from '../../common/guards/role/roleguards';
@ -39,6 +39,7 @@ import { RedisService } from '../../gateways/redis/redis.service';
@ApiTags('auth') @ApiTags('auth')
@Controller('auth') @Controller('auth')
export class AuthController { export class AuthController {
private readonly logger = new Logger(AuthController.name);
constructor( constructor(
private readonly authService: AuthService, private readonly authService: AuthService,
private readonly redisService: RedisService, private readonly redisService: RedisService,
@ -65,8 +66,29 @@ export class AuthController {
'AzureADB2Cでのサインイン後に払いだされるIDトークンを元に認証用のアクセストークンとリフレッシュトークンを生成します', 'AzureADB2Cでのサインイン後に払いだされるIDトークンを元に認証用のアクセストークンとリフレッシュトークンを生成します',
operationId: 'token', operationId: 'token',
}) })
async token(@Body() body: TokenRequest): Promise<TokenResponse> { async token(
const context = makeContext(uuidv4()); @Body() body: TokenRequest,
@Req() req: Request,
): Promise<TokenResponse> {
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const idToken = await this.authService.getVerifiedIdToken( const idToken = await this.authService.getVerifiedIdToken(
context, context,
body.idToken, body.idToken,
@ -145,7 +167,6 @@ export class AuthController {
}) })
async accessToken(@Req() req: Request): Promise<AccessTokenResponse> { async accessToken(@Req() req: Request): Promise<AccessTokenResponse> {
const refreshToken = retrieveAuthorizationToken(req); const refreshToken = retrieveAuthorizationToken(req);
if (!refreshToken) { if (!refreshToken) {
throw new HttpException( throw new HttpException(
makeErrorResponse('E000107'), makeErrorResponse('E000107'),
@ -153,7 +174,24 @@ export class AuthController {
); );
} }
const context = makeContext(uuidv4()); const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const accessToken = await this.authService.generateAccessToken( const accessToken = await this.authService.generateAccessToken(
context, context,
@ -202,13 +240,29 @@ export class AuthController {
): Promise<DelegationTokenResponse> { ): Promise<DelegationTokenResponse> {
const { delegatedAccountId } = body; const { delegatedAccountId } = body;
const token = retrieveAuthorizationToken(req); const token = retrieveAuthorizationToken(req);
if (!token) { if (!token) {
throw new HttpException( throw new HttpException(
makeErrorResponse('E000107'), makeErrorResponse('E000107'),
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(token, { json: true }); const decodedAccessToken = jwt.decode(token, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -218,7 +272,9 @@ export class AuthController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const refreshToken = await this.authService.generateDelegationRefreshToken( const refreshToken = await this.authService.generateDelegationRefreshToken(
context, context,
userId, userId,
@ -257,13 +313,29 @@ export class AuthController {
@Req() req: Request, @Req() req: Request,
): Promise<DelegationAccessTokenResponse> { ): Promise<DelegationAccessTokenResponse> {
const refreshToken = retrieveAuthorizationToken(req); const refreshToken = retrieveAuthorizationToken(req);
if (!refreshToken) { if (!refreshToken) {
throw new HttpException( throw new HttpException(
makeErrorResponse('E000107'), makeErrorResponse('E000107'),
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedRefreshToken = jwt.decode(refreshToken, { json: true }); const decodedRefreshToken = jwt.decode(refreshToken, { json: true });
if (!decodedRefreshToken) { if (!decodedRefreshToken) {
throw new HttpException( throw new HttpException(
@ -273,7 +345,9 @@ export class AuthController {
} }
const { userId, delegateUserId } = decodedRefreshToken as RefreshToken; const { userId, delegateUserId } = decodedRefreshToken as RefreshToken;
const context = makeContext(userId); const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const accessToken = await this.authService.updateDelegationAccessToken( const accessToken = await this.authService.updateDelegationAccessToken(
context, context,
delegateUserId, delegateUserId,

View File

@ -31,7 +31,7 @@ describe('AuthService', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.RyieW-VHsHPQOjXbbhRc307AYJOc1sq2hrcu4SW1-K0pvLlkplepxvx02a3vCwQrnBYrIP5w6HExG-S_JgW5nYyWr6DeY11mA484n9KA8GeAcAXV37StH1gfWUJvfGb4C8BaMbMM9Ix4Z9NGwKA9vjNwevfmBZnz9lQUePgv6BJNmyvCt8ElJ01O-1WODbZuojJ4xXymA1OqluzfbphPOsqWTSNmTn0emkLjjnlMQf1iwM4C_kvvr8dUCFg0_UGDfQVJnzPEKB38UqnhLnC5WacrddDwQ0kBuGKZgZ_63Q_7fOvqAZivqLK7BPmbPxi6mx3R1S9Eq2ugzpY1LfJOjA'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.RyieW-VHsHPQOjXbbhRc307AYJOc1sq2hrcu4SW1-K0pvLlkplepxvx02a3vCwQrnBYrIP5w6HExG-S_JgW5nYyWr6DeY11mA484n9KA8GeAcAXV37StH1gfWUJvfGb4C8BaMbMM9Ix4Z9NGwKA9vjNwevfmBZnz9lQUePgv6BJNmyvCt8ElJ01O-1WODbZuojJ4xXymA1OqluzfbphPOsqWTSNmTn0emkLjjnlMQf1iwM4C_kvvr8dUCFg0_UGDfQVJnzPEKB38UqnhLnC5WacrddDwQ0kBuGKZgZ_63Q_7fOvqAZivqLK7BPmbPxi6mx3R1S9Eq2ugzpY1LfJOjA';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect(await service.getVerifiedIdToken(context, token)).toEqual( expect(await service.getVerifiedIdToken(context, token)).toEqual(
idTokenPayload, idTokenPayload,
); );
@ -43,7 +43,7 @@ describe('AuthService', () => {
const service = await makeAuthServiceMock(adb2cParam, configMockValue); const service = await makeAuthServiceMock(adb2cParam, configMockValue);
const token = 'invalid.id.token'; const token = 'invalid.id.token';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual( await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual(
new HttpException(makeErrorResponse('E000101'), HttpStatus.UNAUTHORIZED), new HttpException(makeErrorResponse('E000101'), HttpStatus.UNAUTHORIZED),
); );
@ -58,7 +58,7 @@ describe('AuthService', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjEwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.r9x61Mf1S2qFgU_QDKB6tRFBmTQXyOEtpoacOlL_bQzFz1t3GsxMy6SJIvQQ-LtDgylQ1UCdMFiRuy4V8nyLuME0fR-9IkKsboGvwllHB_Isai3XFoja0jpDHMVby1m0B3Z9xOTb7YsaQGyEH-qs1TtnRm6Ny98h4Po80nK8HGefQZHBOlfQN_B1LiHwI3nLXV18NL-4olKXj2NloNRYtnWM0PaqDQcGvZFaSNvtrSYpo9ddD906QWDGVOQ7WvGSUgdNCoxX8Lb3r2-VSj6n84jpb-Y1Fz-GhLluNglAsBhasnJfUIvCIO3iG5pRyTYjHFAVHmzjr8xMOmhS3s41Jw'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjEwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.r9x61Mf1S2qFgU_QDKB6tRFBmTQXyOEtpoacOlL_bQzFz1t3GsxMy6SJIvQQ-LtDgylQ1UCdMFiRuy4V8nyLuME0fR-9IkKsboGvwllHB_Isai3XFoja0jpDHMVby1m0B3Z9xOTb7YsaQGyEH-qs1TtnRm6Ny98h4Po80nK8HGefQZHBOlfQN_B1LiHwI3nLXV18NL-4olKXj2NloNRYtnWM0PaqDQcGvZFaSNvtrSYpo9ddD906QWDGVOQ7WvGSUgdNCoxX8Lb3r2-VSj6n84jpb-Y1Fz-GhLluNglAsBhasnJfUIvCIO3iG5pRyTYjHFAVHmzjr8xMOmhS3s41Jw';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual( await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual(
new HttpException(makeErrorResponse('E000102'), HttpStatus.UNAUTHORIZED), new HttpException(makeErrorResponse('E000102'), HttpStatus.UNAUTHORIZED),
); );
@ -73,7 +73,7 @@ describe('AuthService', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6OTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.fX2Gbd7fDPNE3Lw-xbum_5CVqQYqEmMhv_v5u8A-U81pmPD2P5rsJEJx66ns1taFLVaE3j9_OzotxrqjqqQqbACkagGcN5wvA3_ZIxyqmhrKYFJc53ZcO7d0pFWiQlluNBI_pnFNDlSMB2Ut8Th5aiPy2uamBM9wC99bcjo7HkHvTKBf6ljU6rPKoD51qGDWqNxjoH-hdSJ29wprvyxyk_yX6dp-cxXUj5DIgXYQuIZF71rdiPtGlAiyTBns8rS2QlEEXapZVlvYrK4mkpUXVDA7ifD8q6gAC2BStqHeys7CGp2MbV4ZwKCVbAUbMs6Tboh8rADZvQhuTEq7qlhZ-w'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6OTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.fX2Gbd7fDPNE3Lw-xbum_5CVqQYqEmMhv_v5u8A-U81pmPD2P5rsJEJx66ns1taFLVaE3j9_OzotxrqjqqQqbACkagGcN5wvA3_ZIxyqmhrKYFJc53ZcO7d0pFWiQlluNBI_pnFNDlSMB2Ut8Th5aiPy2uamBM9wC99bcjo7HkHvTKBf6ljU6rPKoD51qGDWqNxjoH-hdSJ29wprvyxyk_yX6dp-cxXUj5DIgXYQuIZF71rdiPtGlAiyTBns8rS2QlEEXapZVlvYrK4mkpUXVDA7ifD8q6gAC2BStqHeys7CGp2MbV4ZwKCVbAUbMs6Tboh8rADZvQhuTEq7qlhZ-w';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual( await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual(
new HttpException(makeErrorResponse('E000103'), HttpStatus.UNAUTHORIZED), new HttpException(makeErrorResponse('E000103'), HttpStatus.UNAUTHORIZED),
); );
@ -86,7 +86,7 @@ describe('AuthService', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdXNlciIsInN1YiI6InN1YiIsImF1ZCI6ImF1ZCIsIm5vbmNlIjoiZGVmYXVsdE5vbmNlIiwiaWF0IjoxMDAwMDAwMDAwLCJhdXRoX3RpbWUiOjEwMDAwMDAwMDAsImVtYWlscyI6WyJ4eHhAeHguY29tIl0sInRmcCI6InNpZ25pbl91c2VyZmxvdyJ9.sign'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdXNlciIsInN1YiI6InN1YiIsImF1ZCI6ImF1ZCIsIm5vbmNlIjoiZGVmYXVsdE5vbmNlIiwiaWF0IjoxMDAwMDAwMDAwLCJhdXRoX3RpbWUiOjEwMDAwMDAwMDAsImVtYWlscyI6WyJ4eHhAeHguY29tIl0sInRmcCI6InNpZ25pbl91c2VyZmxvdyJ9.sign';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual( await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual(
new HttpException(makeErrorResponse('E000104'), HttpStatus.UNAUTHORIZED), new HttpException(makeErrorResponse('E000104'), HttpStatus.UNAUTHORIZED),
); );
@ -101,7 +101,7 @@ describe('AuthService', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaW52bGlkX2lzc3VlciIsInN1YiI6InN1YiIsImF1ZCI6ImF1ZCIsIm5vbmNlIjoiZGVmYXVsdE5vbmNlIiwiaWF0IjoxMDAwMDAwMDAwLCJhdXRoX3RpbWUiOjEwMDAwMDAwMDAsImVtYWlscyI6WyJ4eHhAeHguY29tIl0sInRmcCI6InNpZ25pbl91c2VyZmxvdyJ9.0bp3e1mDG78PX3lo8zgOLXGenIqG_Vi6kw7CbwauAQM-cnUZ_aVCoJ_dAv_QmPElOQKcCkRrAvAZ91FwuHDlBGuuDqx8OwqN0VaD-4NPouoAswj-9HNvBm8gUn-pGaXkvWt_72UdCJavZJjDj_RHur8y8kFt5Qeab3mUP2x-uNcV2Q2x3M_IIfcRiIZkRZm_azKfiVIy7tzoUFLDss97y938aR8imMVxazoSQvj7RWIWylgeRr9yVt7qYl18cnEVL0IGtslFbqhfNsiEmRCMsttm5kXs7E9B0bhhUe_xbJW9VumQ6G7dgMrswevp_jRgbpWJoZsgErtqIRl9Tc9ikA'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaW52bGlkX2lzc3VlciIsInN1YiI6InN1YiIsImF1ZCI6ImF1ZCIsIm5vbmNlIjoiZGVmYXVsdE5vbmNlIiwiaWF0IjoxMDAwMDAwMDAwLCJhdXRoX3RpbWUiOjEwMDAwMDAwMDAsImVtYWlscyI6WyJ4eHhAeHguY29tIl0sInRmcCI6InNpZ25pbl91c2VyZmxvdyJ9.0bp3e1mDG78PX3lo8zgOLXGenIqG_Vi6kw7CbwauAQM-cnUZ_aVCoJ_dAv_QmPElOQKcCkRrAvAZ91FwuHDlBGuuDqx8OwqN0VaD-4NPouoAswj-9HNvBm8gUn-pGaXkvWt_72UdCJavZJjDj_RHur8y8kFt5Qeab3mUP2x-uNcV2Q2x3M_IIfcRiIZkRZm_azKfiVIy7tzoUFLDss97y938aR8imMVxazoSQvj7RWIWylgeRr9yVt7qYl18cnEVL0IGtslFbqhfNsiEmRCMsttm5kXs7E9B0bhhUe_xbJW9VumQ6G7dgMrswevp_jRgbpWJoZsgErtqIRl9Tc9ikA';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual( await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual(
new HttpException(makeErrorResponse('E000105'), HttpStatus.UNAUTHORIZED), new HttpException(makeErrorResponse('E000105'), HttpStatus.UNAUTHORIZED),
); );
@ -115,7 +115,7 @@ describe('AuthService', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.RyieW-VHsHPQOjXbbhRc307AYJOc1sq2hrcu4SW1-K0pvLlkplepxvx02a3vCwQrnBYrIP5w6HExG-S_JgW5nYyWr6DeY11mA484n9KA8GeAcAXV37StH1gfWUJvfGb4C8BaMbMM9Ix4Z9NGwKA9vjNwevfmBZnz9lQUePgv6BJNmyvCt8ElJ01O-1WODbZuojJ4xXymA1OqluzfbphPOsqWTSNmTn0emkLjjnlMQf1iwM4C_kvvr8dUCFg0_UGDfQVJnzPEKB38UqnhLnC5WacrddDwQ0kBuGKZgZ_63Q_7fOvqAZivqLK7BPmbPxi6mx3R1S9Eq2ugzpY1LfJOjA'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.RyieW-VHsHPQOjXbbhRc307AYJOc1sq2hrcu4SW1-K0pvLlkplepxvx02a3vCwQrnBYrIP5w6HExG-S_JgW5nYyWr6DeY11mA484n9KA8GeAcAXV37StH1gfWUJvfGb4C8BaMbMM9Ix4Z9NGwKA9vjNwevfmBZnz9lQUePgv6BJNmyvCt8ElJ01O-1WODbZuojJ4xXymA1OqluzfbphPOsqWTSNmTn0emkLjjnlMQf1iwM4C_kvvr8dUCFg0_UGDfQVJnzPEKB38UqnhLnC5WacrddDwQ0kBuGKZgZ_63Q_7fOvqAZivqLK7BPmbPxi6mx3R1S9Eq2ugzpY1LfJOjA';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual( await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),
@ -131,7 +131,7 @@ describe('AuthService', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.RyieW-VHsHPQOjXbbhRc307AYJOc1sq2hrcu4SW1-K0pvLlkplepxvx02a3vCwQrnBYrIP5w6HExG-S_JgW5nYyWr6DeY11mA484n9KA8GeAcAXV37StH1gfWUJvfGb4C8BaMbMM9Ix4Z9NGwKA9vjNwevfmBZnz9lQUePgv6BJNmyvCt8ElJ01O-1WODbZuojJ4xXymA1OqluzfbphPOsqWTSNmTn0emkLjjnlMQf1iwM4C_kvvr8dUCFg0_UGDfQVJnzPEKB38UqnhLnC5WacrddDwQ0kBuGKZgZ_63Q_7fOvqAZivqLK7BPmbPxi6mx3R1S9Eq2ugzpY1LfJOjA'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.RyieW-VHsHPQOjXbbhRc307AYJOc1sq2hrcu4SW1-K0pvLlkplepxvx02a3vCwQrnBYrIP5w6HExG-S_JgW5nYyWr6DeY11mA484n9KA8GeAcAXV37StH1gfWUJvfGb4C8BaMbMM9Ix4Z9NGwKA9vjNwevfmBZnz9lQUePgv6BJNmyvCt8ElJ01O-1WODbZuojJ4xXymA1OqluzfbphPOsqWTSNmTn0emkLjjnlMQf1iwM4C_kvvr8dUCFg0_UGDfQVJnzPEKB38UqnhLnC5WacrddDwQ0kBuGKZgZ_63Q_7fOvqAZivqLK7BPmbPxi6mx3R1S9Eq2ugzpY1LfJOjA';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual( await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),
@ -150,7 +150,7 @@ describe('AuthService', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.RyieW-VHsHPQOjXbbhRc307AYJOc1sq2hrcu4SW1-K0pvLlkplepxvx02a3vCwQrnBYrIP5w6HExG-S_JgW5nYyWr6DeY11mA484n9KA8GeAcAXV37StH1gfWUJvfGb4C8BaMbMM9Ix4Z9NGwKA9vjNwevfmBZnz9lQUePgv6BJNmyvCt8ElJ01O-1WODbZuojJ4xXymA1OqluzfbphPOsqWTSNmTn0emkLjjnlMQf1iwM4C_kvvr8dUCFg0_UGDfQVJnzPEKB38UqnhLnC5WacrddDwQ0kBuGKZgZ_63Q_7fOvqAZivqLK7BPmbPxi6mx3R1S9Eq2ugzpY1LfJOjA'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtpZCJ9.eyJleHAiOjkwMDAwMDAwMDAsIm5iZiI6MTAwMDAwMDAwMCwidmVyIjoiMS4wIiwiaXNzIjoiaXNzdWVyIiwic3ViIjoic3ViIiwiYXVkIjoiYXVkIiwibm9uY2UiOiJkZWZhdWx0Tm9uY2UiLCJpYXQiOjEwMDAwMDAwMDAsImF1dGhfdGltZSI6MTAwMDAwMDAwMCwiZW1haWxzIjpbInh4eEB4eC5jb20iXSwidGZwIjoic2lnbmluX3VzZXJmbG93In0.RyieW-VHsHPQOjXbbhRc307AYJOc1sq2hrcu4SW1-K0pvLlkplepxvx02a3vCwQrnBYrIP5w6HExG-S_JgW5nYyWr6DeY11mA484n9KA8GeAcAXV37StH1gfWUJvfGb4C8BaMbMM9Ix4Z9NGwKA9vjNwevfmBZnz9lQUePgv6BJNmyvCt8ElJ01O-1WODbZuojJ4xXymA1OqluzfbphPOsqWTSNmTn0emkLjjnlMQf1iwM4C_kvvr8dUCFg0_UGDfQVJnzPEKB38UqnhLnC5WacrddDwQ0kBuGKZgZ_63Q_7fOvqAZivqLK7BPmbPxi6mx3R1S9Eq2ugzpY1LfJOjA';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual( await expect(service.getVerifiedIdToken(context, token)).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),
@ -186,7 +186,7 @@ describe('checkIsAcceptedLatestVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 5, tier: 5,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const idToken = { const idToken = {
emails: [], emails: [],
@ -210,7 +210,7 @@ describe('checkIsAcceptedLatestVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 4, tier: 4,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const idToken = { const idToken = {
emails: [], emails: [],
@ -234,7 +234,7 @@ describe('checkIsAcceptedLatestVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 5, tier: 5,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const idToken = { const idToken = {
emails: [], emails: [],
@ -258,7 +258,7 @@ describe('checkIsAcceptedLatestVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 4, tier: 4,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const idToken = { const idToken = {
emails: [], emails: [],
@ -282,7 +282,7 @@ describe('checkIsAcceptedLatestVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 4, tier: 4,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const idToken = { const idToken = {
emails: [], emails: [],
@ -306,7 +306,7 @@ describe('checkIsAcceptedLatestVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 4, tier: 4,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const idToken = { const idToken = {
emails: [], emails: [],
@ -361,7 +361,11 @@ describe('generateDelegationRefreshToken', () => {
{ role: USER_ROLES.NONE }, { role: USER_ROLES.NONE },
); );
const context = makeContext(parentAdmin.external_id); const context = makeContext(
parentAdmin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const delegationRefreshToken = await service.generateDelegationRefreshToken( const delegationRefreshToken = await service.generateDelegationRefreshToken(
context, context,
@ -399,7 +403,11 @@ describe('generateDelegationRefreshToken', () => {
{ role: USER_ROLES.NONE }, { role: USER_ROLES.NONE },
); );
const context = makeContext(parentAdmin.external_id); const context = makeContext(
parentAdmin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
try { try {
await service.generateDelegationRefreshToken( await service.generateDelegationRefreshToken(
@ -437,7 +445,11 @@ describe('generateDelegationRefreshToken', () => {
{ role: USER_ROLES.NONE }, { role: USER_ROLES.NONE },
); );
const context = makeContext(parentAdmin.external_id); const context = makeContext(
parentAdmin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
try { try {
await service.generateDelegationRefreshToken( await service.generateDelegationRefreshToken(
@ -495,7 +507,11 @@ describe('generateDelegationAccessToken', () => {
{ role: USER_ROLES.NONE }, { role: USER_ROLES.NONE },
); );
const context = makeContext(parentAdmin.external_id); const context = makeContext(
parentAdmin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const delegationRefreshToken = await service.generateDelegationRefreshToken( const delegationRefreshToken = await service.generateDelegationRefreshToken(
context, context,
@ -540,7 +556,11 @@ describe('generateDelegationAccessToken', () => {
tier: 4, tier: 4,
}); });
const context = makeContext(parentAdmin.external_id); const context = makeContext(
parentAdmin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
try { try {
await service.generateDelegationAccessToken(context, 'invalid token'); await service.generateDelegationAccessToken(context, 'invalid token');
@ -595,7 +615,11 @@ describe('updateDelegationAccessToken', () => {
{ role: USER_ROLES.NONE }, { role: USER_ROLES.NONE },
); );
const context = makeContext(parentAdmin.external_id); const context = makeContext(
parentAdmin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const delegationRefreshToken = await service.generateDelegationRefreshToken( const delegationRefreshToken = await service.generateDelegationRefreshToken(
context, context,
@ -653,7 +677,11 @@ describe('updateDelegationAccessToken', () => {
{ role: USER_ROLES.NONE }, { role: USER_ROLES.NONE },
); );
const context = makeContext(parentAdmin.external_id); const context = makeContext(
parentAdmin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const delegationRefreshToken = await service.generateDelegationRefreshToken( const delegationRefreshToken = await service.generateDelegationRefreshToken(
context, context,
@ -719,7 +747,11 @@ describe('updateDelegationAccessToken', () => {
{ role: USER_ROLES.NONE }, { role: USER_ROLES.NONE },
); );
const context = makeContext(parentAdmin.external_id); const context = makeContext(
parentAdmin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const delegationRefreshToken = await service.generateDelegationRefreshToken( const delegationRefreshToken = await service.generateDelegationRefreshToken(
context, context,

View File

@ -4,6 +4,7 @@ import {
Get, Get,
HttpException, HttpException,
HttpStatus, HttpStatus,
Logger,
Post, Post,
Query, Query,
Req, Req,
@ -37,12 +38,13 @@ import { RoleGuard } from '../../common/guards/role/roleguards';
import { ADMIN_ROLES, USER_ROLES } from '../../constants'; import { ADMIN_ROLES, USER_ROLES } from '../../constants';
import { retrieveAuthorizationToken } from '../../common/http/helper'; import { retrieveAuthorizationToken } from '../../common/http/helper';
import { Request } from 'express'; import { Request } from 'express';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { makeErrorResponse } from '../../common/error/makeErrorResponse'; import { makeErrorResponse } from '../../common/error/makeErrorResponse';
@ApiTags('files') @ApiTags('files')
@Controller('files') @Controller('files')
export class FilesController { export class FilesController {
private readonly logger = new Logger(FilesController.name);
constructor(private readonly filesService: FilesService) {} constructor(private readonly filesService: FilesService) {}
@ApiResponse({ @ApiResponse({
@ -84,6 +86,22 @@ export class FilesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -93,7 +111,8 @@ export class FilesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const { const {
url, url,
@ -176,6 +195,22 @@ export class FilesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -185,7 +220,8 @@ export class FilesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const url = await this.filesService.publishUploadSas(context, userId); const url = await this.filesService.publishUploadSas(context, userId);
return { url }; return { url };
@ -237,6 +273,22 @@ export class FilesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -246,7 +298,8 @@ export class FilesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const url = await this.filesService.publishAudioFileDownloadSas( const url = await this.filesService.publishAudioFileDownloadSas(
context, context,
@ -301,6 +354,22 @@ export class FilesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -310,7 +379,8 @@ export class FilesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const url = await this.filesService.publishTemplateFileDownloadSas( const url = await this.filesService.publishTemplateFileDownloadSas(
context, context,
@ -357,6 +427,22 @@ export class FilesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -366,7 +452,8 @@ export class FilesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const url = await this.filesService.publishTemplateFileUploadSas( const url = await this.filesService.publishTemplateFileUploadSas(
context, context,
@ -418,6 +505,22 @@ export class FilesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -427,7 +530,8 @@ export class FilesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.filesService.templateUploadFinished(context, userId, url, name); await this.filesService.templateUploadFinished(context, userId, url, name);
return {}; return {};
} }

View File

@ -85,7 +85,7 @@ describe('publishUploadSas', () => {
null, null,
null, null,
); );
const context = makeContext(externalId); const context = makeContext(externalId, 'xxx.xxx.xxx.xxx', 'requestId');
const baseUrl = `https://saodmsusdev.blob.core.windows.net/account-${account.id}/${userId}`; const baseUrl = `https://saodmsusdev.blob.core.windows.net/account-${account.id}/${userId}`;
//SASトークンを返却する //SASトークンを返却する
@ -107,7 +107,11 @@ describe('publishUploadSas', () => {
// 第四階層のアカウント作成 // 第四階層のアカウント作成
const { admin } = await makeTestAccount(source, { tier: 4 }); const { admin } = await makeTestAccount(source, { tier: 4 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//Blobコンテナ存在チェックに失敗するようにする //Blobコンテナ存在チェックに失敗するようにする
overrideBlobstorageService(service, { overrideBlobstorageService(service, {
@ -135,7 +139,11 @@ describe('publishUploadSas', () => {
// 第四階層のアカウント作成 // 第四階層のアカウント作成
const { admin } = await makeTestAccount(source, { tier: 4 }); const { admin } = await makeTestAccount(source, { tier: 4 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//BlobのSASトークン生成に失敗するようにする //BlobのSASトークン生成に失敗するようにする
overrideBlobstorageService(service, { overrideBlobstorageService(service, {
@ -164,7 +172,11 @@ describe('publishUploadSas', () => {
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { admin } = await makeTestAccount(source, { tier: 5, locked: true }); const { admin } = await makeTestAccount(source, { tier: 5, locked: true });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
try { try {
await service.publishUploadSas(context, admin.external_id); await service.publishUploadSas(context, admin.external_id);
@ -209,7 +221,10 @@ describe('publishUploadSas', () => {
const service = module.get<FilesService>(FilesService); const service = module.get<FilesService>(FilesService);
await expect( await expect(
service.publishUploadSas(makeContext('trackingId'), externalId), service.publishUploadSas(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010812'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010812'), HttpStatus.BAD_REQUEST),
); );
@ -267,7 +282,10 @@ describe('publishUploadSas', () => {
const service = module.get<FilesService>(FilesService); const service = module.get<FilesService>(FilesService);
await expect( await expect(
service.publishUploadSas(makeContext('trackingId'), externalId), service.publishUploadSas(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010805'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010805'), HttpStatus.BAD_REQUEST),
); );
@ -348,7 +366,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
NotificationhubService, NotificationhubService,
); );
const result = await service.uploadFinished( const result = await service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
authorExternalId, authorExternalId,
'http://blob/url/file.zip', 'http://blob/url/file.zip',
authorAuthorId ?? '', authorAuthorId ?? '',
@ -368,7 +386,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
expect(result).toEqual({ jobNumber: '00000001' }); expect(result).toEqual({ jobNumber: '00000001' });
// 通知処理が想定通りの引数で呼ばれているか確認 // 通知処理が想定通りの引数で呼ばれているか確認
expect(NotificationHubService.notify).toHaveBeenCalledWith( expect(NotificationHubService.notify).toHaveBeenCalledWith(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
[`user_${typistUserId}`], [`user_${typistUserId}`],
{ {
authorId: 'AUTHOR_ID', authorId: 'AUTHOR_ID',
@ -449,7 +467,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
NotificationhubService, NotificationhubService,
); );
const result = await service.uploadFinished( const result = await service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
authorExternalId, authorExternalId,
'http://blob/url/file.zip', 'http://blob/url/file.zip',
authorAuthorId ?? '', authorAuthorId ?? '',
@ -469,7 +487,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
expect(result).toEqual({ jobNumber: '00000002' }); expect(result).toEqual({ jobNumber: '00000002' });
// 通知処理が想定通りの引数で呼ばれているか確認 // 通知処理が想定通りの引数で呼ばれているか確認
expect(NotificationHubService.notify).toHaveBeenCalledWith( expect(NotificationHubService.notify).toHaveBeenCalledWith(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
[`user_${typistUserId}`], [`user_${typistUserId}`],
{ {
authorId: 'AUTHOR_ID', authorId: 'AUTHOR_ID',
@ -572,7 +590,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
NotificationhubService, NotificationhubService,
); );
const result = await service.uploadFinished( const result = await service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
myExternalId, // API実行者のユーザーIDを設定 myExternalId, // API実行者のユーザーIDを設定
'http://blob/url/file.zip', 'http://blob/url/file.zip',
authorAuthorId ?? '', // 音声ファイルの情報には、録音者のAuthorIDが入る authorAuthorId ?? '', // 音声ファイルの情報には、録音者のAuthorIDが入る
@ -592,7 +610,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
expect(result).toEqual({ jobNumber: '00000001' }); expect(result).toEqual({ jobNumber: '00000001' });
// 通知処理が想定通りの引数で呼ばれているか確認 // 通知処理が想定通りの引数で呼ばれているか確認
expect(NotificationHubService.notify).toHaveBeenCalledWith( expect(NotificationHubService.notify).toHaveBeenCalledWith(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
[`user_${typistUserId}`], [`user_${typistUserId}`],
{ {
authorId: 'AUTHOR_ID', authorId: 'AUTHOR_ID',
@ -694,7 +712,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
NotificationhubService, NotificationhubService,
); );
const result = await service.uploadFinished( const result = await service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
myExternalId, // API実行者のユーザーIDを設定 myExternalId, // API実行者のユーザーIDを設定
'http://blob/url/file.zip', 'http://blob/url/file.zip',
'XXXXXXXXXX', // 音声ファイルの情報には、録音者のAuthorIDが入る 'XXXXXXXXXX', // 音声ファイルの情報には、録音者のAuthorIDが入る
@ -714,7 +732,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
expect(result).toEqual({ jobNumber: '00000001' }); expect(result).toEqual({ jobNumber: '00000001' });
// 通知処理が想定通りの引数で呼ばれているか確認 // 通知処理が想定通りの引数で呼ばれているか確認
expect(NotificationHubService.notify).toHaveBeenCalledWith( expect(NotificationHubService.notify).toHaveBeenCalledWith(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
[`user_${typistUserId}`], [`user_${typistUserId}`],
{ {
authorId: 'XXXXXXXXXX', authorId: 'XXXXXXXXXX',
@ -763,7 +781,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
const service = module.get<FilesService>(FilesService); const service = module.get<FilesService>(FilesService);
const result = await service.uploadFinished( const result = await service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
authorExternalId, // API実行者のユーザーIDを設定 authorExternalId, // API実行者のユーザーIDを設定
'http://blob/url/file.zip', 'http://blob/url/file.zip',
authorAuthorId ?? '', // 音声ファイルの情報には、録音者のAuthorIDが入る authorAuthorId ?? '', // 音声ファイルの情報には、録音者のAuthorIDが入る
@ -819,7 +837,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
await expect( await expect(
service.uploadFinished( service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
authorExternalId, authorExternalId,
'http://blob/url/file.zip', 'http://blob/url/file.zip',
authorAuthorId ?? '', authorAuthorId ?? '',
@ -866,7 +884,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
await expect( await expect(
service.uploadFinished( service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
authorExternalId, authorExternalId,
'http://blob/url/file.zip', 'http://blob/url/file.zip',
authorAuthorId ?? '', authorAuthorId ?? '',
@ -907,7 +925,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
await expect( await expect(
service.uploadFinished( service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
'authorExternalId', 'authorExternalId',
'http://blob/url/file.zip', 'http://blob/url/file.zip',
'authorAuthorId', 'authorAuthorId',
@ -958,7 +976,7 @@ describe('タスク作成から自動ルーティング(DB使用)', () => {
await expect( await expect(
service.uploadFinished( service.uploadFinished(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
authorExternalId, authorExternalId,
'http://blob/url/file.zip', 'http://blob/url/file.zip',
authorAuthorId ?? '', authorAuthorId ?? '',
@ -1043,7 +1061,7 @@ describe('音声ファイルダウンロードURL取得', () => {
expect( expect(
await service.publishAudioFileDownloadSas( await service.publishAudioFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1113,7 +1131,7 @@ describe('音声ファイルダウンロードURL取得', () => {
expect( expect(
await service.publishAudioFileDownloadSas( await service.publishAudioFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1160,7 +1178,7 @@ describe('音声ファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishAudioFileDownloadSas( service.publishAudioFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1214,7 +1232,7 @@ describe('音声ファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishTemplateFileDownloadSas( service.publishTemplateFileDownloadSas(
makeContext('tracking'), makeContext('tracking', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1259,7 +1277,7 @@ describe('音声ファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishAudioFileDownloadSas( service.publishAudioFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1291,7 +1309,7 @@ describe('音声ファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishAudioFileDownloadSas( service.publishAudioFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
1, 1,
), ),
@ -1340,7 +1358,7 @@ describe('音声ファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishAudioFileDownloadSas( service.publishAudioFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1395,7 +1413,7 @@ describe('音声ファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishAudioFileDownloadSas( service.publishAudioFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1467,7 +1485,7 @@ describe('音声ファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishAudioFileDownloadSas( service.publishAudioFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1535,7 +1553,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
expect( expect(
await service.publishTemplateFileDownloadSas( await service.publishTemplateFileDownloadSas(
makeContext('tracking'), makeContext('tracking', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1605,7 +1623,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
expect( expect(
await service.publishTemplateFileDownloadSas( await service.publishTemplateFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1646,7 +1664,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishTemplateFileDownloadSas( service.publishTemplateFileDownloadSas(
makeContext('tracking'), makeContext('tracking', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1696,7 +1714,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishTemplateFileDownloadSas( service.publishTemplateFileDownloadSas(
makeContext('tracking'), makeContext('tracking', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1741,7 +1759,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishTemplateFileDownloadSas( service.publishTemplateFileDownloadSas(
makeContext('tracking'), makeContext('tracking', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1773,7 +1791,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishTemplateFileDownloadSas( service.publishTemplateFileDownloadSas(
makeContext('tracking'), makeContext('tracking', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
1, 1,
), ),
@ -1821,7 +1839,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishTemplateFileDownloadSas( service.publishTemplateFileDownloadSas(
makeContext('tracking'), makeContext('tracking', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1876,7 +1894,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishTemplateFileDownloadSas( service.publishTemplateFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1948,7 +1966,7 @@ describe('テンプレートファイルダウンロードURL取得', () => {
await expect( await expect(
service.publishTemplateFileDownloadSas( service.publishTemplateFileDownloadSas(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
audioFileId, audioFileId,
), ),
@ -1985,7 +2003,11 @@ describe('publishTemplateFileUploadSas', () => {
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { account, admin } = await makeTestAccount(source, { tier: 5 }); const { account, admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const baseUrl = `https://saodmsusdev.blob.core.windows.net/account-${account.id}/Templates`; const baseUrl = `https://saodmsusdev.blob.core.windows.net/account-${account.id}/Templates`;
//SASトークンを返却する //SASトークンを返却する
@ -2010,7 +2032,11 @@ describe('publishTemplateFileUploadSas', () => {
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { admin } = await makeTestAccount(source, { tier: 5 }); const { admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//Blobコンテナ存在チェックに失敗するようにする //Blobコンテナ存在チェックに失敗するようにする
overrideBlobstorageService(service, { overrideBlobstorageService(service, {
@ -2038,7 +2064,11 @@ describe('publishTemplateFileUploadSas', () => {
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { admin } = await makeTestAccount(source, { tier: 5 }); const { admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//BlobのSASトークン生成に失敗するようにする //BlobのSASトークン生成に失敗するようにする
overrideBlobstorageService(service, { overrideBlobstorageService(service, {
@ -2087,7 +2117,11 @@ describe('templateUploadFinished', () => {
const service = module.get<FilesService>(FilesService); const service = module.get<FilesService>(FilesService);
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { account, admin } = await makeTestAccount(source, { tier: 5 }); const { account, admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const fileName = 'test.docs'; const fileName = 'test.docs';
const url = `https://blob.url/account-${account.id}/Templates`; const url = `https://blob.url/account-${account.id}/Templates`;
@ -2121,7 +2155,11 @@ describe('templateUploadFinished', () => {
const service = module.get<FilesService>(FilesService); const service = module.get<FilesService>(FilesService);
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { account, admin } = await makeTestAccount(source, { tier: 5 }); const { account, admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const fileName = 'test.docs'; const fileName = 'test.docs';
const url = `https://blob.url/account-${account.id}/Templates`; const url = `https://blob.url/account-${account.id}/Templates`;
@ -2161,7 +2199,11 @@ describe('templateUploadFinished', () => {
const service = module.get<FilesService>(FilesService); const service = module.get<FilesService>(FilesService);
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { account, admin } = await makeTestAccount(source, { tier: 5 }); const { account, admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const fileName = 'test.docs'; const fileName = 'test.docs';
const url = `https://blob.url/account-${account.id}/Templates`; const url = `https://blob.url/account-${account.id}/Templates`;

View File

@ -4,6 +4,7 @@ import {
Get, Get,
HttpException, HttpException,
HttpStatus, HttpStatus,
Logger,
Post, Post,
Req, Req,
UseGuards, UseGuards,
@ -34,12 +35,13 @@ import { AuthGuard } from '../../common/guards/auth/authguards';
import { RoleGuard } from '../../common/guards/role/roleguards'; import { RoleGuard } from '../../common/guards/role/roleguards';
import { ADMIN_ROLES, TIERS } from '../../constants'; import { ADMIN_ROLES, TIERS } from '../../constants';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { makeErrorResponse } from '../../common/error/makeErrorResponse'; import { makeErrorResponse } from '../../common/error/makeErrorResponse';
@ApiTags('licenses') @ApiTags('licenses')
@Controller('licenses') @Controller('licenses')
export class LicensesController { export class LicensesController {
private readonly logger = new Logger(LicensesController.name);
constructor(private readonly licensesService: LicensesService) {} constructor(private readonly licensesService: LicensesService) {}
@ApiResponse({ @ApiResponse({
status: HttpStatus.OK, status: HttpStatus.OK,
@ -83,6 +85,22 @@ export class LicensesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -91,7 +109,9 @@ export class LicensesController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
// ライセンス注文処理 // ライセンス注文処理
await this.licensesService.licenseOrders( await this.licensesService.licenseOrders(
@ -136,6 +156,22 @@ export class LicensesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -144,7 +180,9 @@ export class LicensesController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const cardLicenseKeys = await this.licensesService.issueCardLicenseKeys( const cardLicenseKeys = await this.licensesService.issueCardLicenseKeys(
context, context,
@ -198,6 +236,22 @@ export class LicensesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -206,7 +260,9 @@ export class LicensesController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId);
const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.licensesService.activateCardLicenseKey( await this.licensesService.activateCardLicenseKey(
context, context,
@ -257,6 +313,22 @@ export class LicensesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -266,7 +338,8 @@ export class LicensesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const allocatableLicenses = const allocatableLicenses =
await this.licensesService.getAllocatableLicenses(context, userId); await this.licensesService.getAllocatableLicenses(context, userId);
@ -319,6 +392,22 @@ export class LicensesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -328,7 +417,8 @@ export class LicensesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.licensesService.cancelOrder(context, userId, body.poNumber); await this.licensesService.cancelOrder(context, userId, body.poNumber);
return {}; return {};

View File

@ -59,7 +59,7 @@ describe('LicensesService', () => {
const userId = '0001'; const userId = '0001';
body.orderCount = 1000; body.orderCount = 1000;
body.poNumber = '1'; body.poNumber = '1';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.licenseOrders( await service.licenseOrders(
context, context,
@ -87,7 +87,7 @@ describe('LicensesService', () => {
const userId = ''; const userId = '';
body.orderCount = 1000; body.orderCount = 1000;
body.poNumber = '1'; body.poNumber = '1';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.licenseOrders(context, userId, body.poNumber, body.orderCount), service.licenseOrders(context, userId, body.poNumber, body.orderCount),
).rejects.toEqual( ).rejects.toEqual(
@ -115,7 +115,7 @@ describe('LicensesService', () => {
const userId = '0001'; const userId = '0001';
body.orderCount = 1000; body.orderCount = 1000;
body.poNumber = '1'; body.poNumber = '1';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.licenseOrders(context, userId, body.poNumber, body.orderCount), service.licenseOrders(context, userId, body.poNumber, body.orderCount),
).rejects.toEqual( ).rejects.toEqual(
@ -143,7 +143,7 @@ describe('LicensesService', () => {
const userId = '0001'; const userId = '0001';
body.orderCount = 1000; body.orderCount = 1000;
body.poNumber = '1'; body.poNumber = '1';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.licenseOrders(context, userId, body.poNumber, body.orderCount), service.licenseOrders(context, userId, body.poNumber, body.orderCount),
).rejects.toEqual( ).rejects.toEqual(
@ -181,7 +181,7 @@ describe('LicensesService', () => {
'AEJWRFFSWRQYQQJ6WVLV', 'AEJWRFFSWRQYQQJ6WVLV',
], ],
}; };
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.issueCardLicenseKeys(context, userId, body.createCount), await service.issueCardLicenseKeys(context, userId, body.createCount),
).toEqual(issueCardLicensesResponse); ).toEqual(issueCardLicensesResponse);
@ -201,7 +201,7 @@ describe('LicensesService', () => {
const body = new IssueCardLicensesRequest(); const body = new IssueCardLicensesRequest();
const userId = '0001'; const userId = '0001';
body.createCount = 1000; body.createCount = 1000;
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.issueCardLicenseKeys(context, userId, body.createCount), service.issueCardLicenseKeys(context, userId, body.createCount),
).rejects.toEqual( ).rejects.toEqual(
@ -225,7 +225,7 @@ describe('LicensesService', () => {
const body = new ActivateCardLicensesRequest(); const body = new ActivateCardLicensesRequest();
const userId = '0001'; const userId = '0001';
body.cardLicenseKey = 'WZCETXC0Z9PQZ9GKRGGY'; body.cardLicenseKey = 'WZCETXC0Z9PQZ9GKRGGY';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.activateCardLicenseKey( await service.activateCardLicenseKey(
context, context,
@ -249,7 +249,7 @@ describe('LicensesService', () => {
const body = new ActivateCardLicensesRequest(); const body = new ActivateCardLicensesRequest();
const userId = '0001'; const userId = '0001';
body.cardLicenseKey = 'WZCETXC0Z9PQZ9GKRGGY'; body.cardLicenseKey = 'WZCETXC0Z9PQZ9GKRGGY';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.activateCardLicenseKey(context, userId, body.cardLicenseKey), service.activateCardLicenseKey(context, userId, body.cardLicenseKey),
).rejects.toEqual( ).rejects.toEqual(
@ -276,7 +276,7 @@ describe('LicensesService', () => {
const body = new ActivateCardLicensesRequest(); const body = new ActivateCardLicensesRequest();
const userId = '0001'; const userId = '0001';
body.cardLicenseKey = 'WZCETXC0Z9PQZ9GKRGGY'; body.cardLicenseKey = 'WZCETXC0Z9PQZ9GKRGGY';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.activateCardLicenseKey(context, userId, body.cardLicenseKey), service.activateCardLicenseKey(context, userId, body.cardLicenseKey),
).rejects.toEqual( ).rejects.toEqual(
@ -299,7 +299,7 @@ describe('LicensesService', () => {
const body = new ActivateCardLicensesRequest(); const body = new ActivateCardLicensesRequest();
const userId = '0001'; const userId = '0001';
body.cardLicenseKey = 'WZCETXC0Z9PQZ9GKRGGY'; body.cardLicenseKey = 'WZCETXC0Z9PQZ9GKRGGY';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.activateCardLicenseKey(context, userId, body.cardLicenseKey), service.activateCardLicenseKey(context, userId, body.cardLicenseKey),
).rejects.toEqual( ).rejects.toEqual(
@ -342,7 +342,7 @@ describe('DBテスト', () => {
const service = module.get<LicensesService>(LicensesService); const service = module.get<LicensesService>(LicensesService);
const issueCount = 500; const issueCount = 500;
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await service.issueCardLicenseKeys(context, externalId, issueCount); await service.issueCardLicenseKeys(context, externalId, issueCount);
const dbSelectResult = await selectCardLicensesCount(source); const dbSelectResult = await selectCardLicensesCount(source);
expect(dbSelectResult.count).toEqual(issueCount); expect(dbSelectResult.count).toEqual(issueCount);
@ -382,7 +382,7 @@ describe('DBテスト', () => {
await createCardLicenseIssue(source, issueId); await createCardLicenseIssue(source, issueId);
const service = module.get<LicensesService>(LicensesService); const service = module.get<LicensesService>(LicensesService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await service.activateCardLicenseKey(context, externalId, cardLicenseKey); await service.activateCardLicenseKey(context, externalId, cardLicenseKey);
const dbSelectResultFromCardLicense = await selectCardLicense( const dbSelectResultFromCardLicense = await selectCardLicense(
@ -529,7 +529,7 @@ describe('DBテスト', () => {
null, null,
); );
const service = module.get<LicensesService>(LicensesService); const service = module.get<LicensesService>(LicensesService);
const context = makeContext('userId'); const context = makeContext('userId', 'xxx.xxx.xxx.xxx', 'requestId');
const response = await service.getAllocatableLicenses(context, externalId); const response = await service.getAllocatableLicenses(context, externalId);
// 対象外のデータは取得していないことを確認する // 対象外のデータは取得していないことを確認する
expect(response.allocatableLicenses.length).toBe(5); expect(response.allocatableLicenses.length).toBe(5);
@ -599,7 +599,11 @@ describe('ライセンス割り当て', () => {
const expiry_date = new NewAllocatedLicenseExpirationDate(); const expiry_date = new NewAllocatedLicenseExpirationDate();
await service.allocateLicense(makeContext('trackingId'), userId, 1); await service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
1,
);
const resultLicense = await selectLicense(source, 1); const resultLicense = await selectLicense(source, 1);
expect(resultLicense.license?.allocated_user_id).toBe(userId); expect(resultLicense.license?.allocated_user_id).toBe(userId);
expect(resultLicense.license?.status).toBe( expect(resultLicense.license?.status).toBe(
@ -664,7 +668,11 @@ describe('ライセンス割り当て', () => {
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.allocateLicense(makeContext('trackingId'), userId, 1); await service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
1,
);
const result = await selectLicense(source, 1); const result = await selectLicense(source, 1);
expect(result.license?.allocated_user_id).toBe(userId); expect(result.license?.allocated_user_id).toBe(userId);
expect(result.license?.status).toBe(LICENSE_ALLOCATED_STATUS.ALLOCATED); expect(result.license?.status).toBe(LICENSE_ALLOCATED_STATUS.ALLOCATED);
@ -739,7 +747,11 @@ describe('ライセンス割り当て', () => {
const expiry_date = new NewAllocatedLicenseExpirationDate(); const expiry_date = new NewAllocatedLicenseExpirationDate();
await service.allocateLicense(makeContext('trackingId'), userId, 2); await service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
2,
);
// もともと割り当てられていたライセンスの状態確認 // もともと割り当てられていたライセンスの状態確認
const result1 = await selectLicense(source, 1); const result1 = await selectLicense(source, 1);
@ -838,7 +850,11 @@ describe('ライセンス割り当て', () => {
); );
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.allocateLicense(makeContext('trackingId'), userId, 2); await service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
2,
);
const licenseAllocationHistory = await selectLicenseAllocationHistory( const licenseAllocationHistory = await selectLicenseAllocationHistory(
source, source,
@ -898,7 +914,11 @@ describe('ライセンス割り当て', () => {
); );
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.allocateLicense(makeContext('trackingId'), userId, 2); await service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
2,
);
const licenseAllocationHistory = await selectLicenseAllocationHistory( const licenseAllocationHistory = await selectLicenseAllocationHistory(
source, source,
@ -958,7 +978,11 @@ describe('ライセンス割り当て', () => {
); );
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.allocateLicense(makeContext('trackingId'), userId, 2); await service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
2,
);
const licenseAllocationHistory = await selectLicenseAllocationHistory( const licenseAllocationHistory = await selectLicenseAllocationHistory(
source, source,
@ -1000,7 +1024,11 @@ describe('ライセンス割り当て', () => {
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await expect( await expect(
service.allocateLicense(makeContext('trackingId'), userId, 1), service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
1,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010805'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010805'), HttpStatus.BAD_REQUEST),
); );
@ -1048,12 +1076,20 @@ describe('ライセンス割り当て', () => {
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await expect( await expect(
service.allocateLicense(makeContext('trackingId'), userId, 1), service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
1,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010806'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010806'), HttpStatus.BAD_REQUEST),
); );
await expect( await expect(
service.allocateLicense(makeContext('trackingId'), userId, 2), service.allocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
2,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010806'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010806'), HttpStatus.BAD_REQUEST),
); );
@ -1115,7 +1151,10 @@ describe('ライセンス割り当て解除', () => {
); );
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.deallocateLicense(makeContext('trackingId'), userId); await service.deallocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
);
// 割り当て解除したライセンスの状態確認 // 割り当て解除したライセンスの状態確認
const deallocatedLicense = await selectLicense(source, 1); const deallocatedLicense = await selectLicense(source, 1);
@ -1203,7 +1242,10 @@ describe('ライセンス割り当て解除', () => {
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await expect( await expect(
service.deallocateLicense(makeContext('trackingId'), userId), service.deallocateLicense(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010807'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010807'), HttpStatus.BAD_REQUEST),
); );
@ -1259,7 +1301,7 @@ describe('ライセンス注文キャンセル', () => {
const service = module.get<LicensesService>(LicensesService); const service = module.get<LicensesService>(LicensesService);
await service.cancelOrder( await service.cancelOrder(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
tier2Accounts[0].users[0].external_id, tier2Accounts[0].users[0].external_id,
poNumber, poNumber,
); );
@ -1295,7 +1337,7 @@ describe('ライセンス注文キャンセル', () => {
const service = module.get<LicensesService>(LicensesService); const service = module.get<LicensesService>(LicensesService);
await expect( await expect(
service.cancelOrder( service.cancelOrder(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
tier2Accounts[0].users[0].external_id, tier2Accounts[0].users[0].external_id,
poNumber, poNumber,
), ),
@ -1326,7 +1368,7 @@ describe('ライセンス注文キャンセル', () => {
const service = module.get<LicensesService>(LicensesService); const service = module.get<LicensesService>(LicensesService);
await expect( await expect(
service.cancelOrder( service.cancelOrder(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
tier2Accounts[0].users[0].external_id, tier2Accounts[0].users[0].external_id,
poNumber, poNumber,
), ),

View File

@ -3,6 +3,7 @@ import {
Controller, Controller,
HttpException, HttpException,
HttpStatus, HttpStatus,
Logger,
Post, Post,
Req, Req,
UseGuards, UseGuards,
@ -21,12 +22,13 @@ import { AuthGuard } from '../../common/guards/auth/authguards';
import { retrieveAuthorizationToken } from '../../common/http/helper'; import { retrieveAuthorizationToken } from '../../common/http/helper';
import { AccessToken } from '../../common/token'; import { AccessToken } from '../../common/token';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { makeErrorResponse } from '../../common/error/makeErrorResponse'; import { makeErrorResponse } from '../../common/error/makeErrorResponse';
@ApiTags('notification') @ApiTags('notification')
@Controller('notification') @Controller('notification')
export class NotificationController { export class NotificationController {
private readonly logger = new Logger(NotificationController.name);
constructor(private readonly notificationService: NotificationService) {} constructor(private readonly notificationService: NotificationService) {}
@Post('register') @Post('register')
@ApiResponse({ @ApiResponse({
@ -65,6 +67,22 @@ export class NotificationController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -74,7 +92,8 @@ export class NotificationController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.notificationService.register(context, userId, pns, handler); await this.notificationService.register(context, userId, pns, handler);
return {}; return {};

View File

@ -19,7 +19,7 @@ describe('NotificationService.register', () => {
expect( expect(
await service.register( await service.register(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
'external_id', 'external_id',
'apns', 'apns',
'handler', 'handler',
@ -38,7 +38,7 @@ describe('NotificationService.register', () => {
await expect( await expect(
service.register( service.register(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
'external_id', 'external_id',
'apns', 'apns',
'handler', 'handler',
@ -63,7 +63,7 @@ describe('NotificationService.register', () => {
await expect( await expect(
service.register( service.register(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
'external_id', 'external_id',
'apns', 'apns',
'handler', 'handler',

View File

@ -2,9 +2,9 @@ import {
Body, Body,
Controller, Controller,
Get, Get,
Headers,
HttpException, HttpException,
HttpStatus, HttpStatus,
Logger,
Param, Param,
ParseIntPipe, ParseIntPipe,
Post, Post,
@ -45,12 +45,13 @@ import { AuthGuard } from '../../common/guards/auth/authguards';
import { RoleGuard } from '../../common/guards/role/roleguards'; import { RoleGuard } from '../../common/guards/role/roleguards';
import { ADMIN_ROLES, USER_ROLES } from '../../constants'; import { ADMIN_ROLES, USER_ROLES } from '../../constants';
import { Roles } from '../../common/types/role'; import { Roles } from '../../common/types/role';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { makeErrorResponse } from '../../common/error/makeErrorResponse'; import { makeErrorResponse } from '../../common/error/makeErrorResponse';
@ApiTags('tasks') @ApiTags('tasks')
@Controller('tasks') @Controller('tasks')
export class TasksController { export class TasksController {
private readonly logger = new Logger(TasksController.name);
constructor(private readonly taskService: TasksService) {} constructor(private readonly taskService: TasksService) {}
@ApiResponse({ @ApiResponse({
@ -91,6 +92,23 @@ export class TasksController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -102,7 +120,8 @@ export class TasksController {
// RoleGuardでroleの文字列に想定外の文字列や重複がないことは担保されているためここでは型変換のみ行う // RoleGuardでroleの文字列に想定外の文字列や重複がないことは担保されているためここでは型変換のみ行う
const roles = role.split(' ') as Roles[]; const roles = role.split(' ') as Roles[];
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const { limit, offset, status } = body; const { limit, offset, status } = body;
const paramName = isTaskListSortableAttribute(body.paramName ?? '') const paramName = isTaskListSortableAttribute(body.paramName ?? '')
@ -164,13 +183,29 @@ export class TasksController {
): Promise<AudioNextResponse> { ): Promise<AudioNextResponse> {
const { endedFileId } = param; const { endedFileId } = param;
const accessToken = retrieveAuthorizationToken(req) as string; const accessToken = retrieveAuthorizationToken(req);
if (!accessToken) { if (!accessToken) {
throw new HttpException( throw new HttpException(
makeErrorResponse('E000107'), makeErrorResponse('E000107'),
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -179,7 +214,8 @@ export class TasksController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const nextFileId = await this.taskService.getNextTask( const nextFileId = await this.taskService.getNextTask(
context, context,
@ -241,6 +277,23 @@ export class TasksController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -253,7 +306,8 @@ export class TasksController {
// RoleGuardでroleの文字列に想定外の文字列や重複がないことは担保されているためここでは型変換のみ行う // RoleGuardでroleの文字列に想定外の文字列や重複がないことは担保されているためここでは型変換のみ行う
const roles = role.split(' ') as Roles[]; const roles = role.split(' ') as Roles[];
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.taskService.checkout(context, param.audioFileId, roles, userId); await this.taskService.checkout(context, param.audioFileId, roles, userId);
return {}; return {};
@ -311,6 +365,23 @@ export class TasksController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -320,7 +391,8 @@ export class TasksController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.taskService.checkin(context, audioFileId, userId); await this.taskService.checkin(context, audioFileId, userId);
return {}; return {};
@ -378,6 +450,23 @@ export class TasksController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -389,7 +478,8 @@ export class TasksController {
// RoleGuardでroleの文字列に想定外の文字列や重複がないことは担保されているためここでは型変換のみ行う // RoleGuardでroleの文字列に想定外の文字列や重複がないことは担保されているためここでは型変換のみ行う
const roles = role.split(' ') as Roles[]; const roles = role.split(' ') as Roles[];
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.taskService.cancel(context, audioFileId, userId, roles); await this.taskService.cancel(context, audioFileId, userId, roles);
return {}; return {};
@ -447,6 +537,23 @@ export class TasksController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -456,7 +563,8 @@ export class TasksController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.taskService.suspend(context, audioFileId, userId); await this.taskService.suspend(context, audioFileId, userId);
return {}; return {};
@ -513,6 +621,23 @@ export class TasksController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -522,7 +647,8 @@ export class TasksController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.taskService.backup(context, audioFileId, userId); await this.taskService.backup(context, audioFileId, userId);
return {}; return {};
@ -585,6 +711,23 @@ export class TasksController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -596,7 +739,8 @@ export class TasksController {
// RoleGuardでroleの文字列に想定外の文字列や重複がないことは担保されているためここでは型変換のみ行う // RoleGuardでroleの文字列に想定外の文字列や重複がないことは担保されているためここでは型変換のみ行う
const roles = role.split(' ') as Roles[]; const roles = role.split(' ') as Roles[];
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.taskService.changeCheckoutPermission( await this.taskService.changeCheckoutPermission(
context, context,

View File

@ -63,7 +63,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
expect( expect(
await service.tasksService.getTasks( await service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[ADMIN_ROLES.ADMIN, USER_ROLES.NONE], [ADMIN_ROLES.ADMIN, USER_ROLES.NONE],
offset, offset,
@ -138,7 +138,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
await expect( await expect(
service.tasksService.getTasks( service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[ADMIN_ROLES.ADMIN, USER_ROLES.NONE], [ADMIN_ROLES.ADMIN, USER_ROLES.NONE],
offset, offset,
@ -180,7 +180,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
await expect( await expect(
service.tasksService.getTasks( service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[ADMIN_ROLES.ADMIN, USER_ROLES.NONE], [ADMIN_ROLES.ADMIN, USER_ROLES.NONE],
offset, offset,
@ -266,7 +266,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
await expect( await expect(
service.tasksService.getTasks( service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[ADMIN_ROLES.ADMIN, USER_ROLES.NONE], [ADMIN_ROLES.ADMIN, USER_ROLES.NONE],
offset, offset,
@ -310,7 +310,7 @@ describe('TasksService', () => {
const paramName = 'JOB_NUMBER'; const paramName = 'JOB_NUMBER';
const direction = 'ASC'; const direction = 'ASC';
const result = await service.tasksService.getTasks( const result = await service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[USER_ROLES.AUTHOR], [USER_ROLES.AUTHOR],
offset, offset,
@ -393,7 +393,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
await expect( await expect(
service.tasksService.getTasks( service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[USER_ROLES.AUTHOR], [USER_ROLES.AUTHOR],
offset, offset,
@ -438,7 +438,7 @@ describe('TasksService', () => {
const paramName = 'JOB_NUMBER'; const paramName = 'JOB_NUMBER';
const direction = 'ASC'; const direction = 'ASC';
const result = await service.tasksService.getTasks( const result = await service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[USER_ROLES.TYPIST], [USER_ROLES.TYPIST],
offset, offset,
@ -521,7 +521,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
await expect( await expect(
service.tasksService.getTasks( service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[USER_ROLES.TYPIST], [USER_ROLES.TYPIST],
offset, offset,
@ -563,7 +563,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
await expect( await expect(
service.tasksService.getTasks( service.tasksService.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
userId, userId,
[ADMIN_ROLES.ADMIN, USER_ROLES.NONE], [ADMIN_ROLES.ADMIN, USER_ROLES.NONE],
offset, offset,
@ -623,7 +623,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
const { tasks, total } = await service.getTasks( const { tasks, total } = await service.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
externalId, externalId,
[ADMIN_ROLES.ADMIN, USER_ROLES.NONE], [ADMIN_ROLES.ADMIN, USER_ROLES.NONE],
offset, offset,
@ -681,7 +681,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
const { tasks, total } = await service.getTasks( const { tasks, total } = await service.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
external_id, external_id,
[USER_ROLES.AUTHOR], [USER_ROLES.AUTHOR],
offset, offset,
@ -753,7 +753,7 @@ describe('TasksService', () => {
const direction = 'ASC'; const direction = 'ASC';
const { tasks, total } = await service.getTasks( const { tasks, total } = await service.getTasks(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
external_id, external_id,
[USER_ROLES.AUTHOR], [USER_ROLES.AUTHOR],
offset, offset,
@ -839,7 +839,7 @@ describe('changeCheckoutPermission', () => {
NotificationhubService, NotificationhubService,
); );
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'typist-user-2', typistUserId: typistUserId_2 }], [{ typistName: 'typist-user-2', typistUserId: typistUserId_2 }],
'author-user-external-id', 'author-user-external-id',
@ -856,7 +856,7 @@ describe('changeCheckoutPermission', () => {
const resultTask = await getTask(source, taskId); const resultTask = await getTask(source, taskId);
// 通知処理が想定通りの引数で呼ばれているか確認 // 通知処理が想定通りの引数で呼ばれているか確認
expect(NotificationHubService.notify).toHaveBeenCalledWith( expect(NotificationHubService.notify).toHaveBeenCalledWith(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
[`user_${typistUserId_2}`], [`user_${typistUserId_2}`],
{ {
authorId: 'MY_AUTHOR_ID', authorId: 'MY_AUTHOR_ID',
@ -922,7 +922,7 @@ describe('changeCheckoutPermission', () => {
NotificationhubService, NotificationhubService,
); );
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'USER_GROUP_B', typistGroupId: userGroupId_2 }], [{ typistName: 'USER_GROUP_B', typistGroupId: userGroupId_2 }],
'author-user-external-id', 'author-user-external-id',
@ -940,7 +940,7 @@ describe('changeCheckoutPermission', () => {
const resultTask = await getTask(source, taskId); const resultTask = await getTask(source, taskId);
// 通知処理が想定通りの引数で呼ばれているか確認 // 通知処理が想定通りの引数で呼ばれているか確認
expect(NotificationHubService.notify).toHaveBeenCalledWith( expect(NotificationHubService.notify).toHaveBeenCalledWith(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
[`user_${typistUserId_2}`], [`user_${typistUserId_2}`],
{ {
authorId: 'MY_AUTHOR_ID', authorId: 'MY_AUTHOR_ID',
@ -992,7 +992,7 @@ describe('changeCheckoutPermission', () => {
await createCheckoutPermissions(source, taskId, undefined, userGroupId); await createCheckoutPermissions(source, taskId, undefined, userGroupId);
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[], [],
'author-user-external-id', 'author-user-external-id',
@ -1045,7 +1045,7 @@ describe('changeCheckoutPermission', () => {
try { try {
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'not-exist-user', typistUserId: 999 }], [{ typistName: 'not-exist-user', typistUserId: 999 }],
'author-user-external-id', 'author-user-external-id',
@ -1111,7 +1111,7 @@ describe('changeCheckoutPermission', () => {
try { try {
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'not-verified-user', typistUserId: typistUserId_2 }], [{ typistName: 'not-verified-user', typistUserId: typistUserId_2 }],
'author-user-external-id', 'author-user-external-id',
@ -1171,7 +1171,7 @@ describe('changeCheckoutPermission', () => {
try { try {
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'not-exist-user-group', typistGroupId: 999 }], [{ typistName: 'not-exist-user-group', typistGroupId: 999 }],
'author-user-external-id', 'author-user-external-id',
@ -1213,7 +1213,7 @@ describe('changeCheckoutPermission', () => {
try { try {
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'typist-user', typistUserId: typistUserId }], [{ typistName: 'typist-user', typistUserId: typistUserId }],
'author-user-external-id', 'author-user-external-id',
@ -1265,7 +1265,7 @@ describe('changeCheckoutPermission', () => {
try { try {
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'typist-user', typistUserId: typistUserId }], [{ typistName: 'typist-user', typistUserId: typistUserId }],
'author-user-external-id', 'author-user-external-id',
@ -1317,7 +1317,7 @@ describe('changeCheckoutPermission', () => {
try { try {
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'typist-user', typistUserId: typistUserId }], [{ typistName: 'typist-user', typistUserId: typistUserId }],
'author-user-external-id', 'author-user-external-id',
@ -1383,7 +1383,7 @@ describe('changeCheckoutPermission', () => {
try { try {
await service.changeCheckoutPermission( await service.changeCheckoutPermission(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
[{ typistName: 'typist-user-2', typistUserId: typistUserId_2 }], [{ typistName: 'typist-user-2', typistUserId: typistUserId_2 }],
'author-user-external-id', 'author-user-external-id',
@ -1460,7 +1460,7 @@ describe('checkout', () => {
const initTask = await getTask(source, taskId); const initTask = await getTask(source, taskId);
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['typist'], ['typist'],
'typist-user-external-id', 'typist-user-external-id',
@ -1520,7 +1520,7 @@ describe('checkout', () => {
const initTask = await getTask(source, taskId); const initTask = await getTask(source, taskId);
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['typist'], ['typist'],
'typist-user-external-id', 'typist-user-external-id',
@ -1573,7 +1573,7 @@ describe('checkout', () => {
const initTask = await getTask(source, taskId); const initTask = await getTask(source, taskId);
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['typist'], ['typist'],
'typist-user-external-id', 'typist-user-external-id',
@ -1625,7 +1625,7 @@ describe('checkout', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
try { try {
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['typist'], ['typist'],
'typist-user-external-id', 'typist-user-external-id',
@ -1672,7 +1672,7 @@ describe('checkout', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
try { try {
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['typist'], ['typist'],
'typist-user-external-id', 'typist-user-external-id',
@ -1733,7 +1733,7 @@ describe('checkout', () => {
try { try {
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
audioFileId, audioFileId,
['typist'], ['typist'],
'typist-user-external-id', 'typist-user-external-id',
@ -1798,7 +1798,7 @@ describe('checkout', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
2, 2,
['typist'], ['typist'],
'typist-user-external-id2', 'typist-user-external-id2',
@ -1839,7 +1839,7 @@ describe('checkout', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
expect( expect(
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['author'], ['author'],
'author-user-external-id', 'author-user-external-id',
@ -1873,7 +1873,7 @@ describe('checkout', () => {
expect( expect(
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['author'], ['author'],
'author-user-external-id', 'author-user-external-id',
@ -1896,7 +1896,7 @@ describe('checkout', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
try { try {
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['author'], ['author'],
'author-user-external-id', 'author-user-external-id',
@ -1937,7 +1937,7 @@ describe('checkout', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
try { try {
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['author'], ['author'],
'author-user-external-id', 'author-user-external-id',
@ -1968,7 +1968,7 @@ describe('checkout', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
try { try {
await service.checkout( await service.checkout(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
['none'], ['none'],
'none-user-external-id', 'none-user-external-id',
@ -2043,7 +2043,7 @@ describe('checkin', () => {
const initTask = await getTask(source, taskId); const initTask = await getTask(source, taskId);
await service.checkin( await service.checkin(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
'typist-user-external-id', 'typist-user-external-id',
); );
@ -2089,7 +2089,11 @@ describe('checkin', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.checkin(makeContext('trackingId'), 1, 'typist-user-external-id'), service.checkin(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1,
'typist-user-external-id',
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST),
); );
@ -2137,7 +2141,11 @@ describe('checkin', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.checkin(makeContext('trackingId'), 1, 'typist-user-external-id'), service.checkin(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1,
'typist-user-external-id',
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST),
); );
@ -2169,7 +2177,11 @@ describe('checkin', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.checkin(makeContext('trackingId'), 1, 'typist-user-external-id'), service.checkin(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1,
'typist-user-external-id',
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010603'), HttpStatus.NOT_FOUND), new HttpException(makeErrorResponse('E010603'), HttpStatus.NOT_FOUND),
); );
@ -2231,7 +2243,7 @@ describe('suspend', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.suspend( await service.suspend(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
'typist-user-external-id', 'typist-user-external-id',
); );
@ -2276,7 +2288,11 @@ describe('suspend', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.suspend(makeContext('trackingId'), 1, 'typist-user-external-id'), service.suspend(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1,
'typist-user-external-id',
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST),
); );
@ -2324,7 +2340,11 @@ describe('suspend', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.checkin(makeContext('trackingId'), 1, 'typist-user-external-id'), service.checkin(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1,
'typist-user-external-id',
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST),
); );
@ -2356,7 +2376,11 @@ describe('suspend', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.checkin(makeContext('trackingId'), 1, 'typist-user-external-id'), service.checkin(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1,
'typist-user-external-id',
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010603'), HttpStatus.NOT_FOUND), new HttpException(makeErrorResponse('E010603'), HttpStatus.NOT_FOUND),
); );
@ -2419,7 +2443,7 @@ describe('cancel', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.cancel( await service.cancel(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
'typist-user-external-id', 'typist-user-external-id',
['typist', 'standard'], ['typist', 'standard'],
@ -2468,7 +2492,7 @@ describe('cancel', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.cancel( await service.cancel(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
'typist-user-external-id', 'typist-user-external-id',
['typist', 'standard'], ['typist', 'standard'],
@ -2520,7 +2544,7 @@ describe('cancel', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.cancel( await service.cancel(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
'typist-user-external-id', 'typist-user-external-id',
['admin', 'author'], ['admin', 'author'],
@ -2571,7 +2595,7 @@ describe('cancel', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.cancel( await service.cancel(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
'typist-user-external-id', 'typist-user-external-id',
['admin', 'author'], ['admin', 'author'],
@ -2620,10 +2644,12 @@ describe('cancel', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.cancel(makeContext('trackingId'), 1, 'typist-user-external-id', [ service.cancel(
'admin', makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
'author', 1,
]), 'typist-user-external-id',
['admin', 'author'],
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST),
); );
@ -2671,10 +2697,12 @@ describe('cancel', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.cancel(makeContext('trackingId'), 1, 'typist-user-external-id', [ service.cancel(
'typist', makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
'standard', 1,
]), 'typist-user-external-id',
['typist', 'standard'],
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010601'), HttpStatus.BAD_REQUEST),
); );
@ -2706,10 +2734,12 @@ describe('cancel', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await expect( await expect(
service.cancel(makeContext('trackingId'), 1, 'typist-user-external-id', [ service.cancel(
'typist', makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
'standard', 1,
]), 'typist-user-external-id',
['typist', 'standard'],
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010603'), HttpStatus.NOT_FOUND), new HttpException(makeErrorResponse('E010603'), HttpStatus.NOT_FOUND),
); );
@ -2774,7 +2804,7 @@ describe('cancel', () => {
NotificationhubService, NotificationhubService,
); );
await service.cancel( await service.cancel(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
'typist-user-external-id', 'typist-user-external-id',
['typist', 'standard'], ['typist', 'standard'],
@ -2791,7 +2821,7 @@ describe('cancel', () => {
expect(permisions[0].user_id).toEqual(typistUserId); expect(permisions[0].user_id).toEqual(typistUserId);
// 通知処理が想定通りの引数で呼ばれているか確認 // 通知処理が想定通りの引数で呼ばれているか確認
expect(NotificationHubService.notify).toHaveBeenCalledWith( expect(NotificationHubService.notify).toHaveBeenCalledWith(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
[`user_${typistUserId}`], [`user_${typistUserId}`],
{ {
authorId: 'AUTHOR_ID', authorId: 'AUTHOR_ID',
@ -2884,7 +2914,7 @@ describe('cancel', () => {
NotificationhubService, NotificationhubService,
); );
await service.cancel( await service.cancel(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
external_id, external_id,
role.split(' ') as Roles[], role.split(' ') as Roles[],
@ -2901,7 +2931,7 @@ describe('cancel', () => {
expect(permisions[0].user_id).toEqual(autoRoutingTypistUserId); expect(permisions[0].user_id).toEqual(autoRoutingTypistUserId);
// 通知処理が想定通りの引数で呼ばれているか確認 // 通知処理が想定通りの引数で呼ばれているか確認
expect(NotificationHubService.notify).toHaveBeenCalledWith( expect(NotificationHubService.notify).toHaveBeenCalledWith(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
[`user_${autoRoutingTypistUserId}`], [`user_${autoRoutingTypistUserId}`],
{ {
authorId: 'AUTHOR_ID', authorId: 'AUTHOR_ID',
@ -2956,7 +2986,7 @@ describe('cancel', () => {
NotificationhubService, NotificationhubService,
); );
await service.cancel( await service.cancel(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
1, 1,
external_id, external_id,
role.split(' ') as Roles[], role.split(' ') as Roles[],
@ -3030,7 +3060,7 @@ describe('backup', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.backup( await service.backup(
makeContext(admin.external_id), makeContext(admin.external_id, 'xxx.xxx.xxx.xxx', 'requestId'),
audioFileId, audioFileId,
admin.external_id, admin.external_id,
); );
@ -3082,7 +3112,7 @@ describe('backup', () => {
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
await service.backup( await service.backup(
makeContext(admin.external_id), makeContext(admin.external_id, 'xxx.xxx.xxx.xxx', 'requestId'),
audioFileId, audioFileId,
admin.external_id, admin.external_id,
); );
@ -3135,7 +3165,7 @@ describe('backup', () => {
try { try {
await service.backup( await service.backup(
makeContext(admin.external_id), makeContext(admin.external_id, 'xxx.xxx.xxx.xxx', 'requestId'),
audioFileId, audioFileId,
admin.external_id, admin.external_id,
); );
@ -3190,7 +3220,7 @@ describe('backup', () => {
try { try {
await service.backup( await service.backup(
makeContext(admin.external_id), makeContext(admin.external_id, 'xxx.xxx.xxx.xxx', 'requestId'),
9999, // 存在しないタスクID 9999, // 存在しないタスクID
admin.external_id, admin.external_id,
); );
@ -3251,7 +3281,7 @@ describe('backup', () => {
try { try {
await service.backup( await service.backup(
makeContext(admin.external_id), makeContext(admin.external_id, 'xxx.xxx.xxx.xxx', 'requestId'),
audioFileId, audioFileId,
admin.external_id, admin.external_id,
); );
@ -3344,7 +3374,11 @@ describe('getNextTask', () => {
await createCheckoutPermissions(source, taskId2, typistUserId); await createCheckoutPermissions(source, taskId2, typistUserId);
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const nextAudioFileId = await service.getNextTask( const nextAudioFileId = await service.getNextTask(
context, context,
@ -3416,7 +3450,11 @@ describe('getNextTask', () => {
await createCheckoutPermissions(source, taskId2, typistUserId); await createCheckoutPermissions(source, taskId2, typistUserId);
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const nextAudioFileId = await service.getNextTask( const nextAudioFileId = await service.getNextTask(
context, context,
@ -3488,7 +3526,11 @@ describe('getNextTask', () => {
await createCheckoutPermissions(source, taskId2, typistUserId); await createCheckoutPermissions(source, taskId2, typistUserId);
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const nextAudioFileId = await service.getNextTask( const nextAudioFileId = await service.getNextTask(
context, context,
@ -3560,7 +3602,11 @@ describe('getNextTask', () => {
await createCheckoutPermissions(source, taskId2, typistUserId); await createCheckoutPermissions(source, taskId2, typistUserId);
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const nextAudioFileId = await service.getNextTask( const nextAudioFileId = await service.getNextTask(
context, context,
@ -3632,7 +3678,11 @@ describe('getNextTask', () => {
await createCheckoutPermissions(source, taskId2, typistUserId); await createCheckoutPermissions(source, taskId2, typistUserId);
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const nextAudioFileId = await service.getNextTask( const nextAudioFileId = await service.getNextTask(
context, context,
@ -3680,7 +3730,11 @@ describe('getNextTask', () => {
await createCheckoutPermissions(source, taskId1, typistUserId); await createCheckoutPermissions(source, taskId1, typistUserId);
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const nextAudioFileId = await service.getNextTask( const nextAudioFileId = await service.getNextTask(
context, context,
@ -3727,7 +3781,11 @@ describe('getNextTask', () => {
await createCheckoutPermissions(source, taskId1, typistUserId); await createCheckoutPermissions(source, taskId1, typistUserId);
const service = module.get<TasksService>(TasksService); const service = module.get<TasksService>(TasksService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
// 実行結果が正しいか確認 // 実行結果が正しいか確認
try { try {

View File

@ -3,6 +3,7 @@ import {
Get, Get,
HttpException, HttpException,
HttpStatus, HttpStatus,
Logger,
Req, Req,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
@ -21,13 +22,14 @@ import { RoleGuard } from '../../common/guards/role/roleguards';
import { ADMIN_ROLES } from '../../constants'; import { ADMIN_ROLES } from '../../constants';
import { retrieveAuthorizationToken } from '../../common/http/helper'; import { retrieveAuthorizationToken } from '../../common/http/helper';
import { Request } from 'express'; import { Request } from 'express';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { TemplatesService } from './templates.service'; import { TemplatesService } from './templates.service';
import { makeErrorResponse } from '../../common/error/makeErrorResponse'; import { makeErrorResponse } from '../../common/error/makeErrorResponse';
@ApiTags('templates') @ApiTags('templates')
@Controller('templates') @Controller('templates')
export class TemplatesController { export class TemplatesController {
private readonly logger = new Logger(TemplatesController.name);
constructor(private readonly templatesService: TemplatesService) {} constructor(private readonly templatesService: TemplatesService) {}
@ApiResponse({ @ApiResponse({
@ -63,6 +65,22 @@ export class TemplatesController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -72,7 +90,9 @@ export class TemplatesController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const templates = await this.templatesService.getTemplates(context, userId); const templates = await this.templatesService.getTemplates(context, userId);
return { templates }; return { templates };

View File

@ -35,7 +35,11 @@ describe('getTemplates', () => {
const service = module.get<TemplatesService>(TemplatesService); const service = module.get<TemplatesService>(TemplatesService);
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { account, admin } = await makeTestAccount(source, { tier: 5 }); const { account, admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const template1 = await createTemplateFile( const template1 = await createTemplateFile(
source, source,
@ -76,7 +80,11 @@ describe('getTemplates', () => {
const service = module.get<TemplatesService>(TemplatesService); const service = module.get<TemplatesService>(TemplatesService);
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { admin } = await makeTestAccount(source, { tier: 5 }); const { admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
const templates = await service.getTemplates(context, admin.external_id); const templates = await service.getTemplates(context, admin.external_id);
@ -94,7 +102,11 @@ describe('getTemplates', () => {
const service = module.get<TemplatesService>(TemplatesService); const service = module.get<TemplatesService>(TemplatesService);
// 第五階層のアカウント作成 // 第五階層のアカウント作成
const { admin } = await makeTestAccount(source, { tier: 5 }); const { admin } = await makeTestAccount(source, { tier: 5 });
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//DBアクセスに失敗するようにする //DBアクセスに失敗するようにする
const typistGroupService = module.get<TemplateFilesRepositoryService>( const typistGroupService = module.get<TemplateFilesRepositoryService>(

View File

@ -1,14 +1,24 @@
import { Controller, HttpStatus, Get } from '@nestjs/common'; import {
Controller,
HttpStatus,
Get,
Logger,
HttpException,
Req,
} from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { TermsService } from '../terms/terms.service'; import { TermsService } from '../terms/terms.service';
import { ErrorResponse } from '../../common/error/types/types'; import { ErrorResponse } from '../../common/error/types/types';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { GetTermsInfoResponse } from './types/types'; import { GetTermsInfoResponse } from './types/types';
import { v4 as uuidv4 } from 'uuid'; import { makeErrorResponse } from '../../common/error/makeErrorResponse';
import { Request } from 'express';
@ApiTags('terms') @ApiTags('terms')
@Controller('terms') @Controller('terms')
export class TermsController { export class TermsController {
private readonly logger = new Logger(TermsController.name);
constructor( constructor(
private readonly termsService: TermsService, //private readonly cryptoService: CryptoService, private readonly termsService: TermsService, //private readonly cryptoService: CryptoService,
) {} ) {}
@ -25,8 +35,24 @@ export class TermsController {
type: ErrorResponse, type: ErrorResponse,
}) })
@ApiOperation({ operationId: 'getTermsInfo' }) @ApiOperation({ operationId: 'getTermsInfo' })
async getTermsInfo(): Promise<GetTermsInfoResponse> { async getTermsInfo(@Req() req: Request): Promise<GetTermsInfoResponse> {
const context = makeContext(uuidv4()); const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const termsInfo = await this.termsService.getTermsInfo(context); const termsInfo = await this.termsService.getTermsInfo(context);

View File

@ -39,7 +39,7 @@ describe('利用規約取得', () => {
await createTermInfo(source, 'DPA', 'v1.0'); await createTermInfo(source, 'DPA', 'v1.0');
await createTermInfo(source, 'DPA', 'v1.2'); await createTermInfo(source, 'DPA', 'v1.2');
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const result = await service.getTermsInfo(context); const result = await service.getTermsInfo(context);
expect(result[0].documentType).toBe('EULA'); expect(result[0].documentType).toBe('EULA');
@ -55,7 +55,7 @@ describe('利用規約取得', () => {
const module = await makeTestingModule(source); const module = await makeTestingModule(source);
if (!module) fail(); if (!module) fail();
const service = module.get<TermsService>(TermsService); const service = module.get<TermsService>(TermsService);
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getTermsInfo(context)).rejects.toEqual( await expect(service.getTermsInfo(context)).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),
@ -70,7 +70,7 @@ describe('利用規約取得', () => {
if (!module) fail(); if (!module) fail();
const service = module.get<TermsService>(TermsService); const service = module.get<TermsService>(TermsService);
await createTermInfo(source, 'DPA', 'v1.0'); await createTermInfo(source, 'DPA', 'v1.0');
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getTermsInfo(context)).rejects.toEqual( await expect(service.getTermsInfo(context)).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),
@ -85,7 +85,7 @@ describe('利用規約取得', () => {
if (!module) fail(); if (!module) fail();
const service = module.get<TermsService>(TermsService); const service = module.get<TermsService>(TermsService);
await createTermInfo(source, 'PrivacyNotice', 'v1.0'); await createTermInfo(source, 'PrivacyNotice', 'v1.0');
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getTermsInfo(context)).rejects.toEqual( await expect(service.getTermsInfo(context)).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),
@ -100,7 +100,7 @@ describe('利用規約取得', () => {
if (!module) fail(); if (!module) fail();
const service = module.get<TermsService>(TermsService); const service = module.get<TermsService>(TermsService);
await createTermInfo(source, 'EULA', 'v1.0'); await createTermInfo(source, 'EULA', 'v1.0');
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.getTermsInfo(context)).rejects.toEqual( await expect(service.getTermsInfo(context)).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),

View File

@ -5,6 +5,7 @@ import {
HttpException, HttpException,
HttpStatus, HttpStatus,
Ip, Ip,
Logger,
Post, Post,
Query, Query,
Req, Req,
@ -52,13 +53,13 @@ import {
} from '../../common/types/sort'; } from '../../common/types/sort';
import { ADMIN_ROLES, TIERS } from '../../constants'; import { ADMIN_ROLES, TIERS } from '../../constants';
import { RoleGuard } from '../../common/guards/role/roleguards'; import { RoleGuard } from '../../common/guards/role/roleguards';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { UserRoles } from '../../common/types/role'; import { UserRoles } from '../../common/types/role';
import { v4 as uuidv4 } from 'uuid';
@ApiTags('users') @ApiTags('users')
@Controller('users') @Controller('users')
export class UsersController { export class UsersController {
private readonly logger = new Logger(UsersController.name);
constructor( constructor(
private readonly usersService: UsersService, private readonly usersService: UsersService,
private readonly authService: AuthService, private readonly authService: AuthService,
@ -81,8 +82,27 @@ export class UsersController {
}) })
@ApiOperation({ operationId: 'confirmUser' }) @ApiOperation({ operationId: 'confirmUser' })
@Post('confirm') @Post('confirm')
async confirmUser(@Body() body: ConfirmRequest): Promise<ConfirmResponse> { async confirmUser(
const context = makeContext(uuidv4()); @Body() body: ConfirmRequest,
@Req() req: Request,
): Promise<ConfirmResponse> {
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.usersService.confirmUser(context, body.token); await this.usersService.confirmUser(context, body.token);
return {}; return {};
@ -107,8 +127,25 @@ export class UsersController {
@Post('confirm/initpassword') @Post('confirm/initpassword')
async confirmUserAndInitPassword( async confirmUserAndInitPassword(
@Body() body: ConfirmRequest, @Body() body: ConfirmRequest,
@Req() req: Request,
): Promise<ConfirmResponse> { ): Promise<ConfirmResponse> {
const context = makeContext(uuidv4()); const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.usersService.confirmUserAndInitPassword(context, body.token); await this.usersService.confirmUserAndInitPassword(context, body.token);
return {}; return {};
} }
@ -137,13 +174,29 @@ export class UsersController {
@Get() @Get()
async getUsers(@Req() req: Request): Promise<GetUsersResponse> { async getUsers(@Req() req: Request): Promise<GetUsersResponse> {
const accessToken = retrieveAuthorizationToken(req); const accessToken = retrieveAuthorizationToken(req);
if (!accessToken) { if (!accessToken) {
throw new HttpException( throw new HttpException(
makeErrorResponse('E000107'), makeErrorResponse('E000107'),
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -152,7 +205,8 @@ export class UsersController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const users = await this.usersService.getUsers(context, userId); const users = await this.usersService.getUsers(context, userId);
return { users }; return { users };
@ -209,6 +263,23 @@ export class UsersController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -218,7 +289,8 @@ export class UsersController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
//ユーザ作成処理 //ユーザ作成処理
await this.usersService.createUser( await this.usersService.createUser(
@ -268,6 +340,23 @@ export class UsersController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -277,7 +366,8 @@ export class UsersController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
return await this.usersService.getRelations(context, userId); return await this.usersService.getRelations(context, userId);
} }
@ -322,6 +412,23 @@ export class UsersController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -330,7 +437,8 @@ export class UsersController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
//型チェック //型チェック
if ( if (
@ -386,6 +494,23 @@ export class UsersController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -394,7 +519,8 @@ export class UsersController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const { direction, paramName } = await this.usersService.getSortCriteria( const { direction, paramName } = await this.usersService.getSortCriteria(
context, context,
@ -456,6 +582,23 @@ export class UsersController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -465,7 +608,8 @@ export class UsersController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.usersService.updateUser( await this.usersService.updateUser(
context, context,
@ -528,6 +672,23 @@ export class UsersController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -537,7 +698,8 @@ export class UsersController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.usersService.allocateLicense( await this.usersService.allocateLicense(
context, context,
body.userId, body.userId,
@ -591,6 +753,23 @@ export class UsersController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -600,7 +779,8 @@ export class UsersController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.usersService.deallocateLicense(context, body.userId); await this.usersService.deallocateLicense(context, body.userId);
return {}; return {};
@ -628,6 +808,7 @@ export class UsersController {
@Post('/accepted-version') @Post('/accepted-version')
async updateAcceptedVersion( async updateAcceptedVersion(
@Body() body: UpdateAcceptedVersionRequest, @Body() body: UpdateAcceptedVersionRequest,
@Req() req: Request,
): Promise<UpdateAcceptedVersionResponse> { ): Promise<UpdateAcceptedVersionResponse> {
const { const {
idToken, idToken,
@ -636,7 +817,23 @@ export class UsersController {
acceptedDPAVersion, acceptedDPAVersion,
} = body; } = body;
const context = makeContext(uuidv4()); const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const context = makeContext('anonymous', ip, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const verifiedIdToken = await this.authService.getVerifiedIdToken( const verifiedIdToken = await this.authService.getVerifiedIdToken(
context, context,
@ -685,13 +882,30 @@ export class UsersController {
@UseGuards(AuthGuard) @UseGuards(AuthGuard)
@Get('me') @Get('me')
async getMyUser(@Req() req: Request): Promise<GetMyUserResponse> { async getMyUser(@Req() req: Request): Promise<GetMyUserResponse> {
const accessToken = retrieveAuthorizationToken(req) as string; const accessToken = retrieveAuthorizationToken(req);
if (!accessToken) { if (!accessToken) {
throw new HttpException( throw new HttpException(
makeErrorResponse('E000107'), makeErrorResponse('E000107'),
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -700,7 +914,8 @@ export class UsersController {
); );
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const userName = await this.usersService.getUserName(context, userId); const userName = await this.usersService.getUserName(context, userId);
return { userName }; return { userName };
} }

View File

@ -97,7 +97,7 @@ describe('UsersService.confirmUser', () => {
// account id:1, user id: 2のトークン // account id:1, user id: 2のトークン
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await service.confirmUser(context, token); await service.confirmUser(context, token);
//result //result
const resultUser = await getUser(source, userId); const resultUser = await getUser(source, userId);
@ -141,7 +141,7 @@ describe('UsersService.confirmUser', () => {
if (!module) fail(); if (!module) fail();
const token = 'invalid.id.token'; const token = 'invalid.id.token';
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.confirmUser(context, token)).rejects.toEqual( await expect(service.confirmUser(context, token)).rejects.toEqual(
new HttpException(makeErrorResponse('E000101'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E000101'), HttpStatus.BAD_REQUEST),
); );
@ -177,7 +177,7 @@ describe('UsersService.confirmUser', () => {
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.confirmUser(context, token)).rejects.toEqual( await expect(service.confirmUser(context, token)).rejects.toEqual(
new HttpException(makeErrorResponse('E010202'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010202'), HttpStatus.BAD_REQUEST),
); );
@ -189,7 +189,7 @@ describe('UsersService.confirmUser', () => {
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw';
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect(service.confirmUser(context, token)).rejects.toEqual( await expect(service.confirmUser(context, token)).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),
@ -246,7 +246,7 @@ describe('UsersService.confirmUserAndInitPassword', () => {
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw';
expect( expect(
await service.confirmUserAndInitPassword( await service.confirmUserAndInitPassword(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
token, token,
), ),
).toEqual(undefined); ).toEqual(undefined);
@ -295,7 +295,10 @@ describe('UsersService.confirmUserAndInitPassword', () => {
); );
const token = 'invalid.id.token'; const token = 'invalid.id.token';
await expect( await expect(
service.confirmUserAndInitPassword(makeContext('trackingId'), token), service.confirmUserAndInitPassword(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
token,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E000101'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E000101'), HttpStatus.BAD_REQUEST),
); );
@ -348,7 +351,10 @@ describe('UsersService.confirmUserAndInitPassword', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw';
await expect( await expect(
service.confirmUserAndInitPassword(makeContext('trackingId'), token), service.confirmUserAndInitPassword(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
token,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException(makeErrorResponse('E010202'), HttpStatus.BAD_REQUEST), new HttpException(makeErrorResponse('E010202'), HttpStatus.BAD_REQUEST),
); );
@ -398,7 +404,10 @@ describe('UsersService.confirmUserAndInitPassword', () => {
const token = const token =
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw'; 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEsInVzZXJJZCI6MiwiZW1haWwiOiJ4eHhAeHh4Lnh4eCIsImlhdCI6MTAwMDAwMDAwMCwiZXhwIjo5MDAwMDAwMDAwfQ.26L6BdNg-3TbyKT62PswlJ6RPMkcTtHzlDXW2Uo9XbMPVSrl2ObcuS6EcXjFFN2DEfNTKbqX_zevIWMpHOAdLNgGhk528nLrBrNvPASqtTjvW9muxMXpjUdjRVkmVbOylBHWW3YpWL9JEbJQ7rAzWDfaIdPhMovdaxumnZt_UwnlnrdaVPLACW7tkH_laEcAU507iSiM4mqxxG8FuTs34t6PEdwRuzZAQPN2IOPYNSvGNdJYryPacSeSNZ_z1xeBYXLOLQfOBZzyTReYDOhXdikhrNUbxjgnZQlSXBCVMlZ9PH42bHfp-LJIeJzW0yqnF6oLklvJP-fo8eW0k5iDOw';
await expect( await expect(
service.confirmUserAndInitPassword(makeContext('trackingId'), token), service.confirmUserAndInitPassword(
makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
token,
),
).rejects.toEqual( ).rejects.toEqual(
new HttpException( new HttpException(
makeErrorResponse('E009999'), makeErrorResponse('E009999'),
@ -482,7 +491,7 @@ describe('UsersService.createUser', () => {
expect( expect(
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -570,7 +579,7 @@ describe('UsersService.createUser', () => {
expect( expect(
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -661,7 +670,7 @@ describe('UsersService.createUser', () => {
expect( expect(
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -749,7 +758,7 @@ describe('UsersService.createUser', () => {
expect( expect(
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -842,7 +851,7 @@ describe('UsersService.createUser', () => {
try { try {
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -862,7 +871,7 @@ describe('UsersService.createUser', () => {
// ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認 // ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認
expect(b2cService.deleteUser).toBeCalledWith( expect(b2cService.deleteUser).toBeCalledWith(
externalId, externalId,
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
); );
}); });
@ -929,7 +938,7 @@ describe('UsersService.createUser', () => {
try { try {
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -954,7 +963,7 @@ describe('UsersService.createUser', () => {
// ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認 // ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認
expect(b2cService.deleteUser).toBeCalledWith( expect(b2cService.deleteUser).toBeCalledWith(
externalId, externalId,
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
); );
}); });
@ -1010,7 +1019,7 @@ describe('UsersService.createUser', () => {
try { try {
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -1089,7 +1098,7 @@ describe('UsersService.createUser', () => {
try { try {
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -1170,7 +1179,7 @@ describe('UsersService.createUser', () => {
expect( expect(
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -1211,7 +1220,7 @@ describe('UsersService.createUser', () => {
try { try {
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -1307,7 +1316,7 @@ describe('UsersService.createUser', () => {
try { try {
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -1335,7 +1344,7 @@ describe('UsersService.createUser', () => {
// ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認 // ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認
expect(b2cService.deleteUser).toBeCalledWith( expect(b2cService.deleteUser).toBeCalledWith(
externalId, externalId,
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
); );
}); });
@ -1396,7 +1405,7 @@ describe('UsersService.createUser', () => {
try { try {
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -1422,7 +1431,7 @@ describe('UsersService.createUser', () => {
// ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認 // ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認
expect(b2cService.deleteUser).toBeCalledWith( expect(b2cService.deleteUser).toBeCalledWith(
externalId, externalId,
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
); );
}); });
@ -1488,7 +1497,7 @@ describe('UsersService.createUser', () => {
try { try {
await service.createUser( await service.createUser(
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
adminExternalId, adminExternalId,
name, name,
role, role,
@ -1512,7 +1521,7 @@ describe('UsersService.createUser', () => {
// ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認 // ADB2Cに作成したユーザーを削除するメソッドが呼ばれていることを確認
expect(b2cService.deleteUser).toBeCalledWith( expect(b2cService.deleteUser).toBeCalledWith(
externalId, externalId,
makeContext('trackingId'), makeContext('trackingId', 'xxx.xxx.xxx.xxx', 'requestId'),
); );
}); });
}); });
@ -1635,7 +1644,7 @@ describe('UsersService.getUsers', () => {
}, },
]; ];
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect(await service.getUsers(context, externalId_author)).toEqual( expect(await service.getUsers(context, externalId_author)).toEqual(
expectedUsers, expectedUsers,
); );
@ -1754,7 +1763,7 @@ describe('UsersService.getUsers', () => {
}, },
]; ];
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect(await service.getUsers(context, external_id1)).toEqual( expect(await service.getUsers(context, external_id1)).toEqual(
expectedUsers, expectedUsers,
); );
@ -1778,7 +1787,7 @@ describe('UsersService.getUsers', () => {
prompt: false, prompt: false,
}); });
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await expect( await expect(
service.getUsers(context, 'externalId_failed'), service.getUsers(context, 'externalId_failed'),
@ -1806,7 +1815,7 @@ describe('UsersService.getUsers', () => {
prompt: false, prompt: false,
}); });
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await expect(service.getUsers(context, externalId_author)).rejects.toEqual( await expect(service.getUsers(context, externalId_author)).rejects.toEqual(
new HttpException(makeErrorResponse('E009999'), HttpStatus.NOT_FOUND), new HttpException(makeErrorResponse('E009999'), HttpStatus.NOT_FOUND),
@ -1831,7 +1840,7 @@ describe('UsersService.updateSortCriteria', () => {
configMockValue, configMockValue,
sortCriteriaRepositoryMockValue, sortCriteriaRepositoryMockValue,
); );
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.updateSortCriteria( await service.updateSortCriteria(
@ -1862,7 +1871,7 @@ describe('UsersService.updateSortCriteria', () => {
configMockValue, configMockValue,
sortCriteriaRepositoryMockValue, sortCriteriaRepositoryMockValue,
); );
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.updateSortCriteria(context, 'AUTHOR_ID', 'ASC', 'external_id'), service.updateSortCriteria(context, 'AUTHOR_ID', 'ASC', 'external_id'),
@ -1894,7 +1903,7 @@ describe('UsersService.updateSortCriteria', () => {
configMockValue, configMockValue,
sortCriteriaRepositoryMockValue, sortCriteriaRepositoryMockValue,
); );
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.updateSortCriteria(context, 'AUTHOR_ID', 'ASC', 'external_id'), service.updateSortCriteria(context, 'AUTHOR_ID', 'ASC', 'external_id'),
@ -1924,7 +1933,7 @@ describe('UsersService.getSortCriteria', () => {
configMockValue, configMockValue,
sortCriteriaRepositoryMockValue, sortCriteriaRepositoryMockValue,
); );
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect(await service.getSortCriteria(context, 'external_id')).toEqual({ expect(await service.getSortCriteria(context, 'external_id')).toEqual({
direction: 'ASC', direction: 'ASC',
@ -1953,7 +1962,7 @@ describe('UsersService.getSortCriteria', () => {
configMockValue, configMockValue,
sortCriteriaRepositoryMockValue, sortCriteriaRepositoryMockValue,
); );
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.getSortCriteria(context, 'external_id'), service.getSortCriteria(context, 'external_id'),
@ -1988,7 +1997,7 @@ describe('UsersService.getSortCriteria', () => {
configMockValue, configMockValue,
sortCriteriaRepositoryMockValue, sortCriteriaRepositoryMockValue,
); );
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.getSortCriteria(context, 'external_id'), service.getSortCriteria(context, 'external_id'),
@ -2048,7 +2057,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.updateUser( await service.updateUser(
@ -2107,7 +2116,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.updateUser( await service.updateUser(
@ -2166,7 +2175,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.updateUser( await service.updateUser(
@ -2225,7 +2234,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.updateUser( await service.updateUser(
@ -2284,7 +2293,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.updateUser( await service.updateUser(
@ -2343,7 +2352,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.updateUser( service.updateUser(
@ -2392,7 +2401,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.updateUser( await service.updateUser(
@ -2451,7 +2460,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
expect( expect(
await service.updateUser( await service.updateUser(
@ -2510,7 +2519,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.updateUser( service.updateUser(
@ -2570,7 +2579,7 @@ describe('UsersService.updateUser', () => {
}); });
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const context = makeContext(`uuidv4`); const context = makeContext(`uuidv4`, 'xxx.xxx.xxx.xxx', 'requestId');
await expect( await expect(
service.updateUser( service.updateUser(
@ -2618,7 +2627,7 @@ describe('UsersService.updateAcceptedVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 5, tier: 5,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.updateAcceptedVersion( await service.updateAcceptedVersion(
@ -2639,7 +2648,7 @@ describe('UsersService.updateAcceptedVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 4, tier: 4,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.updateAcceptedVersion( await service.updateAcceptedVersion(
@ -2662,7 +2671,7 @@ describe('UsersService.updateAcceptedVersion', () => {
const { admin } = await makeTestAccount(source, { const { admin } = await makeTestAccount(source, {
tier: 4, tier: 4,
}); });
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await expect( await expect(
@ -2705,7 +2714,7 @@ describe('UsersService.getUserName', () => {
try { try {
const module = await makeTestingModule(source); const module = await makeTestingModule(source);
if (!module) fail(); if (!module) fail();
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.getUserName(context, 'external_id'); await service.getUserName(context, 'external_id');
@ -2800,7 +2809,7 @@ describe('UsersService.getRelations', () => {
expect(workflows[3].author_id).toBe(user2); expect(workflows[3].author_id).toBe(user2);
} }
const context = makeContext(external_id); const context = makeContext(external_id, 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const relations = await service.getRelations(context, external_id); const relations = await service.getRelations(context, external_id);
@ -2863,7 +2872,7 @@ describe('UsersService.getRelations', () => {
expect(workflows[0].author_id).toBe(user2); expect(workflows[0].author_id).toBe(user2);
} }
const context = makeContext(external_id); const context = makeContext(external_id, 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
const relations = await service.getRelations(context, external_id); const relations = await service.getRelations(context, external_id);
@ -2889,7 +2898,7 @@ describe('UsersService.getRelations', () => {
try { try {
const module = await makeTestingModule(source); const module = await makeTestingModule(source);
if (!module) fail(); if (!module) fail();
const context = makeContext(uuidv4()); const context = makeContext(uuidv4(), 'xxx.xxx.xxx.xxx', 'requestId');
const service = module.get<UsersService>(UsersService); const service = module.get<UsersService>(UsersService);
await service.getRelations(context, 'external_id'); await service.getRelations(context, 'external_id');

View File

@ -545,12 +545,7 @@ export class UsersService {
// DBから取得したユーザーの外部IDをもとにADB2Cからユーザーを取得する // DBから取得したユーザーの外部IDをもとにADB2Cからユーザーを取得する
const externalIds = dbUsers.map((x) => x.external_id); const externalIds = dbUsers.map((x) => x.external_id);
const trackingId = new Context(context.trackingId); const adb2cUsers = await this.adB2cService.getUsers(context, externalIds);
const adb2cUsers = await this.adB2cService.getUsers(
// TODO: 外部連携以外のログ強化時に、ContollerからContextを取得するように修正する
trackingId,
externalIds,
);
// DBから取得した各ユーザーをもとにADB2C情報をマージしライセンス情報を算出 // DBから取得した各ユーザーをもとにADB2C情報をマージしライセンス情報を算出
const users = dbUsers.map((dbUser): User => { const users = dbUsers.map((dbUser): User => {

View File

@ -4,6 +4,7 @@ import {
Get, Get,
HttpException, HttpException,
HttpStatus, HttpStatus,
Logger,
Param, Param,
Post, Post,
Req, Req,
@ -33,13 +34,14 @@ import { RoleGuard } from '../../common/guards/role/roleguards';
import { ADMIN_ROLES } from '../../constants'; import { ADMIN_ROLES } from '../../constants';
import { retrieveAuthorizationToken } from '../../common/http/helper'; import { retrieveAuthorizationToken } from '../../common/http/helper';
import { Request } from 'express'; import { Request } from 'express';
import { makeContext } from '../../common/log'; import { makeContext, retrieveRequestId, retrieveIp } from '../../common/log';
import { WorkflowsService } from './workflows.service'; import { WorkflowsService } from './workflows.service';
import { makeErrorResponse } from '../../common/error/makeErrorResponse'; import { makeErrorResponse } from '../../common/error/makeErrorResponse';
@ApiTags('workflows') @ApiTags('workflows')
@Controller('workflows') @Controller('workflows')
export class WorkflowsController { export class WorkflowsController {
private readonly logger = new Logger(WorkflowsController.name);
constructor(private readonly workflowsService: WorkflowsService) {} constructor(private readonly workflowsService: WorkflowsService) {}
@ApiResponse({ @ApiResponse({
@ -75,6 +77,21 @@ export class WorkflowsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -84,7 +101,8 @@ export class WorkflowsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
const workflows = await this.workflowsService.getWorkflows(context, userId); const workflows = await this.workflowsService.getWorkflows(context, userId);
@ -134,6 +152,21 @@ export class WorkflowsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -143,7 +176,8 @@ export class WorkflowsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.workflowsService.createWorkflow( await this.workflowsService.createWorkflow(
context, context,
userId, userId,
@ -201,6 +235,21 @@ export class WorkflowsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -210,7 +259,8 @@ export class WorkflowsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.workflowsService.updateWorkflow( await this.workflowsService.updateWorkflow(
context, context,
userId, userId,
@ -267,6 +317,21 @@ export class WorkflowsController {
HttpStatus.UNAUTHORIZED, HttpStatus.UNAUTHORIZED,
); );
} }
const ip = retrieveIp(req);
if (!ip) {
throw new HttpException(
makeErrorResponse('E000401'),
HttpStatus.UNAUTHORIZED,
);
}
const requestId = retrieveRequestId(req);
if (!requestId) {
throw new HttpException(
makeErrorResponse('E000501'),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const decodedAccessToken = jwt.decode(accessToken, { json: true }); const decodedAccessToken = jwt.decode(accessToken, { json: true });
if (!decodedAccessToken) { if (!decodedAccessToken) {
throw new HttpException( throw new HttpException(
@ -276,7 +341,8 @@ export class WorkflowsController {
} }
const { userId } = decodedAccessToken as AccessToken; const { userId } = decodedAccessToken as AccessToken;
const context = makeContext(userId); const context = makeContext(userId, requestId);
this.logger.log(`[${context.getTrackingId()}] ip : ${ip}`);
await this.workflowsService.deleteWorkflow(context, userId, workflowId); await this.workflowsService.deleteWorkflow(context, userId, workflowId);
return {}; return {};
} }

View File

@ -118,7 +118,11 @@ describe('getWorkflows', () => {
await createWorkflowTypist(source, workflow3.id, undefined, userGroupId); await createWorkflowTypist(source, workflow3.id, undefined, userGroupId);
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//作成したデータを確認 //作成したデータを確認
{ {
@ -190,7 +194,11 @@ describe('getWorkflows', () => {
const { admin } = await makeTestAccount(source, { tier: 5 }); const { admin } = await makeTestAccount(source, { tier: 5 });
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
overrideAdB2cService(service, { overrideAdB2cService(service, {
getUsers: async () => [], getUsers: async () => [],
@ -212,7 +220,11 @@ describe('getWorkflows', () => {
const { account, admin } = await makeTestAccount(source, { tier: 5 }); const { account, admin } = await makeTestAccount(source, { tier: 5 });
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//DBアクセスに失敗するようにする //DBアクセスに失敗するようにする
const templatesService = module.get<WorkflowsRepositoryService>( const templatesService = module.get<WorkflowsRepositoryService>(
@ -292,7 +304,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.createWorkflow( await service.createWorkflow(
context, context,
@ -357,7 +373,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.createWorkflow( await service.createWorkflow(
context, context,
@ -421,7 +441,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.createWorkflow( await service.createWorkflow(
context, context,
@ -479,7 +503,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.createWorkflow( await service.createWorkflow(
context, context,
@ -543,7 +571,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
// 同一AuthorIDのワークフローを作成 // 同一AuthorIDのワークフローを作成
await service.createWorkflow( await service.createWorkflow(
@ -616,7 +648,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
await service.createWorkflow( await service.createWorkflow(
@ -673,7 +709,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -734,7 +774,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -794,7 +838,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -856,7 +904,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -924,7 +976,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -986,7 +1042,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -1057,7 +1117,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -1124,7 +1188,11 @@ describe('createWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//DBアクセスに失敗するようにする //DBアクセスに失敗するようにする
const templatesService = module.get<WorkflowsRepositoryService>( const templatesService = module.get<WorkflowsRepositoryService>(
@ -1243,7 +1311,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.updateWorkflow( await service.updateWorkflow(
context, context,
@ -1333,7 +1405,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.updateWorkflow( await service.updateWorkflow(
context, context,
@ -1422,7 +1498,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.updateWorkflow( await service.updateWorkflow(
context, context,
@ -1505,7 +1585,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.updateWorkflow( await service.updateWorkflow(
context, context,
@ -1608,7 +1692,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.updateWorkflow( await service.updateWorkflow(
context, context,
@ -1687,7 +1775,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -1730,7 +1822,11 @@ describe('updateWorkflow', () => {
}); });
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -1804,7 +1900,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -1873,7 +1973,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -1941,7 +2045,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -2016,7 +2124,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -2097,7 +2209,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -2172,7 +2288,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -2241,7 +2361,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -2310,7 +2434,11 @@ describe('updateWorkflow', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//DBアクセスに失敗するようにする //DBアクセスに失敗するようにする
const workflowsRepositoryService = module.get<WorkflowsRepositoryService>( const workflowsRepositoryService = module.get<WorkflowsRepositoryService>(
@ -2401,7 +2529,11 @@ describe('deleteWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.deleteWorkflow(context, admin.external_id, workflow.id); await service.deleteWorkflow(context, admin.external_id, workflow.id);
@ -2452,7 +2584,11 @@ describe('deleteWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
await service.deleteWorkflow(context, admin.external_id, workflow1.id); await service.deleteWorkflow(context, admin.external_id, workflow1.id);
@ -2503,7 +2639,11 @@ describe('deleteWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -2578,7 +2718,11 @@ describe('deleteWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//実行結果を確認 //実行結果を確認
try { try {
@ -2633,7 +2777,11 @@ describe('deleteWorkflows', () => {
} }
const service = module.get<WorkflowsService>(WorkflowsService); const service = module.get<WorkflowsService>(WorkflowsService);
const context = makeContext(admin.external_id); const context = makeContext(
admin.external_id,
'xxx.xxx.xxx.xxx',
'requestId',
);
//DBアクセスに失敗するようにする //DBアクセスに失敗するようにする
const workflowsRepositoryService = module.get<WorkflowsRepositoryService>( const workflowsRepositoryService = module.get<WorkflowsRepositoryService>(