Persist auth data across restarts

This commit is contained in:
Max Goodhart
2020-08-24 00:50:59 -07:00
parent 5063a95ab7
commit a7b5bb3d1b
3 changed files with 49 additions and 2 deletions

View File

@@ -64,13 +64,24 @@ export class StateWrapper {
}
export class Auth extends EventEmitter {
constructor({ adminUsername, adminPassword }) {
constructor({ adminUsername, adminPassword, persistData }) {
super()
this.adminUsername = adminUsername
this.adminPassword = adminPassword
this.salt = rand62(16)
this.salt = persistData?.salt || rand62(16)
this.tokensById = new Map()
this.tokensByHash = new Map()
for (const token of persistData?.tokens ?? []) {
this.tokensById.set(token.id, token)
this.tokensByHash.set(token.tokenHash, token)
}
}
getPersistData() {
return {
salt: this.salt,
tokens: [...this.tokensById.values()],
}
}
getState() {

View File

@@ -13,6 +13,7 @@ import {
markDataSource,
combineDataSources,
} from './data'
import * as persistence from './persistence'
import { Auth, StateWrapper } from './auth'
import StreamWindow from './StreamWindow'
import TwitchBot from './TwitchBot'
@@ -195,6 +196,8 @@ async function main() {
callback(false)
})
const persistData = await persistence.load()
const idGen = new StreamIDGenerator()
let updateCustomStreams
const customStreamData = new Repeater(async (push) => {
@@ -216,6 +219,7 @@ async function main() {
const auth = new Auth({
adminUsername: argv.control.username,
adminPassword: argv.control.password,
persistData: persistData.auth,
})
let browseWindow = null
@@ -368,6 +372,7 @@ async function main() {
auth.on('state', (authState) => {
updateState({ auth: authState })
persistence.save({ auth: auth.getPersistData() })
})
const dataSources = [

31
src/node/persistence.js Normal file
View File

@@ -0,0 +1,31 @@
import { app } from 'electron'
import { promises as fsPromises, stat } from 'fs'
import path from 'path'
import throttle from 'lodash/throttle'
const stateFilePath = path.join(app.getPath('userData'), 'streamwall.json')
let lastState = {}
async function _save(partialState) {
const state = { ...lastState, ...partialState }
lastState = state
const data = JSON.stringify(state)
await fsPromises.writeFile(stateFilePath, data)
}
export const save = throttle(_save, 501)
export async function load() {
try {
const data = await fsPromises.readFile(stateFilePath)
return JSON.parse(data)
} catch (err) {
if (err.code === 'ENOENT') {
// Ignore missing file.
} else {
console.warn('error reading persisted state:', err)
}
return {}
}
}