serverpreconfigured 2.1.9 → 2.2.1

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.
@@ -4,14 +4,16 @@ import { Express } from "express";
4
4
  import { Server } from "http";
5
5
  export default class ExpressServer {
6
6
  app: Express;
7
- authBaseUrl: string;
7
+ authUserBaseUrl: string;
8
+ registerUserBaseUrl: string;
8
9
  usePort: number;
9
10
  server?: Server;
10
11
  wsAuthBaseUrl: string;
11
12
  constructor();
12
13
  listen(port?: any): void;
13
14
  initModules(): void;
14
- initAuthSystem(baseUrl?: string): void;
15
+ initUserAuthSystem(baseUrl?: string): void;
16
+ initUserRegisterSystem(baseUrl?: string): void;
15
17
  initWSAuthSystem(wsBaseUrl?: string): void;
16
18
  getApp(): express.Express;
17
19
  getServer(): Server | undefined;
@@ -8,12 +8,14 @@ const sessions_1 = require("./modules/sessions");
8
8
  const postreader_1 = require("./modules/postreader");
9
9
  const initcors_1 = require("./modules/initcors");
10
10
  const env_1 = __importDefault(require("./settings/env"));
11
- const users_1 = __importDefault(require("./routes/users"));
11
+ const userauth_1 = __importDefault(require("./routes/userauth"));
12
12
  const wsauth_1 = require("./routes/wsauth");
13
+ const userresgister_1 = __importDefault(require("./routes/userresgister"));
13
14
  class ExpressServer {
14
15
  constructor() {
15
- this.authBaseUrl = "";
16
+ this.authUserBaseUrl = "";
16
17
  this.wsAuthBaseUrl = "";
18
+ this.registerUserBaseUrl = "";
17
19
  this.usePort = env_1.default.PORT;
18
20
  this.app = (0, express_1.default)();
19
21
  this.initModules();
@@ -28,9 +30,13 @@ class ExpressServer {
28
30
  (0, postreader_1.initPostReader)(this.app);
29
31
  (0, initcors_1.initCors)(this.app);
30
32
  }
31
- initAuthSystem(baseUrl = '/user') {
32
- this.authBaseUrl = baseUrl;
33
- this.app.use(this.authBaseUrl, users_1.default);
33
+ initUserAuthSystem(baseUrl = '/user') {
34
+ this.authUserBaseUrl = baseUrl;
35
+ this.app.use(this.authUserBaseUrl, userauth_1.default);
36
+ }
37
+ initUserRegisterSystem(baseUrl = '/userregister') {
38
+ this.registerUserBaseUrl = baseUrl;
39
+ this.app.use(this.registerUserBaseUrl, userresgister_1.default);
34
40
  }
35
41
  initWSAuthSystem(wsBaseUrl = '/ws') {
36
42
  this.wsAuthBaseUrl = wsBaseUrl;
@@ -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.url;
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,20 +8,16 @@ 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
- const DEBUG = env_1.default.NODE_ENV === 'development' ? true : false;
16
+ const response_1 = require("../utils/response");
21
17
  function setUserDataMiddleware(req, res, next) {
22
18
  return __awaiter(this, void 0, void 0, function* () {
23
19
  if (!(0, server_1.userIsLogged)(req))
24
- return res.status(401).send((0, server_2.JSONResponse)(false, undefined, "User Must Be Logged"));
20
+ return res.status(401).send((0, server_2.JSONResponse)({}, "User Must Be Logged"));
25
21
  try {
26
22
  const dealerEmail = (0, server_3.getUserSessionData)(req);
27
23
  const user = yield server_1.User.findOne({ where: { email: dealerEmail, is_active: true } });
@@ -32,10 +28,7 @@ function setUserDataMiddleware(req, res, next) {
32
28
  next();
33
29
  }
34
30
  catch (e) {
35
- let more = null;
36
- if (DEBUG)
37
- more = e;
38
- return res.status(500).send((0, server_2.JSONResponse)(false, undefined, "Get dealer data error", more));
31
+ return (0, response_1.sendIError)(req, res, e);
39
32
  }
40
33
  });
41
34
  }
@@ -0,0 +1,2 @@
1
+ declare const router: import("express-serve-static-core").Router;
2
+ export default router;
@@ -0,0 +1,68 @@
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
+ const express_1 = __importDefault(require("express"));
16
+ const response_1 = require("../utils/response");
17
+ const auth_1 = require("../auth/auth");
18
+ const meta_sanitizer_1 = __importDefault(require("meta-sanitizer"));
19
+ const users_1 = require("../users/users");
20
+ const auth_2 = require("../middlewares/auth");
21
+ const auth_3 = require("../auth/auth");
22
+ const auth_4 = require("../auth/auth");
23
+ const server_1 = require("../server");
24
+ const router = express_1.default.Router();
25
+ router.post('/logout', (req, res) => {
26
+ let is_ok = false;
27
+ if ((0, auth_1.userIsLogged)(req)) {
28
+ (0, auth_4.logoutUser)(req);
29
+ is_ok = true;
30
+ }
31
+ res.send((0, response_1.JSONResponse)("OK"));
32
+ });
33
+ router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
34
+ let email = "";
35
+ let password = "";
36
+ try {
37
+ email = meta_sanitizer_1.default.sanitizeEmail(req.body.email);
38
+ password = meta_sanitizer_1.default.queryProtector(req.body.password);
39
+ }
40
+ catch (e) {
41
+ return res.status(403).send((0, response_1.JSONResponse)({}, "Must have 'email' and 'password' params"));
42
+ }
43
+ if (password == "" || email == "")
44
+ return res.status(403).send((0, response_1.JSONResponse)({}, "Must have 'email' and 'password' params"));
45
+ email = email.toLocaleLowerCase();
46
+ try {
47
+ const checkPass = yield (0, users_1.checkUserPassword)(email, password);
48
+ if (checkPass) {
49
+ const user = yield server_1.User.findOne({ where: { email: email } });
50
+ if (!user)
51
+ throw "Dont find User";
52
+ if (!user.is_active) {
53
+ return res.status(403).send((0, response_1.JSONResponse)({}, "User deleted"));
54
+ }
55
+ (0, auth_3.setUserLogged)(req, email);
56
+ yield (0, users_1.updateUserLastAction)(user);
57
+ return res.status(200).send((0, response_1.JSONResponse)("Login Ok"));
58
+ }
59
+ return res.status(403).send((0, response_1.JSONResponse)({}, "Invalid Password"));
60
+ }
61
+ catch (e) {
62
+ return (0, response_1.sendIError)(req, res, e);
63
+ }
64
+ }));
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 }));
67
+ }));
68
+ exports.default = router;
@@ -0,0 +1,2 @@
1
+ declare const router: import("express-serve-static-core").Router;
2
+ export default router;
@@ -0,0 +1,42 @@
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
+ const express_1 = require("express");
16
+ const email_1 = require("../utils/validators/email");
17
+ const server_1 = require("../server");
18
+ const server_2 = require("../server");
19
+ const response_1 = require("../utils/response");
20
+ const meta_sanitizer_1 = __importDefault(require("meta-sanitizer"));
21
+ const router = (0, express_1.Router)();
22
+ router.post('/register', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
23
+ try {
24
+ let email = meta_sanitizer_1.default.sanitizeEmail(req.body.email || '');
25
+ let password = meta_sanitizer_1.default.queryProtector(req.body.password || '');
26
+ let name = meta_sanitizer_1.default.SanitizerEngine(req.body.name || '', true, false, [' ']).sanitizedData;
27
+ if (email == "" || password == "" || name == "")
28
+ return res.send((0, server_2.JSONResponse)({}, "Invalid params"));
29
+ email = email.toLocaleLowerCase();
30
+ if (!(0, email_1.checkEmail)(email)) {
31
+ return res.status(403).send((0, server_2.JSONResponse)({}, "Invalid Email"));
32
+ }
33
+ yield (0, server_1.createUser)({ first_name: name, email: email, password_string: password });
34
+ return res.send((0, server_2.JSONResponse)("REGISTER OK"));
35
+ }
36
+ catch (e) {
37
+ if (e === "User exist")
38
+ return res.send((0, server_2.JSONResponse)({}, "User Exist"));
39
+ return (0, response_1.sendIError)(req, res, e);
40
+ }
41
+ }));
42
+ exports.default = router;
@@ -19,25 +19,10 @@ const meta_sanitizer_1 = __importDefault(require("meta-sanitizer"));
19
19
  const users_1 = require("../users/users");
20
20
  const users_2 = require("../users/users");
21
21
  const auth_2 = require("../middlewares/auth");
22
- const env_1 = __importDefault(require("../settings/env"));
23
22
  const auth_3 = require("../auth/auth");
24
23
  const auth_4 = require("../auth/auth");
25
24
  const server_1 = require("../server");
26
- const DEBUG = env_1.default.NODE_ENV === 'development' ? true : false;
27
- var LoginErrorCode;
28
- (function (LoginErrorCode) {
29
- LoginErrorCode[LoginErrorCode["NoError"] = 0] = "NoError";
30
- LoginErrorCode[LoginErrorCode["InvalidParams"] = 1] = "InvalidParams";
31
- LoginErrorCode[LoginErrorCode["InvalidPassword"] = 2] = "InvalidPassword";
32
- LoginErrorCode[LoginErrorCode["InternalError"] = 3] = "InternalError";
33
- })(LoginErrorCode || (LoginErrorCode = {}));
34
- var RegisterUserErrorCode;
35
- (function (RegisterUserErrorCode) {
36
- RegisterUserErrorCode[RegisterUserErrorCode["NoError"] = 0] = "NoError";
37
- RegisterUserErrorCode[RegisterUserErrorCode["InvalidParams"] = 1] = "InvalidParams";
38
- RegisterUserErrorCode[RegisterUserErrorCode["UserExist"] = 2] = "UserExist";
39
- RegisterUserErrorCode[RegisterUserErrorCode["InternalError"] = 3] = "InternalError";
40
- })(RegisterUserErrorCode || (RegisterUserErrorCode = {}));
25
+ const email_1 = require("../utils/validators/email");
41
26
  const router = express_1.default.Router();
42
27
  router.post('/logout', (req, res) => {
43
28
  let is_ok = false;
@@ -45,7 +30,7 @@ router.post('/logout', (req, res) => {
45
30
  (0, auth_4.logoutUser)(req);
46
31
  is_ok = true;
47
32
  }
48
- res.send((0, response_1.JSONResponse)(is_ok, 0, is_ok ? "" : "User Must be logged", {}));
33
+ res.send((0, response_1.JSONResponse)("OK"));
49
34
  });
50
35
  router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
51
36
  let email = "";
@@ -55,32 +40,28 @@ router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function*
55
40
  password = meta_sanitizer_1.default.queryProtector(req.body.password);
56
41
  }
57
42
  catch (e) {
58
- return res.status(403).send((0, response_1.JSONResponse)(false, LoginErrorCode.InvalidParams, "Must have 'email' and 'password' params"));
43
+ return res.status(403).send((0, response_1.JSONResponse)({}, "Must have 'email' and 'password' params"));
59
44
  }
60
45
  if (password == "" || email == "")
61
- return res.status(403).send((0, response_1.JSONResponse)(false, LoginErrorCode.InvalidParams, "Must have 'email' and 'password' params"));
46
+ return res.status(403).send((0, response_1.JSONResponse)({}, "Must have 'email' and 'password' params"));
62
47
  email = email.toLocaleLowerCase();
63
48
  try {
64
49
  const checkPass = yield (0, users_1.checkUserPassword)(email, password);
65
50
  if (checkPass) {
66
51
  const user = yield server_1.User.findOne({ where: { email: email } });
67
- if (!user) {
68
- return res.status(500).send((0, response_1.JSONResponse)(false, 0, "I_E"));
69
- }
52
+ if (!user)
53
+ throw "Dont find User";
70
54
  if (!user.is_active) {
71
- return res.status(400).send((0, response_1.JSONResponse)(false, 0, "User deleted"));
55
+ return res.status(403).send((0, response_1.JSONResponse)({}, "User deleted"));
72
56
  }
73
57
  (0, auth_3.setUserLogged)(req, email);
74
58
  yield (0, users_1.updateUserLastAction)(user);
75
- return res.status(200).send((0, response_1.JSONResponse)(true, LoginErrorCode.NoError, "Login Ok"));
59
+ return res.status(200).send((0, response_1.JSONResponse)("Login Ok"));
76
60
  }
77
- return res.status(403).send((0, response_1.JSONResponse)(false, LoginErrorCode.InvalidPassword, "Invalid Password"));
61
+ return res.status(403).send((0, response_1.JSONResponse)({}, "Invalid Password"));
78
62
  }
79
63
  catch (e) {
80
- let more = null;
81
- if (DEBUG)
82
- more = e;
83
- return res.status(500).send((0, response_1.JSONResponse)(false, LoginErrorCode.InternalError, "I-Error", more));
64
+ return (0, response_1.sendIError)(req, res, e);
84
65
  }
85
66
  }));
86
67
  router.post('/register', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
@@ -89,18 +70,21 @@ router.post('/register', (req, res) => __awaiter(void 0, void 0, void 0, functio
89
70
  let password = meta_sanitizer_1.default.queryProtector(req.body.password || '');
90
71
  let name = meta_sanitizer_1.default.SanitizerEngine(req.body.name || '', true, false, [' ']).sanitizedData;
91
72
  if (email == "" || password == "" || name == "")
92
- return res.send((0, response_1.JSONResponse)(false, RegisterUserErrorCode.InvalidParams, "Invalid params"));
73
+ return res.send((0, response_1.JSONResponse)({}, "Invalid params"));
93
74
  email = email.toLocaleLowerCase();
75
+ if (!(0, email_1.checkEmail)(email)) {
76
+ return res.status(403).send((0, response_1.JSONResponse)({}, "Invalid Email"));
77
+ }
94
78
  yield (0, users_2.createUser)({ first_name: name, email: email, password_string: password });
95
- return res.send((0, response_1.JSONResponse)(true, RegisterUserErrorCode.NoError, "", "REGISTER OK"));
79
+ return res.send((0, response_1.JSONResponse)("REGISTER OK"));
96
80
  }
97
81
  catch (e) {
98
82
  if (e === "User exist")
99
- return res.send((0, response_1.JSONResponse)(false, RegisterUserErrorCode.UserExist, "User Exist"));
100
- return res.send((0, response_1.JSONResponse)(false, RegisterUserErrorCode.InternalError, "I-Error"));
83
+ return res.send((0, response_1.JSONResponse)({}, "User Exist"));
84
+ return (0, response_1.sendIError)(req, res, e);
101
85
  }
102
86
  }));
103
87
  router.post('/getuser', auth_2.setUserDataMiddleware, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
104
- res.send((0, response_1.JSONResponse)(true, 0, "", { email: req.user.email, id: req.user.id }));
88
+ res.send((0, response_1.JSONResponse)({}, { email: req.user.email, id: req.user.id }));
105
89
  }));
106
90
  exports.default = router;
@@ -16,30 +16,18 @@ exports.router = void 0;
16
16
  const express_1 = __importDefault(require("express"));
17
17
  const response_1 = require("../utils/response");
18
18
  const wsauth_1 = require("../wsauth/wsauth");
19
- const env_1 = __importDefault(require("../settings/env"));
20
19
  const auth_1 = require("../middlewares/auth");
21
20
  exports.router = express_1.default.Router();
22
- const DEBUG = env_1.default.NODE_ENV === 'development' ? true : false;
23
- var GenerateTokenError;
24
- (function (GenerateTokenError) {
25
- GenerateTokenError[GenerateTokenError["UserMustBeLogged"] = 1] = "UserMustBeLogged";
26
- GenerateTokenError[GenerateTokenError["GetUserError"] = 2] = "GetUserError";
27
- GenerateTokenError[GenerateTokenError["InternalError"] = 3] = "InternalError";
28
- })(GenerateTokenError || (GenerateTokenError = {}));
29
- ;
30
21
  exports.router.post('/gettoken', auth_1.setUserDataMiddleware, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
31
22
  try {
32
23
  let userId = req.user.id;
33
24
  let n = yield (0, wsauth_1.setWSAuthDataNewToken)(userId);
34
- return res.send((0, response_1.JSONResponse)(true, 0, "", { token: n.dataValues.token,
25
+ return res.send((0, response_1.JSONResponse)({ token: n.dataValues.token,
35
26
  expiration: n.dataValues.expiration,
36
27
  userId: userId
37
28
  }));
38
29
  }
39
30
  catch (e) {
40
- let more = null;
41
- if (DEBUG)
42
- more = e;
43
- return res.status(500).send((0, response_1.JSONResponse)(false, GenerateTokenError.InternalError, "I-Error", more));
31
+ return (0, response_1.sendIError)(req, res, e);
44
32
  }
45
33
  }));
@@ -1,2 +1,8 @@
1
- export declare function JSONResponse(is_ok: boolean, error_code?: number, error_message?: string, data?: any): string;
1
+ import { LogSeverity } from "../logs/logs";
2
+ export declare function JSONResponse(data: any, error?: any): string;
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;
2
8
  export declare function WSResponse(isOK: boolean, message?: string, errorMessage?: string, data?: any): string;
@@ -1,16 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WSResponse = exports.JSONResponse = void 0;
4
- function JSONResponse(is_ok, error_code = 0, error_message = '', data = {}) {
5
- const ret_data = {
6
- is_ok: is_ok,
7
- error_code: error_code,
8
- error_message: error_message,
9
- data: data,
10
- };
11
- return JSON.stringify(ret_data);
3
+ exports.WSResponse = exports.sendIError = exports.JSONResponse = void 0;
4
+ const logs_1 = require("../logs/logs");
5
+ function JSONResponse(data, error) {
6
+ return JSON.stringify({
7
+ data,
8
+ hasError: Boolean(error),
9
+ error,
10
+ });
12
11
  }
13
12
  exports.JSONResponse = JSONResponse;
13
+ ;
14
+ function sendIError(req, res, error, options) {
15
+ (0, logs_1.saveInternalErrorLog)(req, error, options);
16
+ return res.status(500).send(JSONResponse("", "I-E"));
17
+ }
18
+ exports.sendIError = sendIError;
14
19
  function WSResponse(isOK, message = '', errorMessage = "", data = {}) {
15
20
  return JSON.stringify({
16
21
  is_ok: isOK,
@@ -0,0 +1 @@
1
+ export declare function checkEmail(email: string): boolean;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkEmail = void 0;
4
+ function checkEmail(email) {
5
+ const atIndex = email.indexOf("@");
6
+ if (atIndex < 1)
7
+ return false;
8
+ const after = email.slice(atIndex + 1);
9
+ if (after.length < 3)
10
+ return false;
11
+ if (after.indexOf('@') >= 0)
12
+ return false;
13
+ const periodIndex = after.indexOf('.');
14
+ if (periodIndex < 1 || periodIndex >= after.length - 1)
15
+ return false;
16
+ return true;
17
+ }
18
+ exports.checkEmail = checkEmail;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serverpreconfigured",
3
- "version": "2.1.9",
3
+ "version": "2.2.1",
4
4
  "description": "\"Pre-configured server with authentication system and database integration\"",
5
5
  "main": "dist/server.js",
6
6
  "keywords": [
@@ -4,18 +4,21 @@ import { initSessions } from "./modules/sessions";
4
4
  import { initPostReader } from "./modules/postreader";
5
5
  import { initCors } from "./modules/initcors";
6
6
  import ENV from "./settings/env";
7
- import authRouter from "./routes/users";
7
+ import authUserRouter from "./routes/userauth";
8
8
  import { router as wsAuthRoter } from "./routes/wsauth";
9
9
  import { Server } from "http";
10
+ import userRegisterRouter from "./routes/userresgister";
10
11
  export default class ExpressServer{
11
12
  app:Express;
12
- authBaseUrl:string;
13
+ authUserBaseUrl:string;
14
+ registerUserBaseUrl:string;
13
15
  usePort:number;
14
16
  server?:Server;
15
17
  wsAuthBaseUrl:string;
16
18
  constructor(){
17
- this.authBaseUrl="";
19
+ this.authUserBaseUrl="";
18
20
  this.wsAuthBaseUrl="";
21
+ this.registerUserBaseUrl="";
19
22
  this.usePort=ENV.PORT;
20
23
  this.app=express();
21
24
  this.initModules();
@@ -31,9 +34,13 @@ export default class ExpressServer{
31
34
  initPostReader(this.app);
32
35
  initCors(this.app);
33
36
  }
34
- initAuthSystem(baseUrl:string='/user'){
35
- this.authBaseUrl=baseUrl;
36
- this.app.use(this.authBaseUrl,authRouter);
37
+ initUserAuthSystem(baseUrl:string='/user'){
38
+ this.authUserBaseUrl=baseUrl;
39
+ this.app.use(this.authUserBaseUrl,authUserRouter);
40
+ }
41
+ initUserRegisterSystem(baseUrl:string='/userregister'){
42
+ this.registerUserBaseUrl=baseUrl;
43
+ this.app.use(this.registerUserBaseUrl,userRegisterRouter)
37
44
  }
38
45
  initWSAuthSystem(wsBaseUrl:string='/ws'){
39
46
  this.wsAuthBaseUrl=wsBaseUrl;
@@ -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.url;
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,12 +1,11 @@
1
1
  import { User, updateUserLastAction, userIsLogged } from "../server";
2
2
  import { JSONResponse } from "../server";
3
3
  import { getUserSessionData } from "../server";
4
+ import { sendIError } from "../utils/response";
4
5
 
5
- import ENV from "../settings/env";
6
- const DEBUG=ENV.NODE_ENV==='development'?true:false;
7
6
  export async function setUserDataMiddleware(req:any,res:any,next:any){
8
7
  if(!userIsLogged(req))
9
- return res.status(401).send(JSONResponse(false,undefined,"User Must Be Logged"));
8
+ return res.status(401).send(JSONResponse({},"User Must Be Logged"));
10
9
  try{
11
10
  const dealerEmail=getUserSessionData(req);
12
11
  const user=await User.findOne({where:{email:dealerEmail,is_active:true}});
@@ -16,9 +15,6 @@ export async function setUserDataMiddleware(req:any,res:any,next:any){
16
15
  await updateUserLastAction(user);
17
16
  next();
18
17
  }catch(e){
19
- let more=null;
20
- if(DEBUG)
21
- more=e;
22
- return res.status(500).send(JSONResponse(false,undefined,"Get dealer data error",more));
18
+ return sendIError(req,res,e);
23
19
  }
24
20
  }
@@ -0,0 +1,57 @@
1
+ import express from "express";
2
+ import { JSONResponse, sendIError } from "../utils/response";
3
+ import { userIsLogged } from "../auth/auth";
4
+ import meta_sanitizer from 'meta-sanitizer';
5
+ import { checkUserPassword, updateUserLastAction } from "../users/users";
6
+ import { createUser } from "../users/users";
7
+ import { setUserDataMiddleware } from "../middlewares/auth";
8
+ import { setUserLogged } from "../auth/auth";
9
+ import { logoutUser } from "../auth/auth";
10
+ import { User } from "../server";
11
+
12
+
13
+ const router=express.Router();
14
+ router.post('/logout',(req,res)=>{
15
+ let is_ok=false;
16
+ if(userIsLogged(req)){
17
+ logoutUser(req)
18
+ is_ok=true;
19
+ }
20
+ res.send(JSONResponse("OK"));
21
+ });
22
+ router.post('/login',async (req,res)=>{
23
+ let email="";
24
+ let password="";
25
+ try{
26
+ email=meta_sanitizer.sanitizeEmail(req.body.email);
27
+ password=meta_sanitizer.queryProtector(req.body.password);
28
+ }catch(e){
29
+ return res.status(403).send(JSONResponse({},"Must have 'email' and 'password' params"))
30
+ }
31
+ if(password==""||email=="")
32
+ return res.status(403).send(JSONResponse({},"Must have 'email' and 'password' params"));
33
+ email=email.toLocaleLowerCase();
34
+ try{
35
+ const checkPass=await checkUserPassword(email,password);
36
+ if(checkPass){
37
+ const user:User=await User.findOne({where:{email:email}});
38
+ if(!user)
39
+ throw "Dont find User";
40
+ if(!user.is_active){
41
+ return res.status(403).send(JSONResponse({},"User deleted"));
42
+ }
43
+ setUserLogged(req,email);
44
+ await updateUserLastAction(user)
45
+ return res.status(200).send(JSONResponse("Login Ok"));
46
+ }
47
+ return res.status(403).send(JSONResponse({},"Invalid Password"));
48
+ }catch(e){
49
+ return sendIError(req,res,e);
50
+ }
51
+
52
+ });
53
+
54
+ router.post('/getuser',setUserDataMiddleware,async (req:any,res)=>{
55
+ res.send(JSONResponse({},{email:req.user.email,id:req.user.id}));
56
+ });
57
+ export default router;
@@ -0,0 +1,28 @@
1
+ import { Router } from "express";
2
+ import { checkEmail } from "../utils/validators/email";
3
+ import { createUser } from "../server";
4
+ import { JSONResponse } from "../server";
5
+ import { sendIError } from "../utils/response";
6
+ import meta_sanitizer from "meta-sanitizer";
7
+ const router=Router();
8
+ router.post('/register',async (req,res)=>{
9
+ try{
10
+ let email=meta_sanitizer.sanitizeEmail(req.body.email||'');
11
+ let password=meta_sanitizer.queryProtector(req.body.password||'');
12
+ let name=meta_sanitizer.SanitizerEngine(req.body.name||'',true,false,[' ']).sanitizedData;
13
+ if(email=="" || password=="" || name=="")
14
+ return res.send(JSONResponse({},"Invalid params"));
15
+ email=email.toLocaleLowerCase();
16
+ if(!checkEmail(email)){
17
+ return res.status(403).send(JSONResponse({},"Invalid Email"));
18
+ }
19
+ await createUser({first_name:name,email:email,password_string:password});
20
+ return res.send(JSONResponse("REGISTER OK"));
21
+ }catch(e){
22
+ if(e==="User exist")
23
+ return res.send(JSONResponse({},"User Exist"));
24
+ return sendIError(req,res,e);
25
+ }
26
+ });
27
+
28
+ export default router;
@@ -1,27 +1,18 @@
1
1
  import express from "express";
2
- import { JSONResponse } from "../utils/response";
2
+ import { JSONResponse, sendIError } from "../utils/response";
3
3
  import { setWSAuthDataNewToken } from "../wsauth/wsauth";
4
- import ENV from "../settings/env";
5
4
  import { setUserDataMiddleware } from "../middlewares/auth";
6
5
  export const router=express.Router();
7
- const DEBUG=ENV.NODE_ENV==='development'?true:false;
8
- enum GenerateTokenError{
9
- UserMustBeLogged=1,
10
- GetUserError,
11
- InternalError,
12
- };
6
+
13
7
  router.post('/gettoken',setUserDataMiddleware,async (req:any,res:any)=>{
14
8
  try{
15
9
  let userId:number=req.user.id;
16
10
  let n=await setWSAuthDataNewToken(userId);
17
- return res.send(JSONResponse(true,0,"",{token:n.dataValues.token,
11
+ return res.send(JSONResponse({token:n.dataValues.token,
18
12
  expiration:n.dataValues.expiration,
19
13
  userId:userId
20
14
  }));
21
15
  }catch(e){
22
- let more=null;
23
- if(DEBUG)
24
- more=e;
25
- return res.status(500).send(JSONResponse(false,GenerateTokenError.InternalError,"I-Error",more));
16
+ return sendIError(req,res,e);
26
17
  }
27
18
  });
@@ -1,11 +1,19 @@
1
- export function JSONResponse(is_ok:boolean,error_code:number=0,error_message:string='',data:any={}){
2
- const ret_data={
3
- is_ok:is_ok,
4
- error_code:error_code,
5
- error_message:error_message,
6
- data:data,
7
- };
8
- return JSON.stringify(ret_data);
1
+ import { LogSeverity, saveInternalErrorLog } from "../logs/logs";
2
+ export function JSONResponse(data:any,error?:any){
3
+ return JSON.stringify({
4
+ data,
5
+ hasError:Boolean(error),
6
+ error,
7
+ });
8
+ };
9
+ export interface SendIErrorOptions{
10
+ severity?:LogSeverity,
11
+ penTestSuspcion?:boolean;
12
+ }
13
+
14
+ export function sendIError(req:any,res:any,error?:any,options?:SendIErrorOptions){
15
+ saveInternalErrorLog(req,error,options);
16
+ return res.status(500).send(JSONResponse("","I-E"));
9
17
  }
10
18
  export function WSResponse(isOK:boolean,message:string='',errorMessage:string="",data:any={}):string{
11
19
  return JSON.stringify({
@@ -0,0 +1,14 @@
1
+ export function checkEmail(email:string){
2
+ const atIndex=email.indexOf("@");
3
+ if(atIndex<1)
4
+ return false;
5
+ const after=email.slice(atIndex+1);
6
+ if(after.length<3)
7
+ return false;
8
+ if(after.indexOf('@')>=0)
9
+ return false;
10
+ const periodIndex=after.indexOf('.');
11
+ if(periodIndex<1||periodIndex>=after.length-1)
12
+ return false;
13
+ return true;
14
+ }
@@ -1,91 +0,0 @@
1
- import express from "express";
2
- import { JSONResponse } from "../utils/response";
3
- import { userIsLogged } from "../auth/auth";
4
- import meta_sanitizer from 'meta-sanitizer';
5
- import { checkUserPassword, updateUserLastAction } from "../users/users";
6
- import { createUser } from "../users/users";
7
- import { setUserDataMiddleware } from "../middlewares/auth";
8
- import ENV from "../settings/env";
9
- import { setUserLogged } from "../auth/auth";
10
- import { logoutUser } from "../auth/auth";
11
- import { User } from "../server";
12
-
13
- const DEBUG=ENV.NODE_ENV==='development'?true:false;
14
- enum LoginErrorCode{
15
- NoError=0,
16
- InvalidParams,
17
- InvalidPassword,
18
- InternalError,
19
-
20
- }
21
- enum RegisterUserErrorCode{
22
- NoError=0,
23
- InvalidParams,
24
- UserExist,
25
- InternalError
26
- }
27
- const router=express.Router();
28
- router.post('/logout',(req,res)=>{
29
- let is_ok=false;
30
- if(userIsLogged(req)){
31
- logoutUser(req)
32
- is_ok=true;
33
- }
34
- res.send(JSONResponse(is_ok,0,is_ok?"":"User Must be logged",{}));
35
- });
36
- router.post('/login',async (req,res)=>{
37
- let email="";
38
- let password="";
39
- try{
40
- email=meta_sanitizer.sanitizeEmail(req.body.email);
41
- password=meta_sanitizer.queryProtector(req.body.password);
42
- }catch(e){
43
- return res.status(403).send(JSONResponse(false,LoginErrorCode.InvalidParams,"Must have 'email' and 'password' params"))
44
- }
45
- if(password==""||email=="")
46
- return res.status(403).send(JSONResponse(false,LoginErrorCode.InvalidParams,"Must have 'email' and 'password' params"));
47
- email=email.toLocaleLowerCase();
48
- try{
49
- const checkPass=await checkUserPassword(email,password);
50
- if(checkPass){
51
- const user:User=await User.findOne({where:{email:email}});
52
- if(!user){
53
- return res.status(500).send(JSONResponse(false,0,"I_E"));
54
- }
55
- if(!user.is_active){
56
- return res.status(400).send(JSONResponse(false,0,"User deleted"));
57
- }
58
- setUserLogged(req,email);
59
- await updateUserLastAction(user)
60
- return res.status(200).send(JSONResponse(true,LoginErrorCode.NoError,"Login Ok"));
61
- }
62
- return res.status(403).send(JSONResponse(false,LoginErrorCode.InvalidPassword,"Invalid Password"));
63
- }catch(e){
64
- let more=null;
65
- if(DEBUG)
66
- more=e;
67
- return res.status(500).send(JSONResponse(false,LoginErrorCode.InternalError,"I-Error",more));
68
- }
69
-
70
- });
71
- router.post('/register',async (req,res)=>{
72
- try{
73
- let email=meta_sanitizer.sanitizeEmail(req.body.email||'');
74
- let password=meta_sanitizer.queryProtector(req.body.password||'');
75
- let name=meta_sanitizer.SanitizerEngine(req.body.name||'',true,false,[' ']).sanitizedData;
76
- if(email=="" || password=="" || name=="")
77
- return res.send(JSONResponse(false,RegisterUserErrorCode.InvalidParams,"Invalid params"));
78
- email=email.toLocaleLowerCase();
79
- await createUser({first_name:name,email:email,password_string:password});
80
- return res.send(JSONResponse(true,RegisterUserErrorCode.NoError,"","REGISTER OK"));
81
- }catch(e){
82
- if(e==="User exist")
83
- return res.send(JSONResponse(false,RegisterUserErrorCode.UserExist,"User Exist"));
84
- return res.send(JSONResponse(false,RegisterUserErrorCode.InternalError,"I-Error"));
85
- }
86
- });
87
-
88
- router.post('/getuser',setUserDataMiddleware,async (req:any,res)=>{
89
- res.send(JSONResponse(true,0,"",{email:req.user.email,id:req.user.id}));
90
- });
91
- export default router;