[express-ipfilter]

- winston daily log 와 같이 사용할 경우 error 라고 해서 uncaughtException 로그에 남지는 않는다.

- npm install express-ipfilter

- 다른 라우터보다 위에 위치해야 합니다.



var ipfilter = require('express-ipfilter').IpFilter;
var IpDeniedError = require('express-ipfilter').IpDeniedError;

// 차단, 허용할 특정 아이피 목록
var ips = ['192.168.0.10', '192.168.0.11'];

// 범위 사용 예시
// 192.168.0.10 ~ 192.168.0.20 안의 범위와 192.168.0.100 차단 or 허용, 
// var ips = [['192.168.0.10', '192.168.0.20'], '192.168.0.100'];

// ips 목록의 ip들만 허용
app.use(ipfilter(ips, {mode: 'allow'}));

// ips 목록의 ip들 차단
// app.use(ipfilter(ips));

app.use(function(err, req, res, _next) {
    //console.log('Error handler', err);
    res.send('Access Denied');                     // page view 'Access Denied'
    if(err instanceof IpDeniedError){
      res.status(401).end();
    }else{
      res.status(err.status || 500).end();
    }
    // res.render('error', {
    //   message: 'You shall not pass',
    //   error: err
    // });
});

..........

app.get('/', function(req, res){
    res.send('allowed IP');
});


'Programming > Node.js' 카테고리의 다른 글

[Node.js] winston Daily 로그 남기기  (0) 2018.05.21

[Node.js Daily 로그 남기기]


- 인터넷에서 검색해서 적용해 봤는데 모듈이 업데이트 되면서 약간 바뀌었는지 filename , datePattern 부분이 제대로 적용이 되지 않았음.

- 나머지 부분은 다른게 없고 filename , datePattern 두 부분만 바뀌었음.


var winston = require('winston'); // 로그 처리 모듈 var winstonDaily = require('winston-daily-rotate-file'); // 로그 일별 처리 모듈

// Date Format 선택
// moment 모듈 설치 필요
function timeStampFormat() {
    return moment().format('YYYY-MM-DD HH:mm:ss.SSS ZZ'); // '2018-01-01 12:12:12.500 +0900'
};

// 그냥 
const tsFormat = () => (new Date()).toLocaleTimeString();      // '2018-01-01'

// 로그 설정
var logger = new (winston.Logger)({
    transports: [
        new (winstonDaily)({                                              // 로그 파일 설정
                name: 'info-file',
                filename: './logs/app_%DATE%.log',                  // 파일 이름 (아래 설정한 날짜 형식이 %DATE% 위치에 들어간다)
                datePattern: 'YYYY-MM-DD',                           // 날짜 형식 (대문자여야 적용된다.)
                colorize: false,
                maxsize: 50000000,                                       // 로그 파일 하나의 용량 제한
                maxFiles: 1000,                                             // 로그 파일 개수 제한
                level: 'info', // info이상 파일 출력                      // 로그 레벨 지정
                showLevel: true,
                json: false,
                timestamp: timeStampFormat                          // 저장될 시간 형식
            }),
        new (winston.transports.Console)({                            // 콘솔 출력
                name: 'debug-console',
                colorize: true,
                level: 'debug', // debug이상 콘솔 출력
                showLevel: true,
                json: false,
                timestamp: timeStampFormat
        })     
    ],
    exceptionHandlers: [                                                  // uncaughtException 발생시 처리
        new (winstonDaily)({
                name: 'exception-file',
                filename: './logs/exception_%DATE%.log',
                datePattern: 'YYYY-MM-DD',
                colorize: false,
                maxsize: 50000000,
                maxFiles: 1000,
                level: 'error',
                showLevel: true,
                json: false,
                timestamp: timeStampFormat
        }),
        new (winston.transports.Console)({
                name: 'exception-console',
                colorize: true,
                level: 'debug',
                showLevel: true,
                json: false,
                timestamp: timeStampFormat
        })     
    ]
});


// 원하는 위치에 로그 삽입
...................
logger.info('Hello, World');
...................


* ./logs/ 위치에
app_2018-05-21.log
exception_2018-05-21.log

형식으로 로그 파일이 생성됨

출력 내용은 아래와 같은 형태.
2018-05-21 15:59:38.764 +0900 - info: Hello, World




'Programming > Node.js' 카테고리의 다른 글

[Node.js] express-ipfilter IP필터 모듈 사용하기  (2) 2018.05.23

[fabcar 예제 오류 발생]


* (2018.05.08) 새로 fabric-samples 프로젝트를 받아서 fabcar 예제를 진행할 경우 아래와 같은 오류가 발생합니다.


* startFabric.sh 실행 -> node enrollAdmin.js 실행 시 오류!


[user@localhost fabcar]$ node enrollAdmin.js module.js:549 throw err; ^ Error: Cannot find module './api.js' at Function.Module._resolveFilename (module.js:547:15) at Function.Module._load (module.js:474:25) at Module.require (module.js:596:17) at require (internal/module.js:11:18) at Object.<anonymous> (/home/user/go/src/github.com/hyperledger/fabric-samples/fabcar/node_modules/fabric-ca-client/lib/FabricCAClientImpl.js:19:11) at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js:663:10) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3)



[원인 파악 및 해결]


* 이유는 fabric-ca-client 의 FabricCAClientImpl.js 에서 api.js 를 사용하는데

  해당 위치 (./fabcar/node_modules/fabric-ca-client/lib/) 에 api.js 파일이 없습니다.


* fabric-ca-client 패키지를 확인해보니 최신버전이 1.1.0 -> 1.1.1 로 업데이트 되면서 내용이 약간씩 바뀌었으며 그로인해 필요한 파일들이 누락된듯 합니다.


* 따라서 저는 기존 1.1.0 버전 모듈로 다시 설치해서 문제를 해결했습니다.



<fabcar 폴더 안의 package.json 내용>

{ "name": "fabcar", "version": "1.0.0", "description": "Hyperledger Fabric Car Sample Application", "main": "fabcar.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "fabric-ca-client": "~1.1.0", "fabric-client": "~1.1.0", "grpc": "^1.6.0" }, "author": "Anthony O'Dowd", "license": "Apache-2.0", "keywords": [ "Hyperledger", "Fabric", "Car", "Sample", "Application" ] }


*fabcar 폴더 안에서 npm install --unsafe-perm 을 통해 package.json 에 입력된 모듈들을 자동으로 설치하게 됩니다.

* dependencies 항목에 fabric-ca-client 버전의 경우 틸드형식으로 지정되어 표시된 버전 마지막 자리의 최신버전으로 설치되게 됩니다.
(즉 현재 저상태로 실행하면 fabric-ca-client 버전은 1.1.1 이 설치됩니다.)

* 틸드형식을 제거하고 고정 버전을 설치하면 정상적으로 fabcar 예제를 테스트 하실 수 있습니다.
(node_modules 폴더를 삭제한 후 진행)

"name": "fabcar", "version": "1.0.0", "description": "Hyperledger Fabric Car Sample Application", "main": "fabcar.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "fabric-ca-client": "1.1.0", "fabric-client": "~1.1.0", "grpc": "^1.6.0" }, "author": "Anthony O'Dowd", "license": "Apache-2.0", "keywords": [ "Hyperledger", "Fabric", "Car", "Sample", "Application" ] }


[user@localhost fabcar]$ npm install --unsafe-perm ....... [user@localhost fabcar]$ node enrollAdmin.js

* 추후에 fabric-ca-client 모듈이 안정화 되면 신경쓰지 않으셔도 될 듯 합니다.


* 기존 모듈에서 api.js 파일을 복사해 와도 가능할 것으로 보이지만 그 외 어떤 다른파일이 누락되어 있을지 알 수 없어서

  이전버전을 설치하는 방향으로 진행했습니다.



--------------------------------------------------------------

(English)


['fabcar' example error]


* (2018.05.08) If you take a new fabric-samples project and proceed with the fabcar example, the following error occurs.


* Run 'startFabric.sh' -> error when running 'node enrollAdmin.js'


[user@localhost fabcar]$ node enrollAdmin.js module.js:549 throw err; ^ Error: Cannot find module './api.js' at Function.Module._resolveFilename (module.js:547:15) at Function.Module._load (module.js:474:25) at Module.require (module.js:596:17) at require (internal/module.js:11:18) at Object.<anonymous> (/home/user/go/src/github.com/hyperledger/fabric-samples/fabcar/node_modules/fabric-ca-client/lib/FabricCAClientImpl.js:19:11) at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js:663:10) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3)


[Cause & Solution]


* There is no api.js file in that location (./fabcar/node_modules/fabric-ca-client/lib/).


* Checking the fabric-ca-client package shows that the latest version has been updated with 1.1.0 -> 1.1.1, and the contents have been slightly changed, so that the necessary files are missing.


* So I reinstalled it with the existing 1.1.0 version module and solved the problem.


<'package.json' contents in fabcar folder>

{ "name": "fabcar", "version": "1.0.0", "description": "Hyperledger Fabric Car Sample Application", "main": "fabcar.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "fabric-ca-client": "~1.1.0", "fabric-client": "~1.1.0", "grpc": "^1.6.0" }, "author": "Anthony O'Dowd", "license": "Apache-2.0", "keywords": [ "Hyperledger", "Fabric", "Car", "Sample", "Application" ] }


* 'npm install --unsafe-perm' inside the 'fabcar' folder will automatically install the modules in package.json. * Dependencies item will be installed with the latest version of fabric-ca-client(1.1.1). (by tiled version range : ~1.1.0)
* If you remove the tilde format and install the fixed version, you can test the fabcar example normally.    (proceed after deleting the node_modules folder)

{ "name": "fabcar", "version": "1.0.0", "description": "Hyperledger Fabric Car Sample Application", "main": "fabcar.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "fabric-ca-client": "1.1.0", "fabric-client": "~1.1.0", "grpc": "^1.6.0" }, "author": "Anthony O'Dowd", "license": "Apache-2.0", "keywords": [ "Hyperledger", "Fabric", "Car", "Sample", "Application" ] }


[user@localhost fabcar]$ npm install --unsafe-perm ....... [user@localhost fabcar]$ node enrollAdmin.js

* If the 'fabric-ca-client' module stabilizes later, you do not need to worry about it.


* It seems possible to copy the 'api.js' file from the existing module(1.1.0), but I could not figure out what other files were missing, so i proceeded to install the previous version.


+ Recent posts