serverpreconfigured 1.0.2 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ import { Model } from "sequelize";
2
+ export declare class WebSocketAuth extends Model {
3
+ token: string;
4
+ expiration: Date;
5
+ auth_connection_token: string;
6
+ static init(sequelize: any): void;
7
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const sequelize_1 = require("sequelize");
4
+ const sequelize_2 = require("sequelize");
5
+ class WebSocketAuth extends sequelize_1.Model {
6
+ static init(sequelize) {
7
+ super.init({
8
+ token: sequelize_2.DataTypes.STRING,
9
+ expiration: sequelize_2.DataTypes.DATE,
10
+ user_id: sequelize_2.DataTypes.INTEGER,
11
+ is_active: sequelize_2.DataTypes.BOOLEAN,
12
+ auth_connection_token: sequelize_2.DataTypes.STRING,
13
+ }, {
14
+ sequelize: sequelize,
15
+ tableName: 'spc_wsauth'
16
+ });
17
+ }
18
+ }
19
+ exports.WebSocketAuth = WebSocketAuth;
@@ -2,9 +2,11 @@ export default class ExpressServer {
2
2
  app: any;
3
3
  authBaseUrl: string;
4
4
  usePort: number;
5
+ wsAuthBaseUrl: string;
5
6
  constructor();
6
7
  listen(port?: any): void;
7
8
  initModules(): void;
8
9
  initAuthSystem(baseUrl?: string): void;
10
+ initWSAuthSystem(wsBaseUrl?: string): void;
9
11
  getApp(): any;
10
12
  }
@@ -8,10 +8,12 @@ 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 auth_1 = __importDefault(require("./routes/auth"));
11
+ const users_1 = __importDefault(require("./routes/users"));
12
+ const wsauth_1 = require("./routes/wsauth");
12
13
  class ExpressServer {
13
14
  constructor() {
14
15
  this.authBaseUrl = "";
16
+ this.wsAuthBaseUrl = "";
15
17
  this.usePort = env_1.default.PORT;
16
18
  this.app = express_1.default();
17
19
  this.initModules();
@@ -28,7 +30,11 @@ class ExpressServer {
28
30
  }
29
31
  initAuthSystem(baseUrl = '/user') {
30
32
  this.authBaseUrl = baseUrl;
31
- this.app.use(this.authBaseUrl, auth_1.default);
33
+ this.app.use(this.authBaseUrl, users_1.default);
34
+ }
35
+ initWSAuthSystem(wsBaseUrl = '/ws') {
36
+ this.wsAuthBaseUrl = wsBaseUrl;
37
+ this.app.use(this.wsAuthBaseUrl, wsauth_1.router);
32
38
  }
33
39
  getApp() {
34
40
  return this.app;
@@ -0,0 +1,2 @@
1
+ declare const router: import("express-serve-static-core").Router;
2
+ export default router;
@@ -0,0 +1,80 @@
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
+ const users_2 = require("../users/users");
23
+ var LoginErrorCode;
24
+ (function (LoginErrorCode) {
25
+ LoginErrorCode[LoginErrorCode["NoError"] = 0] = "NoError";
26
+ LoginErrorCode[LoginErrorCode["InvalidParams"] = 1] = "InvalidParams";
27
+ LoginErrorCode[LoginErrorCode["InvalidPassword"] = 2] = "InvalidPassword";
28
+ })(LoginErrorCode || (LoginErrorCode = {}));
29
+ var RegisterUserErrorCode;
30
+ (function (RegisterUserErrorCode) {
31
+ RegisterUserErrorCode[RegisterUserErrorCode["NoError"] = 0] = "NoError";
32
+ RegisterUserErrorCode[RegisterUserErrorCode["InvalidParams"] = 1] = "InvalidParams";
33
+ RegisterUserErrorCode[RegisterUserErrorCode["UserExist"] = 2] = "UserExist";
34
+ RegisterUserErrorCode[RegisterUserErrorCode["InternalError"] = 3] = "InternalError";
35
+ })(RegisterUserErrorCode || (RegisterUserErrorCode = {}));
36
+ const router = express_1.default.Router();
37
+ router.post('/logout', (req, res) => {
38
+ let is_ok = false;
39
+ if (auth_1.userIsLogged(req)) {
40
+ secureset_1.deleteSessionValue(req, config_1.SESSION_LOGGED_DATA);
41
+ is_ok = true;
42
+ }
43
+ res.send(response_1.JSONResponse(is_ok, 0, is_ok ? "" : "User Must be logged", {}));
44
+ });
45
+ router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
46
+ let email = "";
47
+ let password = "";
48
+ try {
49
+ email = meta_sanitizer_1.default.sanitizeEmail(req.body.email);
50
+ password = meta_sanitizer_1.default.queryProtector(req.body.password);
51
+ }
52
+ catch (e) {
53
+ return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidParams, "Must have 'email' and 'password' params"));
54
+ }
55
+ if (password == "" || email == "")
56
+ return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidParams, "Must have 'email' and 'password' params"));
57
+ const checkPass = yield users_1.checkUserPassword(email, password);
58
+ if (checkPass) {
59
+ secureset_1.setSessionValue(req, config_1.SESSION_LOGGED_DATA, email);
60
+ return res.send(response_1.JSONResponse(true, LoginErrorCode.NoError, "Login Ok"));
61
+ }
62
+ return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidPassword, "Invalid Password"));
63
+ }));
64
+ router.post('/register', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
65
+ try {
66
+ let email = meta_sanitizer_1.default.sanitizeEmail(req.body.email || '');
67
+ let password = meta_sanitizer_1.default.queryProtector(req.body.password || '');
68
+ let name = meta_sanitizer_1.default.SanitizerEngine(req.body.name || '', true, false, [' ']).sanitizedData;
69
+ if (email == "" || password == "" || name == "")
70
+ return res.send(response_1.JSONResponse(false, RegisterUserErrorCode.InvalidParams, "Invalid params"));
71
+ yield users_2.createUser({ first_name: name, email: email, password_string: password });
72
+ return res.send(response_1.JSONResponse(true, RegisterUserErrorCode.NoError, "", "REGISTER OK"));
73
+ }
74
+ catch (e) {
75
+ if (e === "User exist")
76
+ return res.send(response_1.JSONResponse(false, RegisterUserErrorCode.UserExist, "User Exist"));
77
+ return res.send(response_1.JSONResponse(false, RegisterUserErrorCode.InternalError, "I-Error"));
78
+ }
79
+ }));
80
+ exports.default = router;
@@ -0,0 +1 @@
1
+ export declare const router: import("express-serve-static-core").Router;
@@ -0,0 +1,45 @@
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 wsauth_1 = require("../wsauth/wsauth");
19
+ const users_1 = require("../users/users");
20
+ const server_1 = require("../server");
21
+ const config_1 = require("../auth/config");
22
+ exports.router = express_1.default.Router();
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
+ exports.router.post('/gettoken', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
31
+ if (!auth_1.userIsLogged(req))
32
+ return res.send(response_1.JSONResponse(false, GenerateTokenError.UserMustBeLogged, "User Must Be Logged"));
33
+ try {
34
+ let userId = yield users_1.getUserIdByUserEmail(server_1.getSessionValue(req, config_1.SESSION_LOGGED_DATA));
35
+ if (userId == NaN)
36
+ return res.send(response_1.JSONResponse(false, GenerateTokenError.GetUserError, "Get user error"));
37
+ let n = yield wsauth_1.setWSAuthDataNewToken(userId);
38
+ return res.send(response_1.JSONResponse(true, 0, "", { token: n.dataValues.token,
39
+ expiration: n.dataValues.expiration,
40
+ userId: userId
41
+ }));
42
+ }
43
+ catch (e) {
44
+ }
45
+ }));
package/dist/server.d.ts CHANGED
@@ -4,5 +4,9 @@ export { dataBase } from "./database/database";
4
4
  export { setSessionValue, deleteSessionValue } from "./sessions/secureset";
5
5
  export { getSessionValue } from "./sessions/secureget";
6
6
  export { checkUserPassword } from "./users/users";
7
+ export { WebSocketAuth } from "./database/models/WSAuth";
8
+ export { checkWSAuthToken, authenticateWS, checkConnectionAuth } from "./wsauth/wsauth";
9
+ export { randomString } from "./utils/string/random";
10
+ export { JSONResponse } from "./utils/response";
7
11
  import ExpressServer from "./expressServer";
8
12
  export default ExpressServer;
package/dist/server.js CHANGED
@@ -17,5 +17,15 @@ var secureget_1 = require("./sessions/secureget");
17
17
  exports.getSessionValue = secureget_1.getSessionValue;
18
18
  var users_1 = require("./users/users");
19
19
  exports.checkUserPassword = users_1.checkUserPassword;
20
+ var WSAuth_1 = require("./database/models/WSAuth");
21
+ exports.WebSocketAuth = WSAuth_1.WebSocketAuth;
22
+ var wsauth_1 = require("./wsauth/wsauth");
23
+ exports.checkWSAuthToken = wsauth_1.checkWSAuthToken;
24
+ exports.authenticateWS = wsauth_1.authenticateWS;
25
+ exports.checkConnectionAuth = wsauth_1.checkConnectionAuth;
26
+ var random_1 = require("./utils/string/random");
27
+ exports.randomString = random_1.randomString;
28
+ var response_1 = require("./utils/response");
29
+ exports.JSONResponse = response_1.JSONResponse;
20
30
  const expressServer_1 = __importDefault(require("./expressServer"));
21
31
  exports.default = expressServer_1.default;
@@ -1,2 +1,3 @@
1
+ import { PasswordVerifyResult } from './types';
1
2
  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">;
3
+ export declare function checkArgon2Password(password_hash: string, password_string: string): Promise<PasswordVerifyResult>;
@@ -1,6 +1,7 @@
1
1
  import { UserCreateInterface } from "./types";
2
2
  export declare function getUserById(id: Number): Promise<any>;
3
3
  export declare function getUserByEmail(email: string): Promise<any>;
4
+ export declare function getUserIdByUserEmail(email: string): Promise<number>;
4
5
  export declare function deleteUserById(id: Number): Promise<any>;
5
6
  export declare function isUserExist(email: string): Promise<boolean>;
6
7
  export declare function createUser(data: UserCreateInterface): Promise<any>;
@@ -27,6 +27,20 @@ function getUserByEmail(email) {
27
27
  });
28
28
  }
29
29
  exports.getUserByEmail = getUserByEmail;
30
+ function getUserIdByUserEmail(email) {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ try {
33
+ let u = yield getUserByEmail(email);
34
+ if (!Boolean(u))
35
+ return NaN;
36
+ return u.dataValues.id;
37
+ }
38
+ catch (e) {
39
+ return NaN;
40
+ }
41
+ });
42
+ }
43
+ exports.getUserIdByUserEmail = getUserIdByUserEmail;
30
44
  function deleteUserById(id) {
31
45
  return __awaiter(this, void 0, void 0, function* () {
32
46
  let result = yield User_1.User.destroy({ where: { id: id.toString() } });
@@ -0,0 +1 @@
1
+ export declare function randomString(length: number): string;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function randomString(length) {
4
+ var result = '';
5
+ var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
6
+ var charactersLength = characters.length;
7
+ for (var i = 0; i < length; i++) {
8
+ result += characters.charAt(Math.floor(Math.random() *
9
+ charactersLength));
10
+ }
11
+ return result;
12
+ }
13
+ exports.randomString = randomString;
@@ -0,0 +1,4 @@
1
+ export declare enum AuthenticateWSResult {
2
+ OK = 1,
3
+ InvalidToken = 2
4
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var AuthenticateWSResult;
4
+ (function (AuthenticateWSResult) {
5
+ AuthenticateWSResult[AuthenticateWSResult["OK"] = 1] = "OK";
6
+ AuthenticateWSResult[AuthenticateWSResult["InvalidToken"] = 2] = "InvalidToken";
7
+ })(AuthenticateWSResult = exports.AuthenticateWSResult || (exports.AuthenticateWSResult = {}));
@@ -0,0 +1,6 @@
1
+ import { AuthenticateWSResult } from "./types";
2
+ export declare function getWSAuthDataByUserId(userId: number): Promise<any>;
3
+ export declare function setWSAuthDataNewToken(userId: number, expiration_hours?: number): Promise<any>;
4
+ export declare function checkWSAuthToken(userId: number, token: string): Promise<boolean>;
5
+ export declare function authenticateWS(userId: number, token: string, connection_token: string): Promise<AuthenticateWSResult>;
6
+ export declare function checkConnectionAuth(userId: number, connection_token: string): Promise<boolean>;
@@ -0,0 +1,113 @@
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 server_1 = require("../server");
13
+ const server_2 = require("../server");
14
+ const random_1 = require("./../utils/string/random");
15
+ const types_1 = require("./types");
16
+ server_1.WebSocketAuth.init(server_2.dataBase);
17
+ function getWSAuthDataByUserId(userId) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ try {
20
+ let u = yield server_1.WebSocketAuth.findOne({ where: { user_id: userId.toString() } });
21
+ return u;
22
+ }
23
+ catch (e) {
24
+ throw e;
25
+ }
26
+ });
27
+ }
28
+ exports.getWSAuthDataByUserId = getWSAuthDataByUserId;
29
+ function setWSAuthDataNewToken(userId, expiration_hours = 72) {
30
+ return __awaiter(this, void 0, void 0, function* () {
31
+ try {
32
+ let ws = yield getWSAuthDataByUserId(userId);
33
+ let token = random_1.randomString(50);
34
+ let expiration = new Date();
35
+ expiration.setTime(expiration.getTime() + expiration_hours * 60 * 60 * 1000);
36
+ if (!Boolean(ws)) {
37
+ return yield server_1.WebSocketAuth.create({ user_id: userId.toString(),
38
+ token: token,
39
+ expiration: expiration,
40
+ is_active: true,
41
+ auth_connection_token: "",
42
+ });
43
+ }
44
+ else {
45
+ ws.token = token;
46
+ ws.expiration = expiration;
47
+ ws.is_active = true;
48
+ ws.auth_connection_token = "";
49
+ return yield ws.save();
50
+ }
51
+ }
52
+ catch (e) {
53
+ throw e;
54
+ }
55
+ });
56
+ }
57
+ exports.setWSAuthDataNewToken = setWSAuthDataNewToken;
58
+ function checkWSAuthToken(userId, token) {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ try {
61
+ let ws = yield getWSAuthDataByUserId(userId);
62
+ if (!Boolean(ws))
63
+ return false;
64
+ if (!ws.dataValues.is_active)
65
+ return false;
66
+ if (ws.dataValues.token != token)
67
+ return false;
68
+ if (Date.now() > ws.dataValues.expiration.getTime())
69
+ return false;
70
+ return true;
71
+ }
72
+ catch (e) {
73
+ throw e;
74
+ }
75
+ });
76
+ }
77
+ exports.checkWSAuthToken = checkWSAuthToken;
78
+ function authenticateWS(userId, token, connection_token) {
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ try {
81
+ if (!(yield checkWSAuthToken(userId, token)))
82
+ return types_1.AuthenticateWSResult.InvalidToken;
83
+ let ws = yield getWSAuthDataByUserId(userId);
84
+ ws.auth_connection_token = connection_token;
85
+ yield ws.save();
86
+ return types_1.AuthenticateWSResult.OK;
87
+ }
88
+ catch (e) {
89
+ throw e;
90
+ }
91
+ });
92
+ }
93
+ exports.authenticateWS = authenticateWS;
94
+ function checkConnectionAuth(userId, connection_token) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ try {
97
+ let ws = yield getWSAuthDataByUserId(userId);
98
+ if (!Boolean(ws))
99
+ return false;
100
+ if (!ws.dataValues.is_active)
101
+ return false;
102
+ if (Date.now() > ws.dataValues.expiration.getTime())
103
+ return false;
104
+ if (ws.dataValues.auth_connection_token !== connection_token)
105
+ return false;
106
+ return true;
107
+ }
108
+ catch (e) {
109
+ throw e;
110
+ }
111
+ });
112
+ }
113
+ exports.checkConnectionAuth = checkConnectionAuth;
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ module.exports = {
4
+ async up (queryInterface, Sequelize) {
5
+ return await queryInterface.createTable('spc_wsauth',
6
+ { id: {
7
+ type:Sequelize.INTEGER,
8
+ primaryKey:true,
9
+ autoIncrement:true,
10
+ allowNull:false
11
+ } ,
12
+ user_id:{
13
+ type:Sequelize.INTEGER,
14
+ references:{model:'spc_users',key:'id'}
15
+ },
16
+ token:{
17
+ type:Sequelize.STRING,
18
+ allowNull:false,
19
+ },
20
+ expiration:{
21
+ type:Sequelize.DATE,
22
+ allowNull:false,
23
+ },
24
+ is_active:{
25
+ type:Sequelize.BOOLEAN,
26
+ allowNull:false,
27
+ defaultValue:true,
28
+ },
29
+ auth_connection_token:{
30
+ type:Sequelize.STRING,
31
+ allowNull:true,
32
+ defaultValue:"",
33
+ },
34
+ created_at:{
35
+ type:Sequelize.DATE,
36
+ allowNull:false,
37
+ },
38
+ updated_at:{
39
+ type:Sequelize.DATE,
40
+ allowNull:false,
41
+ },
42
+ }
43
+
44
+ );
45
+ },
46
+
47
+ async down (queryInterface, Sequelize) {
48
+ return await queryInterface.dropTable('spc_wsauth');
49
+ }
50
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serverpreconfigured",
3
- "version": "1.0.2",
3
+ "version": "1.0.5",
4
4
  "description": "\"Pre-configured server with authentication system and database integration\"",
5
5
  "main": "dist/server.js",
6
6
  "keywords": ["server","pre configured","database","authentication"],
@@ -0,0 +1,19 @@
1
+ import { Model } from "sequelize";
2
+ import { DataTypes } from "sequelize";
3
+ export class WebSocketAuth extends Model{
4
+ declare token:string;
5
+ declare expiration:Date;
6
+ 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
+ }
@@ -3,13 +3,16 @@ import { initSessions } from "./modules/sessions";
3
3
  import { initPostReader } from "./modules/postreader";
4
4
  import { initCors } from "./modules/initcors";
5
5
  import ENV from "./settings/env";
6
- import authRouter from "./routes/auth";
6
+ import authRouter from "./routes/users";
7
+ import { router as wsAuthRoter } from "./routes/wsauth";
7
8
  export default class ExpressServer{
8
9
  app:any;
9
10
  authBaseUrl:string;
10
11
  usePort:number;
12
+ wsAuthBaseUrl:string;
11
13
  constructor(){
12
14
  this.authBaseUrl="";
15
+ this.wsAuthBaseUrl="";
13
16
  this.usePort=ENV.PORT;
14
17
  this.app=express();
15
18
  this.initModules();
@@ -29,6 +32,10 @@ export default class ExpressServer{
29
32
  this.authBaseUrl=baseUrl;
30
33
  this.app.use(this.authBaseUrl,authRouter);
31
34
  }
35
+ initWSAuthSystem(wsBaseUrl:string='/ws'){
36
+ this.wsAuthBaseUrl=wsBaseUrl;
37
+ this.app.use(this.wsAuthBaseUrl,wsAuthRoter);
38
+ }
32
39
 
33
40
  getApp(){
34
41
  return this.app;
@@ -5,12 +5,19 @@ import { JSONResponse } from "../utils/response";
5
5
  import { userIsLogged } from "../auth/auth";
6
6
  import meta_sanitizer from 'meta-sanitizer';
7
7
  import { checkUserPassword } from "../users/users";
8
+ import { createUser } from "../users/users";
8
9
  enum LoginErrorCode{
9
10
  NoError=0,
10
11
  InvalidParams,
11
12
  InvalidPassword,
12
13
 
13
14
  }
15
+ enum RegisterUserErrorCode{
16
+ NoError=0,
17
+ InvalidParams,
18
+ UserExist,
19
+ InternalError
20
+ }
14
21
  const router=express.Router();
15
22
  router.post('/logout',(req,res)=>{
16
23
  let is_ok=false;
@@ -38,5 +45,20 @@ router.post('/login',async (req,res)=>{
38
45
  }
39
46
  return res.send(JSONResponse(false,LoginErrorCode.InvalidPassword,"Invalid Password"));
40
47
  });
48
+ router.post('/register',async (req,res)=>{
49
+ try{
50
+ let email=meta_sanitizer.sanitizeEmail(req.body.email||'');
51
+ let password=meta_sanitizer.queryProtector(req.body.password||'');
52
+ let name=meta_sanitizer.SanitizerEngine(req.body.name||'',true,false,[' ']).sanitizedData;
53
+ if(email=="" || password=="" || name=="")
54
+ return res.send(JSONResponse(false,RegisterUserErrorCode.InvalidParams,"Invalid params"));
55
+ await createUser({first_name:name,email:email,password_string:password});
56
+ return res.send(JSONResponse(true,RegisterUserErrorCode.NoError,"","REGISTER OK"));
57
+ }catch(e){
58
+ if(e==="User exist")
59
+ return res.send(JSONResponse(false,RegisterUserErrorCode.UserExist,"User Exist"));
60
+ return res.send(JSONResponse(false,RegisterUserErrorCode.InternalError,"I-Error"));
61
+ }
62
+ });
41
63
 
42
64
  export default router;
@@ -0,0 +1,29 @@
1
+ import express from "express";
2
+ import { JSONResponse } from "../utils/response";
3
+ import { userIsLogged } from "../auth/auth";
4
+ import { setWSAuthDataNewToken } from "../wsauth/wsauth";
5
+ import { getUserIdByUserEmail } from "../users/users";
6
+ import { getSessionValue } from "../server";
7
+ import { SESSION_LOGGED_DATA } from "../auth/config";
8
+ export const router=express.Router();
9
+ enum GenerateTokenError{
10
+ UserMustBeLogged=1,
11
+ GetUserError,
12
+ InternalError,
13
+ };
14
+ router.post('/gettoken',async (req,res)=>{
15
+ if(!userIsLogged(req))
16
+ return res.send(JSONResponse(false,GenerateTokenError.UserMustBeLogged,"User Must Be Logged"));
17
+ try{
18
+ let userId=await getUserIdByUserEmail(getSessionValue(req,SESSION_LOGGED_DATA));
19
+ if(userId==NaN)
20
+ return res.send(JSONResponse(false,GenerateTokenError.GetUserError,"Get user error"));
21
+ let n=await setWSAuthDataNewToken(userId);
22
+ return res.send(JSONResponse(true,0,"",{token:n.dataValues.token,
23
+ expiration:n.dataValues.expiration,
24
+ userId:userId
25
+ }));
26
+ }catch(e){
27
+
28
+ }
29
+ });
package/src/server.ts CHANGED
@@ -4,5 +4,9 @@ export { dataBase } from "./database/database";
4
4
  export { setSessionValue,deleteSessionValue } from "./sessions/secureset";
5
5
  export { getSessionValue } from "./sessions/secureget";
6
6
  export { checkUserPassword } from "./users/users";
7
+ export { WebSocketAuth } from "./database/models/WSAuth";
8
+ export { checkWSAuthToken ,authenticateWS,checkConnectionAuth} from "./wsauth/wsauth";
9
+ export { randomString } from "./utils/string/random";
10
+ export { JSONResponse } from "./utils/response";
7
11
  import ExpressServer from "./expressServer";
8
- export default ExpressServer;
12
+ export default ExpressServer;
@@ -9,7 +9,7 @@ export async function createArgon2Hash(password_string:string){
9
9
  }
10
10
  }
11
11
 
12
- export async function checkArgon2Password(password_hash:string,password_string:string){
12
+ export async function checkArgon2Password(password_hash:string,password_string:string):Promise<PasswordVerifyResult>{
13
13
  try{
14
14
  if(await argon2.verify(password_hash,password_string))
15
15
  return "Match";
@@ -12,6 +12,16 @@ export async function getUserByEmail(email:string){
12
12
  let result=await User.findOne({where:{email:email}});
13
13
  return (result);
14
14
  }
15
+ export async function getUserIdByUserEmail(email:string):Promise<number>{
16
+ try{
17
+ let u=await getUserByEmail(email);
18
+ if(!Boolean(u))
19
+ return NaN;
20
+ return u.dataValues.id;
21
+ }catch(e){
22
+ return NaN;
23
+ }
24
+ }
15
25
 
16
26
  export async function deleteUserById(id:Number){
17
27
  let result=await User.destroy({where:{id:id.toString()}});
@@ -0,0 +1,10 @@
1
+ export function randomString(length:number):string {
2
+ var result = '';
3
+ var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
4
+ var charactersLength = characters.length;
5
+ for ( var i = 0; i < length; i++ ) {
6
+ result += characters.charAt(Math.floor(Math.random() *
7
+ charactersLength));
8
+ }
9
+ return result;
10
+ }
@@ -0,0 +1,4 @@
1
+ export enum AuthenticateWSResult{
2
+ OK=1,
3
+ InvalidToken,
4
+ }
@@ -0,0 +1,85 @@
1
+ import { WebSocketAuth } from "../server";
2
+ import { dataBase } from "../server";
3
+ import {randomString} from "./../utils/string/random";
4
+ import {AuthenticateWSResult} from "./types";
5
+ WebSocketAuth.init(dataBase);
6
+ export async function getWSAuthDataByUserId(userId:number):Promise<any>{
7
+ try{
8
+ let u=await WebSocketAuth.findOne({where:{user_id:userId.toString()}});
9
+ return u;
10
+ }catch(e){
11
+ throw e;
12
+ }
13
+ }
14
+
15
+ export async function setWSAuthDataNewToken(userId:number,expiration_hours:number=72){
16
+ try{
17
+ let ws=await getWSAuthDataByUserId(userId);
18
+ let token=randomString(50);
19
+ let expiration=new Date();
20
+ expiration.setTime(expiration.getTime()+expiration_hours*60*60*1000);
21
+ if(!Boolean(ws)){
22
+ return await WebSocketAuth.create({user_id:userId.toString(),
23
+ token:token,
24
+ expiration:expiration,
25
+ is_active:true,
26
+ auth_connection_token:"",
27
+ });
28
+ }else{
29
+ ws.token=token;
30
+ ws.expiration=expiration;
31
+ ws.is_active=true;
32
+ ws.auth_connection_token="";
33
+ return await ws.save();
34
+ }
35
+ }catch(e){
36
+ throw e;
37
+ }
38
+ }
39
+
40
+ export async function checkWSAuthToken(userId:number,token:string):Promise<boolean>{
41
+ try{
42
+ let ws=await getWSAuthDataByUserId(userId);
43
+ if(!Boolean(ws))
44
+ return false;
45
+ if(!ws.dataValues.is_active)
46
+ return false;
47
+ if(ws.dataValues.token!=token)
48
+ return false;
49
+ if(Date.now()>ws.dataValues.expiration.getTime())
50
+ return false;
51
+ return true;
52
+ }catch(e){
53
+ throw e;
54
+ }
55
+ }
56
+
57
+ export async function authenticateWS(userId:number,token:string,connection_token:string):Promise<AuthenticateWSResult>{
58
+ try{
59
+ if(!(await checkWSAuthToken(userId,token)))
60
+ return AuthenticateWSResult.InvalidToken;
61
+ let ws=await getWSAuthDataByUserId(userId);
62
+ ws.auth_connection_token=connection_token;
63
+ await ws.save();
64
+ return AuthenticateWSResult.OK;
65
+ }catch(e){
66
+ throw e;
67
+ }
68
+ }
69
+
70
+ export async function checkConnectionAuth(userId:number,connection_token:string):Promise<boolean>{
71
+ try{
72
+ let ws=await getWSAuthDataByUserId(userId);
73
+ if(!Boolean(ws))
74
+ return false;
75
+ if(!ws.dataValues.is_active)
76
+ return false;
77
+ if(Date.now()>ws.dataValues.expiration.getTime())
78
+ return false;
79
+ if(ws.dataValues.auth_connection_token!==connection_token)
80
+ return false;
81
+ return true;
82
+ }catch(e){
83
+ throw e;
84
+ }
85
+ }