Skip to content

Commit

Permalink
fix(socket): make socket persistent (#2888)
Browse files Browse the repository at this point in the history
So we don't lose auth on crash etc.
  • Loading branch information
sogehige committed Oct 27, 2019
1 parent 632eb8d commit 81aa4c5
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/bot/socket.ts
@@ -1,5 +1,5 @@
import Core from './_interface';
import { settings, ui } from './decorators';
import { settings, shared, ui } from './decorators';
import { MINUTE, SECOND } from './constants';
import { isMainThread } from 'worker_threads';
import uuid from 'uuid/v4';
Expand All @@ -16,9 +16,10 @@ type Auth = {
refreshTokenTimestamp: number;
};

let sockets: Auth[] = [];

class Socket extends Core {
@shared(true)
socketsTokenAuthList: Auth[] = [];

@settings('connection')
accessTokenExpirationTime = 120;

Expand All @@ -43,15 +44,15 @@ class Socket extends Core {

if (isMainThread) {
setInterval(() => {
sockets = sockets.filter(socket => {
this.socketsTokenAuthList = this.socketsTokenAuthList.filter(socket => {
const isAccessTokenExpired = socket.accessTokenTimestamp + (this.accessTokenExpirationTime * 1000) < Date.now();
const isRefreshTokenExpired = socket.refreshTokenTimestamp + (this.refreshTokenExpirationTime * 1000) < Date.now();
return !(isRefreshTokenExpired && isAccessTokenExpired);
});
}, MINUTE);

setInterval(() => {
sockets = sockets.map(socket => {
this.socketsTokenAuthList = this.socketsTokenAuthList.map(socket => {
const isAccessTokenExpired = socket.accessTokenTimestamp + (this.accessTokenExpirationTime * 1000) < Date.now();
if (isAccessTokenExpired) {
// expire token
Expand Down Expand Up @@ -105,7 +106,7 @@ class Socket extends Core {
// we don't have anything
return socket.emit('unauthorized');
} else {
const auth = sockets.find(o => (o.accessToken === cb.accessToken || o.refreshToken === cb.refreshToken));
const auth = global.socket.socketsTokenAuthList.find(o => (o.accessToken === cb.accessToken || o.refreshToken === cb.refreshToken));
if (!auth) {
return socket.emit('unauthorized');
} else {
Expand Down Expand Up @@ -138,7 +139,7 @@ class Socket extends Core {
if (userPermission === permission.CASTERS) {
auth.type = 'admin';
}
sockets.push(auth);
global.socket.socketsTokenAuthList.push(auth);
sendAuthorized(socket, auth);
cb();
});
Expand All @@ -155,7 +156,7 @@ class Socket extends Core {
sockets () {
global.panel.io.of('/core/socket').on('connection', (socket) => {
socket.on('purgeAllConnections', (cb) => {
sockets = [];
this.socketsTokenAuthList = [];
cb(null);
});
});
Expand Down

0 comments on commit 81aa4c5

Please sign in to comment.