serverpreconfigured 2.2.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ import { Request } from 'express';
2
+ export declare const BASE_LOG_PATH = "./logs";
3
+ export declare enum LogSeverity {
4
+ danger = "danger",
5
+ servere = "severe",
6
+ moderate = "moderate",
7
+ info = "info"
8
+ }
9
+ export interface SaveLogOptions {
10
+ userId?: number;
11
+ data: string;
12
+ severity: LogSeverity;
13
+ penTestSuspcion?: boolean;
14
+ req?: Request;
15
+ ip?: string;
16
+ url?: string;
17
+ }
18
+ export declare function saveInternalErrorLog(req: Request, error: any, options?: {
19
+ penTestSuspcion?: boolean;
20
+ severity?: LogSeverity;
21
+ }): Promise<void>;
22
+ export declare function saveLog(options: SaveLogOptions): {
23
+ fileName: string;
24
+ basePath: string;
25
+ };
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.saveLog = exports.saveInternalErrorLog = exports.LogSeverity = exports.BASE_LOG_PATH = void 0;
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const path_1 = __importDefault(require("path"));
18
+ exports.BASE_LOG_PATH = './logs';
19
+ var LogSeverity;
20
+ (function (LogSeverity) {
21
+ LogSeverity["danger"] = "danger";
22
+ LogSeverity["servere"] = "severe";
23
+ LogSeverity["moderate"] = "moderate";
24
+ LogSeverity["info"] = "info";
25
+ })(LogSeverity = exports.LogSeverity || (exports.LogSeverity = {}));
26
+ function stringfyError(err) {
27
+ const type = typeof (err);
28
+ if (type !== 'object')
29
+ return err.toString();
30
+ let ret = {};
31
+ for (let key of Object.keys(err)) {
32
+ let value = err[key];
33
+ ret[key] = typeof (value) == 'object' ? 'Is Object' : value.toString();
34
+ }
35
+ let retData = "";
36
+ try {
37
+ retData = JSON.stringify(ret);
38
+ }
39
+ catch (e) {
40
+ retData = "error on stringfy error data";
41
+ }
42
+ return retData;
43
+ }
44
+ function saveInternalErrorLog(req, error, options) {
45
+ var _a;
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ try {
48
+ const ip = req.ip;
49
+ const url = req.originalUrl;
50
+ //@ts-ignore
51
+ const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
52
+ let errorString = stringfyError(error);
53
+ saveLog({
54
+ ip: ip,
55
+ url: url,
56
+ userId: userId,
57
+ data: errorString,
58
+ severity: (options === null || options === void 0 ? void 0 : options.severity) || LogSeverity.info,
59
+ penTestSuspcion: options === null || options === void 0 ? void 0 : options.penTestSuspcion,
60
+ });
61
+ }
62
+ catch (e) {
63
+ console.log("Error ON Save Log", e);
64
+ }
65
+ });
66
+ }
67
+ exports.saveInternalErrorLog = saveInternalErrorLog;
68
+ function saveLog(options) {
69
+ if (!fs_1.default.existsSync(exports.BASE_LOG_PATH)) {
70
+ fs_1.default.mkdirSync(exports.BASE_LOG_PATH);
71
+ }
72
+ let basePath = exports.BASE_LOG_PATH;
73
+ if (options.userId) {
74
+ basePath = path_1.default.join(basePath, options.userId.toString());
75
+ }
76
+ else {
77
+ basePath = path_1.default.join(basePath, "unlogged");
78
+ }
79
+ if (!fs_1.default.existsSync(basePath)) {
80
+ fs_1.default.mkdirSync(basePath);
81
+ }
82
+ let fileName = path_1.default.join(basePath, `${getDateString(new Date())}.csv`);
83
+ let data = "";
84
+ if (fs_1.default.existsSync(fileName)) {
85
+ data = fs_1.default.readFileSync(fileName).toString() + "\n";
86
+ }
87
+ if (!data) {
88
+ data = 'Data;Severidade;Usuário;Dados;IP;URL;Supeita de Ataque\n';
89
+ }
90
+ data += `${new Date()};${options.severity};${options.userId || "Deslogado"};${options.data};${options.ip || "Não Informado"};${options.url || "Não Informado"};${options.penTestSuspcion ? "SIM" : "NÃO"}`;
91
+ fs_1.default.writeFileSync(fileName, data);
92
+ return {
93
+ fileName,
94
+ basePath,
95
+ };
96
+ }
97
+ exports.saveLog = saveLog;
98
+ function getDateString(d) {
99
+ const year = d.getFullYear();
100
+ const month = zerof(d.getMonth() + 1);
101
+ const day = zerof(d.getDate());
102
+ const hour = zerof(d.getHours());
103
+ return `${year}_${month}_${day}_${hour}`;
104
+ function zerof(n) {
105
+ if (n > 9)
106
+ return n.toString();
107
+ return `0${n}`;
108
+ }
109
+ }
@@ -8,17 +8,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.setUserDataMiddleware = void 0;
16
13
  const server_1 = require("../server");
17
14
  const server_2 = require("../server");
18
15
  const server_3 = require("../server");
19
- const env_1 = __importDefault(require("../settings/env"));
20
16
  const response_1 = require("../utils/response");
21
- const DEBUG = env_1.default.NODE_ENV === 'development' ? true : false;
22
17
  function setUserDataMiddleware(req, res, next) {
23
18
  return __awaiter(this, void 0, void 0, function* () {
24
19
  if (!(0, server_1.userIsLogged)(req))
@@ -1,3 +1,8 @@
1
+ import { LogSeverity } from "../logs/logs";
1
2
  export declare function JSONResponse(data: any, error?: any): string;
2
- export declare function sendIError(req: any, res: any, error?: any): any;
3
+ export interface SendIErrorOptions {
4
+ severity?: LogSeverity;
5
+ penTestSuspcion?: boolean;
6
+ }
7
+ export declare function sendIError(req: any, res: any, error?: any, options?: SendIErrorOptions): any;
3
8
  export declare function WSResponse(isOK: boolean, message?: string, errorMessage?: string, data?: any): string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WSResponse = exports.sendIError = exports.JSONResponse = void 0;
4
+ const logs_1 = require("../logs/logs");
4
5
  function JSONResponse(data, error) {
5
6
  return JSON.stringify({
6
7
  data,
@@ -10,8 +11,8 @@ function JSONResponse(data, error) {
10
11
  }
11
12
  exports.JSONResponse = JSONResponse;
12
13
  ;
13
- function sendIError(req, res, error) {
14
- console.log(error);
14
+ function sendIError(req, res, error, options) {
15
+ (0, logs_1.saveInternalErrorLog)(req, error, options);
15
16
  return res.status(500).send(JSONResponse("", "I-E"));
16
17
  }
17
18
  exports.sendIError = sendIError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serverpreconfigured",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
4
4
  "description": "\"Pre-configured server with authentication system and database integration\"",
5
5
  "main": "dist/server.js",
6
6
  "keywords": [
@@ -0,0 +1,97 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { Request } from 'express';
4
+ export const BASE_LOG_PATH='./logs';
5
+ export enum LogSeverity{
6
+ danger='danger',
7
+ servere='severe',
8
+ moderate='moderate',
9
+ info='info',
10
+ }
11
+ export interface SaveLogOptions{
12
+ userId?:number;
13
+ data:string;
14
+ severity:LogSeverity;
15
+ penTestSuspcion?:boolean;
16
+ req?:Request;
17
+ ip?:string;
18
+ url?:string;
19
+ }
20
+
21
+
22
+ function stringfyError(err:any):string{
23
+ const type=typeof(err);
24
+ if(type!=='object')
25
+ return err.toString();
26
+ let ret:any={};
27
+ for(let key of Object.keys(err)){
28
+ let value=err[key];
29
+ ret[key]=typeof(value)=='object'?'Is Object':value.toString();
30
+ }
31
+ let retData="";
32
+ try{
33
+ retData=JSON.stringify(ret);
34
+ }catch(e){
35
+ retData="error on stringfy error data";
36
+ }
37
+ return retData;
38
+ }
39
+ export async function saveInternalErrorLog(req:Request,error:any,options?:{penTestSuspcion?:boolean,severity?:LogSeverity}){
40
+ try{
41
+ const ip=req.ip;
42
+ const url=req.originalUrl;
43
+ //@ts-ignore
44
+ const userId=req.user?.id;
45
+ let errorString=stringfyError(error);
46
+ saveLog({
47
+ ip:ip,
48
+ url:url,
49
+ userId:userId,
50
+ data:errorString,
51
+ severity:options?.severity||LogSeverity.info,
52
+ penTestSuspcion:options?.penTestSuspcion,
53
+ });
54
+ }catch(e){
55
+ console.log("Error ON Save Log",e);
56
+ }
57
+ }
58
+ export function saveLog(options:SaveLogOptions){
59
+ if(!fs.existsSync(BASE_LOG_PATH)){
60
+ fs.mkdirSync(BASE_LOG_PATH);
61
+ }
62
+ let basePath=BASE_LOG_PATH;
63
+ if(options.userId){
64
+ basePath=path.join(basePath,options.userId.toString());
65
+ }else{
66
+ basePath=path.join(basePath,"unlogged");
67
+ }
68
+ if(!fs.existsSync(basePath)){
69
+ fs.mkdirSync(basePath);
70
+ }
71
+ let fileName=path.join(basePath,`${getDateString(new Date())}.csv`);
72
+ let data="";
73
+ if(fs.existsSync(fileName)){
74
+ data=fs.readFileSync(fileName).toString()+"\n";
75
+ }
76
+ if(!data){
77
+ data='Data;Severidade;Usuário;Dados;IP;URL;Supeita de Ataque\n';
78
+ }
79
+ data+=`${new Date()};${options.severity};${options.userId||"Deslogado"};${options.data};${options.ip||"Não Informado"};${options.url||"Não Informado"};${options.penTestSuspcion?"SIM":"NÃO"}`;
80
+ fs.writeFileSync(fileName,data);
81
+ return {
82
+ fileName,
83
+ basePath,
84
+ };
85
+ }
86
+ function getDateString(d:Date){
87
+ const year=d.getFullYear();
88
+ const month=zerof(d.getMonth()+1);
89
+ const day=zerof(d.getDate());
90
+ const hour=zerof(d.getHours());
91
+ return `${year}_${month}_${day}_${hour}`;
92
+ function zerof(n:number){
93
+ if(n>9)
94
+ return n.toString();
95
+ return `0${n}`;
96
+ }
97
+ }
@@ -1,10 +1,8 @@
1
1
  import { User, updateUserLastAction, userIsLogged } from "../server";
2
2
  import { JSONResponse } from "../server";
3
3
  import { getUserSessionData } from "../server";
4
-
5
- import ENV from "../settings/env";
6
4
  import { sendIError } from "../utils/response";
7
- const DEBUG=ENV.NODE_ENV==='development'?true:false;
5
+
8
6
  export async function setUserDataMiddleware(req:any,res:any,next:any){
9
7
  if(!userIsLogged(req))
10
8
  return res.status(401).send(JSONResponse({},"User Must Be Logged"));
@@ -1,3 +1,4 @@
1
+ import { LogSeverity, saveInternalErrorLog } from "../logs/logs";
1
2
  export function JSONResponse(data:any,error?:any){
2
3
  return JSON.stringify({
3
4
  data,
@@ -5,9 +6,13 @@ export function JSONResponse(data:any,error?:any){
5
6
  error,
6
7
  });
7
8
  };
9
+ export interface SendIErrorOptions{
10
+ severity?:LogSeverity,
11
+ penTestSuspcion?:boolean;
12
+ }
8
13
 
9
- export function sendIError(req:any,res:any,error?:any){
10
- console.log(error);
14
+ export function sendIError(req:any,res:any,error?:any,options?:SendIErrorOptions){
15
+ saveInternalErrorLog(req,error,options);
11
16
  return res.status(500).send(JSONResponse("","I-E"));
12
17
  }
13
18
  export function WSResponse(isOK:boolean,message:string='',errorMessage:string="",data:any={}):string{