serverpreconfigured 2.2.9 → 2.2.11

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.
@@ -6,5 +6,4 @@ export declare class User extends Model {
6
6
  is_active: boolean;
7
7
  password_hash: string;
8
8
  last_action: Date;
9
- static init(sequelize: any): void;
10
9
  }
@@ -3,18 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.User = void 0;
4
4
  const sequelize_1 = require("sequelize");
5
5
  const sequelize_2 = require("sequelize");
6
+ const database_1 = require("../database");
6
7
  class User extends sequelize_1.Model {
7
- static init(sequelize) {
8
- super.init({
9
- first_name: sequelize_2.DataTypes.STRING,
10
- email: sequelize_2.DataTypes.STRING,
11
- is_active: sequelize_2.DataTypes.BOOLEAN,
12
- password_hash: sequelize_2.DataTypes.STRING,
13
- last_action: sequelize_2.DataTypes.DATE,
14
- }, {
15
- sequelize: sequelize,
16
- tableName: 'spc_users',
17
- });
18
- }
19
8
  }
20
9
  exports.User = User;
10
+ User.init({
11
+ first_name: sequelize_2.DataTypes.STRING,
12
+ email: sequelize_2.DataTypes.STRING,
13
+ is_active: sequelize_2.DataTypes.BOOLEAN,
14
+ password_hash: sequelize_2.DataTypes.STRING,
15
+ last_action: sequelize_2.DataTypes.DATE,
16
+ }, {
17
+ sequelize: database_1.dataBase,
18
+ tableName: 'spc_users',
19
+ });
@@ -3,5 +3,4 @@ export declare class WebSocketAuth extends Model {
3
3
  token: string;
4
4
  expiration: Date;
5
5
  auth_connection_token: string;
6
- static init(sequelize: any): void;
7
6
  }
@@ -3,18 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WebSocketAuth = void 0;
4
4
  const sequelize_1 = require("sequelize");
5
5
  const sequelize_2 = require("sequelize");
6
+ const database_1 = require("../database");
6
7
  class WebSocketAuth extends sequelize_1.Model {
7
- static init(sequelize) {
8
- super.init({
9
- token: sequelize_2.DataTypes.STRING,
10
- expiration: sequelize_2.DataTypes.DATE,
11
- user_id: sequelize_2.DataTypes.INTEGER,
12
- is_active: sequelize_2.DataTypes.BOOLEAN,
13
- auth_connection_token: sequelize_2.DataTypes.STRING,
14
- }, {
15
- sequelize: sequelize,
16
- tableName: 'spc_wsauth'
17
- });
18
- }
19
8
  }
20
9
  exports.WebSocketAuth = WebSocketAuth;
10
+ WebSocketAuth.init({
11
+ token: sequelize_2.DataTypes.STRING,
12
+ expiration: sequelize_2.DataTypes.DATE,
13
+ user_id: sequelize_2.DataTypes.INTEGER,
14
+ is_active: sequelize_2.DataTypes.BOOLEAN,
15
+ auth_connection_token: sequelize_2.DataTypes.STRING,
16
+ }, {
17
+ sequelize: database_1.dataBase,
18
+ tableName: 'spc_wsauth'
19
+ });
@@ -63,6 +63,6 @@ router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function*
63
63
  }
64
64
  }));
65
65
  router.post('/getuser', auth_2.setUserDataMiddleware, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
66
- res.send((0, response_1.JSONResponse)({}, { email: req.user.email, id: req.user.id }));
66
+ res.send((0, response_1.JSONResponse)({ email: req.user.email, id: req.user.id }));
67
67
  }));
68
68
  exports.default = router;
@@ -10,12 +10,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.checkUserPassword = exports.changeUserPassword = exports.createUser = exports.isUserExist = exports.deleteUserById = exports.getUserIdByUserEmail = exports.getUserByEmail = exports.getUserById = exports.getUserSessionData = exports.updateUserLastAction = void 0;
13
- const database_1 = require("./../database/database");
14
13
  const User_1 = require("./../database/models/User");
15
14
  const password_1 = require("./password");
16
15
  const config_1 = require("../auth/config");
17
16
  const secureget_1 = require("../sessions/secureget");
18
- User_1.User.init(database_1.dataBase);
19
17
  function updateUserLastAction(user) {
20
18
  return __awaiter(this, void 0, void 0, function* () {
21
19
  try {
@@ -113,8 +111,8 @@ function changeUserPassword(email, password) {
113
111
  if (!user)
114
112
  throw "Unknwon User";
115
113
  let hash = yield (0, password_1.createArgon2Hash)(password);
116
- if (!hash)
117
- "Create Hash Error";
114
+ if (typeof (hash) !== "string")
115
+ throw "Create Hash Error";
118
116
  user.password_hash = hash;
119
117
  yield user.save();
120
118
  return user;
@@ -11,9 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.checkConnectionAuth = exports.authenticateWS = exports.checkWSAuthToken = exports.setWSAuthDataNewToken = exports.getWSAuthDataByUserId = void 0;
13
13
  const server_1 = require("../server");
14
- const server_2 = require("../server");
15
14
  const random_1 = require("./../utils/string/random");
16
- server_1.WebSocketAuth.init(server_2.dataBase);
17
15
  function getWSAuthDataByUserId(userId) {
18
16
  return __awaiter(this, void 0, void 0, function* () {
19
17
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serverpreconfigured",
3
- "version": "2.2.9",
3
+ "version": "2.2.11",
4
4
  "description": "\"Pre-configured server with authentication system and database integration\"",
5
5
  "main": "dist/server.js",
6
6
  "keywords": [
@@ -35,7 +35,7 @@
35
35
  "nodemon": "^2.0.15",
36
36
  "pg": "^8.7.3",
37
37
  "pg-hstore": "^2.3.4",
38
- "sequelize": "^7.0.0-alpha.9",
38
+ "sequelize": "^6.37.4",
39
39
  "sequelize-cli": "^6.4.1",
40
40
  "sucrase": "^3.20.3",
41
41
  "typescript": "^4.6.2"
@@ -1,5 +1,6 @@
1
1
  import { Model } from "sequelize";
2
2
  import { DataTypes } from "sequelize";
3
+ import { dataBase } from "../database";
3
4
 
4
5
  export class User extends Model{
5
6
  declare id:number;
@@ -8,20 +9,18 @@ export class User extends Model{
8
9
  declare is_active:boolean;
9
10
  declare password_hash:string;
10
11
  declare last_action:Date;
11
- static init(sequelize:any){
12
- super.init({
13
- first_name:DataTypes.STRING,
14
- email:DataTypes.STRING,
15
- is_active:DataTypes.BOOLEAN,
16
- password_hash:DataTypes.STRING,
17
- last_action:DataTypes.DATE,
18
- },
19
- {
20
- sequelize:sequelize,
21
- tableName: 'spc_users',
22
- }
23
- );
24
- }
25
12
  }
13
+ User.init({
14
+ first_name:DataTypes.STRING,
15
+ email:DataTypes.STRING,
16
+ is_active:DataTypes.BOOLEAN,
17
+ password_hash:DataTypes.STRING,
18
+ last_action:DataTypes.DATE,
19
+ },
20
+ {
21
+ sequelize:dataBase,
22
+ tableName: 'spc_users',
23
+ }
24
+ );
26
25
 
27
26
 
@@ -1,19 +1,19 @@
1
1
  import { Model } from "sequelize";
2
2
  import { DataTypes } from "sequelize";
3
+ import { dataBase } from "../database";
3
4
  export class WebSocketAuth extends Model{
4
5
  declare token:string;
5
6
  declare expiration:Date;
6
7
  declare auth_connection_token:string;
7
- static init(sequelize:any){
8
- super.init({
9
- token:DataTypes.STRING,
10
- expiration:DataTypes.DATE,
11
- user_id:DataTypes.INTEGER,
12
- is_active:DataTypes.BOOLEAN,
13
- auth_connection_token:DataTypes.STRING,
14
- },{
15
- sequelize:sequelize,
16
- tableName:'spc_wsauth'
17
- });
18
- }
19
- }
8
+ }
9
+
10
+ WebSocketAuth.init({
11
+ token:DataTypes.STRING,
12
+ expiration:DataTypes.DATE,
13
+ user_id:DataTypes.INTEGER,
14
+ is_active:DataTypes.BOOLEAN,
15
+ auth_connection_token:DataTypes.STRING,
16
+ },{
17
+ sequelize:dataBase,
18
+ tableName:'spc_wsauth'
19
+ });
@@ -11,7 +11,7 @@ export async function setUserDataMiddleware(req:any,res:any,next:any){
11
11
  return res.status(401).send(JSONResponse({},"User Must Be Logged"));
12
12
  try{
13
13
  const dealerEmail=getUserSessionData(req);
14
- const user:User=await User.findOne({where:{email:dealerEmail,is_active:true}});
14
+ const user=await User.findOne({where:{email:dealerEmail,is_active:true}});
15
15
  if(!user)
16
16
  throw "Unknown user";
17
17
  req.user=user;
@@ -34,7 +34,7 @@ router.post('/login',async (req,res)=>{
34
34
  try{
35
35
  const checkPass=await checkUserPassword(email,password);
36
36
  if(checkPass){
37
- const user:User=await User.findOne({where:{email:email}});
37
+ const user=await User.findOne({where:{email:email}});
38
38
  if(!user)
39
39
  throw "Dont find User";
40
40
  if(!user.is_active){
@@ -52,6 +52,6 @@ router.post('/login',async (req,res)=>{
52
52
  });
53
53
 
54
54
  router.post('/getuser',setUserDataMiddleware,async (req:any,res)=>{
55
- res.send(JSONResponse({},{email:req.user.email,id:req.user.id}));
55
+ res.send(JSONResponse({email:req.user.email,id:req.user.id}));
56
56
  });
57
57
  export default router;
@@ -1,10 +1,9 @@
1
- import {dataBase} from "./../database/database";
1
+
2
2
  import { User } from "./../database/models/User";
3
3
  import { createArgon2Hash,checkArgon2Password } from "./password";
4
4
  import {UserCreateInterface} from "./types";
5
5
  import {SESSION_LOGGED_DATA} from "../auth/config";
6
6
  import {getSessionValue} from "../sessions/secureget";
7
- User.init(dataBase);
8
7
 
9
8
  export async function updateUserLastAction(user:User){
10
9
  try{
@@ -80,8 +79,8 @@ export async function changeUserPassword(email:string,password:string):Promise<U
80
79
  if(!user)
81
80
  throw "Unknwon User";
82
81
  let hash=await createArgon2Hash(password);
83
- if(!hash)
84
- "Create Hash Error";
82
+ if(typeof(hash)!=="string")
83
+ throw "Create Hash Error";
85
84
  user.password_hash=hash;
86
85
  await user.save();
87
86
  return user;
@@ -1,7 +1,7 @@
1
1
  import { WebSocketAuth } from "../server";
2
- import { dataBase } from "../server";
2
+
3
3
  import {randomString} from "./../utils/string/random";
4
- WebSocketAuth.init(dataBase);
4
+
5
5
  export async function getWSAuthDataByUserId(userId:number):Promise<any>{
6
6
  try{
7
7
  let u=await WebSocketAuth.findOne({where:{user_id:userId.toString()}});
@@ -1,29 +0,0 @@
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
- addPath?: string;
14
- filePrefix?: string;
15
- penTestSuspcion?: boolean;
16
- req?: Request;
17
- ip?: string;
18
- url?: string;
19
- }
20
- export declare function stringfyError(err: any): string;
21
- export declare function getIpFromRequest(req: Request): string;
22
- export declare function saveInternalErrorLog(req: Request, error: any, options?: {
23
- penTestSuspcion?: boolean;
24
- severity?: LogSeverity;
25
- }): Promise<void>;
26
- export declare function saveLog(options: SaveLogOptions): {
27
- fileName: string;
28
- basePath: string;
29
- };
package/dist/logs/logs.js DELETED
@@ -1,132 +0,0 @@
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.getIpFromRequest = exports.stringfyError = 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 = stringfyObject(err, 0);
31
- return ret || "";
32
- function stringfyObject(obj, level = 0) {
33
- if (!obj)
34
- return "";
35
- if (typeof (obj) !== 'object')
36
- return obj.toString();
37
- if (level == 5)
38
- return "Is Object level max 8";
39
- let ret = {};
40
- for (let key of Object.keys(obj)) {
41
- let value = obj[key];
42
- //@ts-ignore
43
- ret[key] = typeof (value) == 'object' ? stringfyObject(value, level + 1).replaceAll('\\', '') : value === null || value === void 0 ? void 0 : value.toString();
44
- }
45
- return JSON.stringify(ret);
46
- }
47
- }
48
- exports.stringfyError = stringfyError;
49
- function getIpFromRequest(req) {
50
- //@
51
- let ips = (req.headers['cf-connecting-ip'] ||
52
- req.headers['x-real-ip'] ||
53
- req.headers['x-forwarded-for'] ||
54
- req.ip || '');
55
- if (typeof (ips) == 'string') {
56
- ips = ips.split(',');
57
- }
58
- return ips[0].trim();
59
- }
60
- exports.getIpFromRequest = getIpFromRequest;
61
- function saveInternalErrorLog(req, error, options) {
62
- var _a;
63
- return __awaiter(this, void 0, void 0, function* () {
64
- try {
65
- const ip = getIpFromRequest(req);
66
- const url = req.originalUrl;
67
- //@ts-ignore
68
- const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
69
- let errorString = stringfyError(error);
70
- saveLog({
71
- ip: ip,
72
- url: url,
73
- userId: userId,
74
- data: errorString,
75
- severity: (options === null || options === void 0 ? void 0 : options.severity) || LogSeverity.info,
76
- penTestSuspcion: options === null || options === void 0 ? void 0 : options.penTestSuspcion,
77
- });
78
- }
79
- catch (e) {
80
- console.log("Error ON Save Log", e);
81
- }
82
- });
83
- }
84
- exports.saveInternalErrorLog = saveInternalErrorLog;
85
- function saveLog(options) {
86
- if (!fs_1.default.existsSync(exports.BASE_LOG_PATH)) {
87
- fs_1.default.mkdirSync(exports.BASE_LOG_PATH);
88
- }
89
- let basePath = exports.BASE_LOG_PATH;
90
- if (options.addPath) {
91
- basePath = path_1.default.join(basePath, options.addPath);
92
- if (!fs_1.default.existsSync(basePath)) {
93
- fs_1.default.mkdirSync(basePath);
94
- }
95
- }
96
- if (options.userId) {
97
- basePath = path_1.default.join(basePath, options.userId.toString());
98
- }
99
- else {
100
- basePath = path_1.default.join(basePath, "unlogged");
101
- }
102
- if (!fs_1.default.existsSync(basePath)) {
103
- fs_1.default.mkdirSync(basePath);
104
- }
105
- let fileName = path_1.default.join(basePath, `${options.filePrefix ? options.filePrefix + '_' : ""}${getDateString(new Date())}.csv`);
106
- let data = "";
107
- if (fs_1.default.existsSync(fileName)) {
108
- data = fs_1.default.readFileSync(fileName).toString() + "\n";
109
- }
110
- if (!data) {
111
- data = 'Data;Severidade;Usuário;Dados;IP;URL;Supeita de Ataque\n';
112
- }
113
- 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"}`;
114
- fs_1.default.writeFileSync(fileName, data);
115
- return {
116
- fileName,
117
- basePath,
118
- };
119
- }
120
- exports.saveLog = saveLog;
121
- function getDateString(d) {
122
- const year = d.getFullYear();
123
- const month = zerof(d.getMonth() + 1);
124
- const day = zerof(d.getDate());
125
- const hour = zerof(d.getHours());
126
- return `${year}_${month}_${day}_${hour}`;
127
- function zerof(n) {
128
- if (n > 9)
129
- return n.toString();
130
- return `0${n}`;
131
- }
132
- }
package/src/logs/logs.ts DELETED
@@ -1,127 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { Request } from 'express';
4
- import axios from 'axios';
5
- export const BASE_LOG_PATH='./logs';
6
- export enum LogSeverity{
7
- danger='danger',
8
- servere='severe',
9
- moderate='moderate',
10
- info='info',
11
- }
12
- export interface SaveLogOptions{
13
- userId?:number;
14
- data:string;
15
- severity:LogSeverity;
16
- addPath?:string;
17
- filePrefix?:string;
18
- penTestSuspcion?:boolean;
19
- req?:Request;
20
- ip?:string;
21
- url?:string;
22
- }
23
-
24
-
25
- export function stringfyError(err:any):string{
26
- const type=typeof(err);
27
- if(type!=='object')
28
- return err.toString();
29
- let ret=stringfyObject(err,0);
30
- return ret||"";
31
- function stringfyObject(obj:any,level:number=0){
32
- if(!obj)
33
- return "";
34
- if(typeof(obj)!=='object')
35
- return obj.toString();
36
- if(level==5)
37
- return "Is Object level max 8";
38
- let ret:any={};
39
- for(let key of Object.keys(obj)){
40
- let value=obj[key];
41
- //@ts-ignore
42
- ret[key]=typeof(value)=='object'?stringfyObject(value,level+1).replaceAll('\\',''):value?.toString();
43
- }
44
- return JSON.stringify(ret);
45
- }
46
-
47
- }
48
-
49
-
50
- export function getIpFromRequest(req:Request){
51
- //@
52
- let ips = (
53
- req.headers['cf-connecting-ip'] ||
54
- req.headers['x-real-ip'] ||
55
- req.headers['x-forwarded-for'] ||
56
- req.ip || ''
57
- );
58
- if(typeof(ips)=='string'){
59
- ips=ips.split(',');
60
- }
61
- return ips[0].trim();
62
- }
63
- export async function saveInternalErrorLog(req:Request,error:any,options?:{penTestSuspcion?:boolean,severity?:LogSeverity}){
64
- try{
65
- const ip=getIpFromRequest(req);
66
- const url=req.originalUrl;
67
- //@ts-ignore
68
- const userId=req.user?.id;
69
- let errorString=stringfyError(error);
70
- saveLog({
71
- ip:ip,
72
- url:url,
73
- userId:userId,
74
- data:errorString,
75
- severity:options?.severity||LogSeverity.info,
76
- penTestSuspcion:options?.penTestSuspcion,
77
- });
78
- }catch(e){
79
- console.log("Error ON Save Log",e);
80
- }
81
- }
82
- export function saveLog(options:SaveLogOptions){
83
- if(!fs.existsSync(BASE_LOG_PATH)){
84
- fs.mkdirSync(BASE_LOG_PATH);
85
- }
86
- let basePath=BASE_LOG_PATH;
87
- if(options.addPath){
88
- basePath=path.join(basePath,options.addPath);
89
- if(!fs.existsSync(basePath)){
90
- fs.mkdirSync(basePath);
91
- }
92
- }
93
- if(options.userId){
94
- basePath=path.join(basePath,options.userId.toString());
95
- }else{
96
- basePath=path.join(basePath,"unlogged");
97
- }
98
- if(!fs.existsSync(basePath)){
99
- fs.mkdirSync(basePath);
100
- }
101
- let fileName=path.join(basePath,`${options.filePrefix?options.filePrefix+'_':""}${getDateString(new Date())}.csv`);
102
- let data="";
103
- if(fs.existsSync(fileName)){
104
- data=fs.readFileSync(fileName).toString()+"\n";
105
- }
106
- if(!data){
107
- data='Data;Severidade;Usuário;Dados;IP;URL;Supeita de Ataque\n';
108
- }
109
- 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"}`;
110
- fs.writeFileSync(fileName,data);
111
- return {
112
- fileName,
113
- basePath,
114
- };
115
- }
116
- function getDateString(d:Date){
117
- const year=d.getFullYear();
118
- const month=zerof(d.getMonth()+1);
119
- const day=zerof(d.getDate());
120
- const hour=zerof(d.getHours());
121
- return `${year}_${month}_${day}_${hour}`;
122
- function zerof(n:number){
123
- if(n>9)
124
- return n.toString();
125
- return `0${n}`;
126
- }
127
- }