serverpreconfigured 1.0.0

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.
Files changed (57) hide show
  1. package/.sequelizerc +6 -0
  2. package/LICENSE +21 -0
  3. package/README.md +2 -0
  4. package/dist/auth/auth.d.ts +1 -0
  5. package/dist/auth/auth.js +11 -0
  6. package/dist/auth/config.d.ts +1 -0
  7. package/dist/auth/config.js +3 -0
  8. package/dist/database/database.d.ts +1 -0
  9. package/dist/database/database.js +10 -0
  10. package/dist/database/models/User.d.ts +4 -0
  11. package/dist/database/models/User.js +18 -0
  12. package/dist/modules/initcors.d.ts +1 -0
  13. package/dist/modules/initcors.js +12 -0
  14. package/dist/modules/postreader.d.ts +1 -0
  15. package/dist/modules/postreader.js +11 -0
  16. package/dist/modules/sessions.d.ts +1 -0
  17. package/dist/modules/sessions.js +19 -0
  18. package/dist/routes/auth.d.ts +2 -0
  19. package/dist/routes/auth.js +56 -0
  20. package/dist/server.d.ts +10 -0
  21. package/dist/server.js +37 -0
  22. package/dist/sessions/secureget.d.ts +1 -0
  23. package/dist/sessions/secureget.js +6 -0
  24. package/dist/sessions/secureset.d.ts +2 -0
  25. package/dist/sessions/secureset.js +10 -0
  26. package/dist/settings/database/database.d.ts +10 -0
  27. package/dist/settings/database/database.js +14 -0
  28. package/dist/settings/env.d.ts +13 -0
  29. package/dist/settings/env.js +15 -0
  30. package/dist/users/password.d.ts +2 -0
  31. package/dist/users/password.js +40 -0
  32. package/dist/users/types.d.ts +6 -0
  33. package/dist/users/types.js +3 -0
  34. package/dist/users/users.d.ts +7 -0
  35. package/dist/users/users.js +92 -0
  36. package/dist/utils/response.d.ts +1 -0
  37. package/dist/utils/response.js +12 -0
  38. package/migrations/20220314190413-new.js +44 -0
  39. package/package.json +35 -0
  40. package/src/auth/auth.ts +8 -0
  41. package/src/auth/config.ts +1 -0
  42. package/src/database/database.ts +5 -0
  43. package/src/database/models/User.ts +20 -0
  44. package/src/modules/initcors.ts +7 -0
  45. package/src/modules/postreader.ts +5 -0
  46. package/src/modules/sessions.ts +14 -0
  47. package/src/routes/auth.ts +42 -0
  48. package/src/server.ts +36 -0
  49. package/src/sessions/secureget.ts +3 -0
  50. package/src/sessions/secureset.ts +7 -0
  51. package/src/settings/database/database.js +14 -0
  52. package/src/settings/env.ts +13 -0
  53. package/src/users/password.ts +20 -0
  54. package/src/users/types.ts +6 -0
  55. package/src/users/users.ts +64 -0
  56. package/src/utils/response.ts +9 -0
  57. package/tsconfig.json +68 -0
package/.sequelizerc ADDED
@@ -0,0 +1,6 @@
1
+ const path = require('path');
2
+
3
+ module.exports = {
4
+ 'config': path.resolve(__dirname,'dist','settings','database','database.js'),
5
+ 'migrations-path': path.resolve(__dirname, 'migrations'),
6
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Rafael Floriani Pinto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # Node-Server-Preconfigured
2
+ Node Server Preconfigured
@@ -0,0 +1 @@
1
+ export declare function userIsLogged(req: any): boolean;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const secureget_1 = require("../sessions/secureget");
4
+ const config_1 = require("./config");
5
+ function userIsLogged(req) {
6
+ let user = secureget_1.getSessionValue(req, config_1.SESSION_LOGGED_DATA);
7
+ if (user)
8
+ return true;
9
+ return false;
10
+ }
11
+ exports.userIsLogged = userIsLogged;
@@ -0,0 +1 @@
1
+ export declare const SESSION_LOGGED_DATA = "email";
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SESSION_LOGGED_DATA = 'email';
@@ -0,0 +1 @@
1
+ export declare const dataBase: any;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ //@ts-ignore
7
+ //@ts-nocheck
8
+ const sequelize_1 = require("sequelize");
9
+ const database_1 = __importDefault(require("./../settings/database/database"));
10
+ exports.dataBase = new sequelize_1.Sequelize(database_1.default);
@@ -0,0 +1,4 @@
1
+ import { Model } from "sequelize";
2
+ export declare class User extends Model {
3
+ static init(sequelize: any): void;
4
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const sequelize_1 = require("sequelize");
4
+ const sequelize_2 = require("sequelize");
5
+ class User extends sequelize_1.Model {
6
+ static init(sequelize) {
7
+ super.init({
8
+ first_name: sequelize_2.DataTypes.STRING,
9
+ email: sequelize_2.DataTypes.STRING,
10
+ is_active: sequelize_2.DataTypes.BOOLEAN,
11
+ password_hash: sequelize_2.DataTypes.STRING,
12
+ }, {
13
+ sequelize: sequelize,
14
+ tableName: 'users',
15
+ });
16
+ }
17
+ }
18
+ exports.User = User;
@@ -0,0 +1 @@
1
+ export declare function initCors(app: any): void;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const cors_1 = __importDefault(require("cors"));
7
+ const env_1 = __importDefault(require("../settings/env"));
8
+ function initCors(app) {
9
+ if (env_1.default.ALLOW_CORS)
10
+ app.use(cors_1.default());
11
+ }
12
+ exports.initCors = initCors;
@@ -0,0 +1 @@
1
+ export declare function initPostReader(app: any): void;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const express_1 = __importDefault(require("express"));
7
+ function initPostReader(app) {
8
+ app.use(express_1.default.json());
9
+ app.use(express_1.default.urlencoded({ extended: true }));
10
+ }
11
+ exports.initPostReader = initPostReader;
@@ -0,0 +1 @@
1
+ export declare function initSessions(app: any): void;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const express_session_1 = __importDefault(require("express-session"));
7
+ const env_1 = __importDefault(require("../settings/env"));
8
+ function initSessions(app) {
9
+ app.set('trust proxy', 1); // trust first proxy
10
+ app.use(express_session_1.default({
11
+ secret: 'keyboard cat',
12
+ resave: false,
13
+ saveUninitialized: true,
14
+ cookie: { secure: env_1.default.NODE_ENV == 'development' ? false : true,
15
+ httpOnly: true,
16
+ },
17
+ }));
18
+ }
19
+ exports.initSessions = initSessions;
@@ -0,0 +1,2 @@
1
+ declare const router: import("express-serve-static-core").Router;
2
+ export default router;
@@ -0,0 +1,56 @@
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 secureset_1 = require("../sessions/secureset");
17
+ const config_1 = require("../auth/config");
18
+ const response_1 = require("../utils/response");
19
+ const auth_1 = require("../auth/auth");
20
+ const meta_sanitizer_1 = __importDefault(require("meta-sanitizer"));
21
+ const users_1 = require("../users/users");
22
+ var LoginErrorCode;
23
+ (function (LoginErrorCode) {
24
+ LoginErrorCode[LoginErrorCode["NoError"] = 0] = "NoError";
25
+ LoginErrorCode[LoginErrorCode["InvalidParams"] = 1] = "InvalidParams";
26
+ LoginErrorCode[LoginErrorCode["InvalidPassword"] = 2] = "InvalidPassword";
27
+ })(LoginErrorCode || (LoginErrorCode = {}));
28
+ const router = express_1.default.Router();
29
+ router.post('/logout', (req, res) => {
30
+ let is_ok = false;
31
+ if (auth_1.userIsLogged(req)) {
32
+ secureset_1.deleteSessionValue(req, config_1.SESSION_LOGGED_DATA);
33
+ is_ok = true;
34
+ }
35
+ res.send(response_1.JSONResponse(is_ok, 0, is_ok ? "" : "User Must be logged", {}));
36
+ });
37
+ router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
38
+ let email = "";
39
+ let password = "";
40
+ try {
41
+ email = meta_sanitizer_1.default.sanitizeEmail(req.body.email);
42
+ password = meta_sanitizer_1.default.queryProtector(req.body.password);
43
+ }
44
+ catch (e) {
45
+ return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidParams, "Must have 'email' and 'password' params"));
46
+ }
47
+ if (password == "" || email == "")
48
+ return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidParams, "Must have 'email' and 'password' params"));
49
+ const checkPass = yield users_1.checkUserPassword(email, password);
50
+ if (checkPass) {
51
+ secureset_1.setSessionValue(req, config_1.SESSION_LOGGED_DATA, email);
52
+ return res.send(response_1.JSONResponse(true, LoginErrorCode.NoError, "Login Ok"));
53
+ }
54
+ return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidPassword, "Invalid Password"));
55
+ }));
56
+ exports.default = router;
@@ -0,0 +1,10 @@
1
+ export default class ExpressServer {
2
+ app: any;
3
+ authBaseUrl: string;
4
+ usePort: number;
5
+ constructor();
6
+ listen(port?: any): void;
7
+ initModules(): void;
8
+ initAuthSystem(baseUrl?: string): void;
9
+ getApp(): any;
10
+ }
package/dist/server.js ADDED
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const express_1 = __importDefault(require("express"));
7
+ const sessions_1 = require("./modules/sessions");
8
+ const postreader_1 = require("./modules/postreader");
9
+ const initcors_1 = require("./modules/initcors");
10
+ const env_1 = __importDefault(require("./settings/env"));
11
+ const auth_1 = __importDefault(require("./routes/auth"));
12
+ class ExpressServer {
13
+ constructor() {
14
+ this.authBaseUrl = "";
15
+ this.usePort = env_1.default.PORT;
16
+ this.app = express_1.default();
17
+ this.initModules();
18
+ }
19
+ listen(port = null) {
20
+ if (port != null)
21
+ this.usePort = parseInt(port);
22
+ this.app.listen(this.usePort);
23
+ }
24
+ initModules() {
25
+ sessions_1.initSessions(this.app);
26
+ postreader_1.initPostReader(this.app);
27
+ initcors_1.initCors(this.app);
28
+ }
29
+ initAuthSystem(baseUrl = '/user') {
30
+ this.authBaseUrl = baseUrl;
31
+ this.app.use(this.authBaseUrl, auth_1.default);
32
+ }
33
+ getApp() {
34
+ return this.app;
35
+ }
36
+ }
37
+ exports.default = ExpressServer;
@@ -0,0 +1 @@
1
+ export declare function getSessionValue(req: any, get: string): any;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function getSessionValue(req, get) {
4
+ return req.session[get];
5
+ }
6
+ exports.getSessionValue = getSessionValue;
@@ -0,0 +1,2 @@
1
+ export declare function setSessionValue(req: any, to: string, value: any): void;
2
+ export declare function deleteSessionValue(req: any, to: string): void;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function setSessionValue(req, to, value) {
4
+ req.session[to] = value;
5
+ }
6
+ exports.setSessionValue = setSessionValue;
7
+ function deleteSessionValue(req, to) {
8
+ setSessionValue(req, to, undefined);
9
+ }
10
+ exports.deleteSessionValue = deleteSessionValue;
@@ -0,0 +1,10 @@
1
+ export declare const dialect: string;
2
+ export declare const host: string;
3
+ export declare const database: string;
4
+ export declare const username: string;
5
+ export declare const password: string;
6
+ export declare namespace define {
7
+ export const underscored: boolean;
8
+ export const timestamps: boolean;
9
+ }
10
+ export declare const logging: boolean;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ const ENV = require("./../env").default;
3
+ module.exports = {
4
+ dialect: ENV.DATABASE.dialect,
5
+ host: ENV.DATABASE.host,
6
+ database: ENV.DATABASE.database,
7
+ username: ENV.DATABASE.username,
8
+ password: ENV.DATABASE.password,
9
+ define: {
10
+ underscored: true,
11
+ timestamps: true,
12
+ },
13
+ logging: false,
14
+ };
@@ -0,0 +1,13 @@
1
+ declare const ENV: {
2
+ NODE_ENV: string;
3
+ ALLOW_CORS: boolean;
4
+ PORT: number;
5
+ DATABASE: {
6
+ dialect: string;
7
+ host: string;
8
+ database: string;
9
+ username: string;
10
+ password: string;
11
+ };
12
+ };
13
+ export default ENV;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const ENV = {
4
+ NODE_ENV: process.env.SERVER_ENV == 'development' ? 'development' : 'production',
5
+ ALLOW_CORS: process.env.ALLOW_CORS == 'ALLOW' ? true : false,
6
+ PORT: process.env.SERVER_PORT ? parseInt(process.env.SERVER_PORT) : 3000,
7
+ DATABASE: {
8
+ dialect: process.env.DATABASE_DIALECT ? process.env.DATABASE_DIALECT : 'postgres',
9
+ host: process.env.DATABASE_HOST ? process.env.DATABASE_HOST : 'localhost',
10
+ database: process.env.DATABASE_DATABASE ? process.env.DATABASE_DATABASE : 'postgres',
11
+ username: process.env.DATABASE_USERNAME ? process.env.DATABASE_USERNAME : 'postgres',
12
+ password: process.env.DATABASE_PASSWORD ? process.env.DATABASE_PASSWORD : '',
13
+ }
14
+ };
15
+ exports.default = ENV;
@@ -0,0 +1,2 @@
1
+ export declare function createArgon2Hash(password_string: string): Promise<string | false>;
2
+ export declare function checkArgon2Password(password_hash: string, password_string: string): Promise<"Match" | "Dont Match">;
@@ -0,0 +1,40 @@
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 argon2_1 = __importDefault(require("argon2"));
16
+ function createArgon2Hash(password_string) {
17
+ return __awaiter(this, void 0, void 0, function* () {
18
+ try {
19
+ let hash = yield argon2_1.default.hash(password_string);
20
+ return hash;
21
+ }
22
+ catch (e) {
23
+ return false;
24
+ }
25
+ });
26
+ }
27
+ exports.createArgon2Hash = createArgon2Hash;
28
+ function checkArgon2Password(password_hash, password_string) {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ try {
31
+ if (yield argon2_1.default.verify(password_hash, password_string))
32
+ return "Match";
33
+ return "Dont Match";
34
+ }
35
+ catch (e) {
36
+ return "Dont Match";
37
+ }
38
+ });
39
+ }
40
+ exports.checkArgon2Password = checkArgon2Password;
@@ -0,0 +1,6 @@
1
+ export interface UserCreateInterface {
2
+ first_name: string;
3
+ email: string;
4
+ password_string: string;
5
+ }
6
+ export declare type PasswordVerifyResult = 'Match' | 'Dont Match';
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ ;
@@ -0,0 +1,7 @@
1
+ import { UserCreateInterface } from "./types";
2
+ export declare function getUserById(id: Number): Promise<any>;
3
+ export declare function getUserByEmail(email: string): Promise<any>;
4
+ export declare function deleteUserById(id: Number): Promise<any>;
5
+ export declare function isUserExist(email: string): Promise<boolean>;
6
+ export declare function createUser(data: UserCreateInterface): Promise<any>;
7
+ export declare function checkUserPassword(email: string, password_string: string): Promise<boolean>;
@@ -0,0 +1,92 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const database_1 = require("./../database/database");
13
+ const User_1 = require("./../database/models/User");
14
+ const password_1 = require("./password");
15
+ User_1.User.init(database_1.dataBase);
16
+ function getUserById(id) {
17
+ return __awaiter(this, void 0, void 0, function* () {
18
+ let result = yield User_1.User.findOne({ where: { id: id.toString() } });
19
+ return (result);
20
+ });
21
+ }
22
+ exports.getUserById = getUserById;
23
+ function getUserByEmail(email) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ let result = yield User_1.User.findOne({ where: { email: email } });
26
+ return (result);
27
+ });
28
+ }
29
+ exports.getUserByEmail = getUserByEmail;
30
+ function deleteUserById(id) {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ let result = yield User_1.User.destroy({ where: { id: id.toString() } });
33
+ return result;
34
+ });
35
+ }
36
+ exports.deleteUserById = deleteUserById;
37
+ function isUserExist(email) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ try {
40
+ let user = yield getUserByEmail(email);
41
+ return Boolean(user);
42
+ }
43
+ catch (e) {
44
+ throw (e);
45
+ }
46
+ });
47
+ }
48
+ exports.isUserExist = isUserExist;
49
+ function createUser(data) {
50
+ return __awaiter(this, void 0, void 0, function* () {
51
+ let user_exist = false;
52
+ try {
53
+ user_exist = yield isUserExist(data.email);
54
+ }
55
+ catch (e) {
56
+ throw (e);
57
+ }
58
+ if (user_exist)
59
+ throw "User exist";
60
+ let hash = yield password_1.createArgon2Hash(data.password_string);
61
+ if (!hash)
62
+ throw "Create argon2 hash error";
63
+ try {
64
+ let user_instance = yield User_1.User.create({ email: data.email,
65
+ first_name: data.first_name,
66
+ password_hash: hash });
67
+ return user_instance;
68
+ }
69
+ catch (e) {
70
+ throw e;
71
+ }
72
+ });
73
+ }
74
+ exports.createUser = createUser;
75
+ function checkUserPassword(email, password_string) {
76
+ return __awaiter(this, void 0, void 0, function* () {
77
+ let user;
78
+ try {
79
+ user = yield getUserByEmail(email);
80
+ }
81
+ catch (e) {
82
+ return false;
83
+ }
84
+ if (!user)
85
+ return false;
86
+ let hash = user.dataValues.password_hash;
87
+ if ((yield password_1.checkArgon2Password(hash, password_string)) == 'Match')
88
+ return true;
89
+ return false;
90
+ });
91
+ }
92
+ exports.checkUserPassword = checkUserPassword;
@@ -0,0 +1 @@
1
+ export declare function JSONResponse(is_ok: boolean, error_code?: number, error_message?: string, data?: any): string;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function JSONResponse(is_ok, error_code = 0, error_message = '', data = {}) {
4
+ const ret_data = {
5
+ is_ok: is_ok,
6
+ error_code: error_code,
7
+ error_message: error_message,
8
+ data: data,
9
+ };
10
+ return JSON.stringify(ret_data);
11
+ }
12
+ exports.JSONResponse = JSONResponse;
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ module.exports = {
4
+ async up (queryInterface, Sequelize) {
5
+
6
+ return await queryInterface.createTable('users',
7
+ { id: {
8
+ type:Sequelize.INTEGER,
9
+ primaryKey:true,
10
+ autoIncrement:true,
11
+ allowNull:false
12
+ },
13
+ first_name:{
14
+ type:Sequelize.STRING,
15
+ allowNull:false,
16
+ } ,
17
+ email:{
18
+ type:Sequelize.STRING,
19
+ unique:true,
20
+ allowNull:false,
21
+ },
22
+ password_hash:{
23
+ type:Sequelize.STRING(500),
24
+ },
25
+ is_active:{
26
+ type:Sequelize.BOOLEAN,
27
+ defaultValue:true,
28
+ },
29
+ created_at:{
30
+ type:Sequelize.DATE,
31
+ allowNull:false,
32
+ },
33
+ updated_at:{
34
+ type:Sequelize.DATE,
35
+ allowNull:false,
36
+ },
37
+ });
38
+
39
+ },
40
+
41
+ async down (queryInterface, Sequelize) {
42
+ return await queryInterface.dropTable('users');
43
+ }
44
+ };
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "serverpreconfigured",
3
+ "version": "1.0.0",
4
+ "description": "\"Pre-configured server with authentication system and database integration\"",
5
+ "main": "dist/server.js",
6
+ "type": "commonjs",
7
+ "scripts": {
8
+ "test": "echo \"Error: no test specified\" && exit 1",
9
+ "start": "node ./dist/server.js",
10
+ "dev": "npx nodemon"
11
+ },
12
+ "author": "Rafael Floriani Pinto",
13
+ "license": "MIT",
14
+ "dependencies": {
15
+ "@types/cors": "^2.8.12",
16
+ "@types/express": "^4.17.13",
17
+ "@types/express-session": "^1.17.4",
18
+ "argon2": "^0.28.5",
19
+ "body-parser": "^1.19.2",
20
+ "cors": "^2.8.5",
21
+ "express": "^4.17.3",
22
+ "express-session": "^1.17.2",
23
+ "meta-sanitizer": "^2.0.2",
24
+ "nodemon": "^2.0.15",
25
+ "pg": "^8.7.3",
26
+ "pg-hstore": "^2.3.4",
27
+ "sequelize": "^7.0.0-alpha.9",
28
+ "sequelize-cli": "^6.4.1",
29
+ "sucrase": "^3.20.3",
30
+ "typescript": "^4.6.2"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "^17.0.21"
34
+ }
35
+ }
@@ -0,0 +1,8 @@
1
+ import { getSessionValue } from "../sessions/secureget";
2
+ import { SESSION_LOGGED_DATA } from "./config";
3
+ export function userIsLogged(req:any):boolean{
4
+ let user=getSessionValue(req,SESSION_LOGGED_DATA);
5
+ if(user)
6
+ return true;
7
+ return false;
8
+ }
@@ -0,0 +1 @@
1
+ export const SESSION_LOGGED_DATA='email';
@@ -0,0 +1,5 @@
1
+ //@ts-ignore
2
+ //@ts-nocheck
3
+ import {Sequelize} from "sequelize";
4
+ import config from "./../settings/database/database";
5
+ export const dataBase=new Sequelize(config);
@@ -0,0 +1,20 @@
1
+ import { Model } from "sequelize";
2
+ import { DataTypes } from "sequelize";
3
+
4
+ export class User extends Model{
5
+ static init(sequelize:any){
6
+ super.init({
7
+ first_name:DataTypes.STRING,
8
+ email:DataTypes.STRING,
9
+ is_active:DataTypes.BOOLEAN,
10
+ password_hash:DataTypes.STRING,
11
+ },
12
+ {
13
+ sequelize:sequelize,
14
+ tableName: 'users',
15
+ }
16
+ );
17
+ }
18
+ }
19
+
20
+
@@ -0,0 +1,7 @@
1
+ import cors from 'cors';
2
+ import ENV from '../settings/env';
3
+
4
+ export function initCors(app:any){
5
+ if(ENV.ALLOW_CORS)
6
+ app.use(cors());
7
+ }
@@ -0,0 +1,5 @@
1
+ import express from "express";
2
+ export function initPostReader(app:any){
3
+ app.use(express.json());
4
+ app.use(express.urlencoded({extended:true}));
5
+ }
@@ -0,0 +1,14 @@
1
+ import session from "express-session";
2
+ import ENV from "../settings/env";
3
+ export function initSessions(app:any){
4
+ app.set('trust proxy', 1) // trust first proxy
5
+ app.use(session({
6
+ secret: 'keyboard cat',
7
+ resave: false,
8
+ saveUninitialized: true,
9
+ cookie: { secure: ENV.NODE_ENV=='development'?false:true,
10
+ httpOnly:true,
11
+ },
12
+ }));
13
+
14
+ }
@@ -0,0 +1,42 @@
1
+ import express from "express";
2
+ import { deleteSessionValue ,setSessionValue} from "../sessions/secureset";
3
+ import { SESSION_LOGGED_DATA } from "../auth/config";
4
+ import { JSONResponse } from "../utils/response";
5
+ import { userIsLogged } from "../auth/auth";
6
+ import meta_sanitizer from 'meta-sanitizer';
7
+ import { checkUserPassword } from "../users/users";
8
+ enum LoginErrorCode{
9
+ NoError=0,
10
+ InvalidParams,
11
+ InvalidPassword,
12
+
13
+ }
14
+ const router=express.Router();
15
+ router.post('/logout',(req,res)=>{
16
+ let is_ok=false;
17
+ if(userIsLogged(req)){
18
+ deleteSessionValue(req,SESSION_LOGGED_DATA);
19
+ is_ok=true;
20
+ }
21
+ res.send(JSONResponse(is_ok,0,is_ok?"":"User Must be logged",{}));
22
+ });
23
+ router.post('/login',async (req,res)=>{
24
+ let email="";
25
+ let password="";
26
+ try{
27
+ email=meta_sanitizer.sanitizeEmail(req.body.email);
28
+ password=meta_sanitizer.queryProtector(req.body.password);
29
+ }catch(e){
30
+ return res.send(JSONResponse(false,LoginErrorCode.InvalidParams,"Must have 'email' and 'password' params"))
31
+ }
32
+ if(password==""||email=="")
33
+ return res.send(JSONResponse(false,LoginErrorCode.InvalidParams,"Must have 'email' and 'password' params"));
34
+ const checkPass=await checkUserPassword(email,password);
35
+ if(checkPass){
36
+ setSessionValue(req,SESSION_LOGGED_DATA,email);
37
+ return res.send(JSONResponse(true,LoginErrorCode.NoError,"Login Ok"));
38
+ }
39
+ return res.send(JSONResponse(false,LoginErrorCode.InvalidPassword,"Invalid Password"));
40
+ });
41
+
42
+ export default router;
package/src/server.ts ADDED
@@ -0,0 +1,36 @@
1
+ import express from "express";
2
+ import { initSessions } from "./modules/sessions";
3
+ import { initPostReader } from "./modules/postreader";
4
+ import { initCors } from "./modules/initcors";
5
+ import ENV from "./settings/env";
6
+ import authRouter from "./routes/auth";
7
+ export default class ExpressServer{
8
+ app:any;
9
+ authBaseUrl:string;
10
+ usePort:number;
11
+ constructor(){
12
+ this.authBaseUrl="";
13
+ this.usePort=ENV.PORT;
14
+ this.app=express();
15
+ this.initModules();
16
+ }
17
+ listen(port:any=null){
18
+ if(port!=null)
19
+ this.usePort=parseInt(port);
20
+ this.app.listen(this.usePort);
21
+ }
22
+
23
+ initModules(){
24
+ initSessions(this.app);
25
+ initPostReader(this.app);
26
+ initCors(this.app);
27
+ }
28
+ initAuthSystem(baseUrl:string='/user'){
29
+ this.authBaseUrl=baseUrl;
30
+ this.app.use(this.authBaseUrl,authRouter);
31
+ }
32
+
33
+ getApp(){
34
+ return this.app;
35
+ }
36
+ }
@@ -0,0 +1,3 @@
1
+ export function getSessionValue(req:any,get:string){
2
+ return req.session[get];
3
+ }
@@ -0,0 +1,7 @@
1
+ export function setSessionValue(req:any,to:string,value:any){
2
+ req.session[to]=value;
3
+ }
4
+
5
+ export function deleteSessionValue(req:any,to:string){
6
+ setSessionValue(req,to,undefined);
7
+ }
@@ -0,0 +1,14 @@
1
+ const ENV=require("./../env").default;
2
+ module.exports={
3
+ dialect:ENV.DATABASE.dialect,
4
+ host:ENV.DATABASE.host,
5
+ database:ENV.DATABASE.database,
6
+ username:ENV.DATABASE.username,
7
+ password:ENV.DATABASE.password,
8
+ define:{
9
+ underscored:true,
10
+ timestamps:true,
11
+ },
12
+ logging:false,
13
+
14
+ };
@@ -0,0 +1,13 @@
1
+ const ENV={
2
+ NODE_ENV:process.env.SERVER_ENV=='development'?'development':'production',
3
+ ALLOW_CORS:process.env.ALLOW_CORS=='ALLOW'?true:false,
4
+ PORT:process.env.SERVER_PORT?parseInt(process.env.SERVER_PORT):3000,
5
+ DATABASE:{
6
+ dialect:process.env.DATABASE_DIALECT?process.env.DATABASE_DIALECT:'postgres',
7
+ host:process.env.DATABASE_HOST?process.env.DATABASE_HOST:'localhost',
8
+ database:process.env.DATABASE_DATABASE?process.env.DATABASE_DATABASE:'postgres',
9
+ username:process.env.DATABASE_USERNAME?process.env.DATABASE_USERNAME:'postgres',
10
+ password:process.env.DATABASE_PASSWORD?process.env.DATABASE_PASSWORD:'',
11
+ }
12
+ };
13
+ export default ENV;
@@ -0,0 +1,20 @@
1
+ import argon2 from "argon2";
2
+ import {PasswordVerifyResult} from './types';
3
+ export async function createArgon2Hash(password_string:string){
4
+ try{
5
+ let hash=await argon2.hash(password_string);
6
+ return hash;
7
+ }catch(e){
8
+ return false;
9
+ }
10
+ }
11
+
12
+ export async function checkArgon2Password(password_hash:string,password_string:string){
13
+ try{
14
+ if(await argon2.verify(password_hash,password_string))
15
+ return "Match";
16
+ return "Dont Match";
17
+ }catch(e){
18
+ return "Dont Match";
19
+ }
20
+ }
@@ -0,0 +1,6 @@
1
+ export interface UserCreateInterface{
2
+ first_name:string,
3
+ email:string,
4
+ password_string:string
5
+ };
6
+ export type PasswordVerifyResult='Match'|'Dont Match';
@@ -0,0 +1,64 @@
1
+ import {dataBase} from "./../database/database";
2
+ import { User } from "./../database/models/User";
3
+ import { createArgon2Hash,checkArgon2Password } from "./password";
4
+ import {UserCreateInterface} from "./types";
5
+ User.init(dataBase);
6
+ export async function getUserById(id:Number){
7
+ let result=await User.findOne({where:{id:id.toString()}});
8
+ return (result);
9
+ }
10
+
11
+ export async function getUserByEmail(email:string){
12
+ let result=await User.findOne({where:{email:email}});
13
+ return (result);
14
+ }
15
+
16
+ export async function deleteUserById(id:Number){
17
+ let result=await User.destroy({where:{id:id.toString()}});
18
+ return result;
19
+ }
20
+ export async function isUserExist(email:string) {
21
+ try{
22
+ let user=await getUserByEmail(email);
23
+ return Boolean(user);
24
+ }catch(e){
25
+ throw (e);
26
+ }
27
+ }
28
+
29
+ export async function createUser(data:UserCreateInterface){
30
+ let user_exist=false;
31
+ try{
32
+ user_exist=await isUserExist(data.email);
33
+ }catch(e){
34
+ throw(e);
35
+ }
36
+ if(user_exist)
37
+ throw "User exist";
38
+ let hash=await createArgon2Hash(data.password_string);
39
+ if(!hash)
40
+ throw "Create argon2 hash error";
41
+ try{
42
+ let user_instance=await User.create({email:data.email,
43
+ first_name:data.first_name,
44
+ password_hash:hash});
45
+ return user_instance;
46
+ }catch(e){
47
+ throw e;
48
+ }
49
+ }
50
+
51
+ export async function checkUserPassword(email:string,password_string:string):Promise<boolean>{
52
+ let user;
53
+ try{
54
+ user=await getUserByEmail(email);
55
+ }catch(e){
56
+ return false;
57
+ }
58
+ if(!user)
59
+ return false;
60
+ let hash=user.dataValues.password_hash;
61
+ if(await checkArgon2Password(hash,password_string)=='Match')
62
+ return true;
63
+ return false;
64
+ }
@@ -0,0 +1,9 @@
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);
9
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
4
+ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
5
+ "skipLibCheck": true,
6
+ // "lib": [], /* Specify library files to be included in the compilation. */
7
+ "allowJs": true, /* Allow javascript files to be compiled. */
8
+ "checkJs": false, /* Report errors in .js files. */
9
+ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
10
+ "declaration": true, /* Generates corresponding '.d.ts' file. */
11
+ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
12
+ // "sourceMap": true, /* Generates corresponding '.map' file. */
13
+ // "outFile": "./", /* Concatenate and emit output to single file. */
14
+ "outDir": "./dist", /* Redirect output structure to the directory. */
15
+ "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
16
+ // "composite": true, /* Enable project compilation */
17
+ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
18
+ // "removeComments": true, /* Do not emit comments to output. */
19
+ // "noEmit": true, /* Do not emit outputs. */
20
+ // "importHelpers": true, /* Import emit helpers from 'tslib'. */
21
+ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
22
+ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
23
+
24
+ /* Strict Type-Checking Options */
25
+ "strict": true, /* Enable all strict type-checking options. */
26
+ // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
27
+ // "strictNullChecks": true, /* Enable strict null checks. */
28
+ // "strictFunctionTypes": true, /* Enable strict checking of function types. */
29
+ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
30
+ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
31
+ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
32
+ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
33
+
34
+ /* Additional Checks */
35
+ // "noUnusedLocals": true, /* Report errors on unused locals. */
36
+ // "noUnusedParameters": true, /* Report errors on unused parameters. */
37
+ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
38
+ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
39
+
40
+ /* Module Resolution Options */
41
+ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
42
+ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
43
+ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
44
+ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
45
+ "typeRoots": ["./typings"], /* List of folders to include type definitions from. */
46
+ // "types": [], /* Type declaration files to be included in compilation. */
47
+ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
48
+ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
49
+ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
50
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
51
+
52
+ /* Source Map Options */
53
+ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
54
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
55
+ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
56
+ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
57
+
58
+ /* Experimental Options */
59
+ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
60
+ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
61
+
62
+ /* Advanced Options */
63
+ "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
64
+ },
65
+ "exclude": ["node_modules"],
66
+ "include": ["src"]
67
+
68
+ }