Procházet zdrojové kódy

Изменения механизма ограничения доступа

Book Pauk před 2 roky
rodič
revize
59b4f48897

+ 21 - 1
client/components/Api/Api.vue

@@ -60,10 +60,21 @@ const componentOptions = {
         settings() {
             this.loadSettings();
         },
+        modelValue(newValue) {
+            this.accessGranted = newValue;
+        },
+        accessGranted(newValue) {
+            this.$emit('update:modelValue', newValue);
+        }
     },
 };
 class Api {
     _options = componentOptions;
+    _props = {
+        modelValue: Boolean,
+    };
+    accessGranted = false;
+
     busyDialogVisible = false;
     mainMessage = '';
     jobMessage = '';
@@ -123,7 +134,13 @@ class Api {
             });
 
             if (result && result.value) {
-                const accessToken = utils.toHex(cryptoUtils.sha256(result.value));
+                //получим свежую соль
+                const response = await wsc.message(await wsc.send({}), 10);
+                let salt = '';
+                if (response && response.error == 'need_access_token' && response.salt)
+                    salt = response.salt;
+
+                const accessToken = utils.toHex(cryptoUtils.sha256(result.value + salt));
                 this.commit('setSettings', {accessToken});
             }
         } finally {
@@ -192,10 +209,13 @@ class Api {
                 const response = await wsc.message(await wsc.send(params), timeoutSecs);
 
                 if (response && response.error == 'need_access_token') {
+                    this.accessGranted = false;
                     await this.showPasswordDialog();
                 } else if (response && response.error == 'server_busy') {
+                    this.accessGranted = true;
                     await this.showBusyDialog();
                 } else {
+                    this.accessGranted = true;
                     if (response.error) {
                         throw new Error(response.error);
                     }

+ 3 - 2
client/components/App.vue

@@ -1,10 +1,10 @@
 <template>
     <div class="fit row">
-        <Api ref="api" />
+        <Api ref="api" v-model="accessGranted" />
         <Notify ref="notify" />
         <StdDialog ref="stdDialog" />
 
-        <router-view v-slot="{ Component }">
+        <router-view v-if="accessGranted" v-slot="{ Component }">
             <keep-alive>
                 <component :is="Component" class="col" />
             </keep-alive>
@@ -37,6 +37,7 @@ const componentOptions = {
 };
 class App {
     _options = componentOptions;
+    accessGranted = false;
 
     created() {
         this.commit = this.$store.commit;

+ 1 - 0
server/config/base.js

@@ -11,6 +11,7 @@ module.exports = {
     execDir,
 
     accessPassword: '',
+    accessTimeout: 0,
     bookReadLink: '',
     loggingEnabled: true,
 

+ 1 - 0
server/config/index.js

@@ -6,6 +6,7 @@ const branchFilename = __dirname + '/application_env';
 
 const propsToSave = [
     'accessPassword',
+    'accessTimeout',
     'bookReadLink',
     'loggingEnabled',
     'dbCacheSize',

+ 54 - 7
server/controllers/WebSocketController.js

@@ -6,16 +6,18 @@ const WebWorker = require('../core/WebWorker');//singleton
 const log = new (require('../core/AppLogger'))().log;//singleton
 const utils = require('../core/utils');
 
-const cleanPeriod = 1*60*1000;//1 минута
+const cleanPeriod = 1*60*1000;//1 минута, не менять!
+const cleanUnusedTokenTimeout = 5*60*1000;//5 минут
 const closeSocketOnIdle = 5*60*1000;//5 минут
 
 class WebSocketController {
     constructor(wss, config) {
         this.config = config;
         this.isDevelopment = (config.branch == 'development');
-        this.accessToken = '';
-        if (config.accessPassword)
-            this.accessToken = utils.getBufHash(config.accessPassword, 'sha256', 'hex');
+
+        this.freeAccess = (config.accessPassword === '');
+        this.accessTimeout = config.accessTimeout*60*1000;
+        this.accessMap = new Map();
 
         this.workerState = new WorkerState();
         this.webWorker = new WebWorker(config);
@@ -38,6 +40,19 @@ class WebSocketController {
     periodicClean() {
         try {
             const now = Date.now();
+
+            //почистим accessMap
+            if (!this.freeAccess) {
+                for (const [accessToken, accessRec] of this.accessMap) {
+                    if (   !(accessRec.used > 0 || now - accessRec.time < cleanUnusedTokenTimeout)
+                        || !(this.accessTimeout === 0 || now - accessRec.time < this.accessTimeout)
+                        ) {
+                        this.accessMap.delete(accessToken);
+                    }
+                }
+            }
+
+            //почистим ws-клиентов
             this.wss.clients.forEach((ws) => {
                 if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
                     ws.terminate();
@@ -48,6 +63,24 @@ class WebSocketController {
         }
     }
 
+    hasAccess(accessToken) {
+        if (this.freeAccess)
+            return true;
+
+        const accessRec = this.accessMap.get(accessToken);
+        if (accessRec) {
+            const now = Date.now();
+
+            if (this.accessTimeout === 0 || now - accessRec.time < this.accessTimeout) {
+                accessRec.used++;
+                accessRec.time = now;
+                return true;
+            }
+        }
+
+        return false;
+    }
+
     async onMessage(ws, message) {
         let req = {};
         try {
@@ -62,14 +95,23 @@ class WebSocketController {
             //pong for WebSocketConnection
             this.send({_rok: 1}, req, ws);
 
-            if (this.accessToken && req.accessToken !== this.accessToken) {
-                await utils.sleep(1000);
-                throw new Error('need_access_token');
+            //access
+            if (!this.hasAccess(req.accessToken)) {
+                await utils.sleep(500);
+                const salt = utils.randomHexString(32);
+                const accessToken = utils.getBufHash(this.config.accessPassword + salt, 'sha256', 'hex');
+                this.accessMap.set(accessToken, {time: Date.now(), used: 0});
+
+                this.send({error: 'need_access_token', salt}, req, ws);
+                return;
             }
 
+            //api
             switch (req.action) {
                 case 'test':
                     await this.test(req, ws); break;
+                case 'logout':
+                    await this.logout(req, ws); break;
                 case 'get-config':
                     await this.getConfig(req, ws); break;
                 case 'get-worker-state':
@@ -120,6 +162,11 @@ class WebSocketController {
         this.send({message: `${this.config.name} project is awesome`}, req, ws);
     }
 
+    async logout(req, ws) {
+        this.accessMap.delete(req.accessToken);
+        this.send({success: true}, req, ws);
+    }
+
     async getConfig(req, ws) {
         const config = _.pick(this.config, this.config.webConfigParams);
         config.dbConfig = await this.webWorker.dbConfig();