budibase/packages/server/src/utilities/redis.js

55 lines
1.5 KiB
JavaScript
Raw Normal View History

2021-05-12 18:37:09 +02:00
const { Client, utils } = require("@budibase/auth").redis
const { getGlobalIDFromUserMetadataID } = require("../db/utils")
2021-05-12 18:37:09 +02:00
const APP_DEV_LOCK_SECONDS = 600
const DB_NAME = utils.Databases.DEV_LOCKS
let devAppClient
// we init this as we want to keep the connection open all the time
// reduces the performance hit
exports.init = async () => {
2021-05-12 18:43:29 +02:00
devAppClient = await new Client(DB_NAME).init()
2021-05-12 18:37:09 +02:00
}
exports.doesUserHaveLock = async (devAppId, user) => {
2021-05-12 18:37:09 +02:00
const value = await devAppClient.get(devAppId)
if (!value) {
return true
}
// make sure both IDs are global
const expected = getGlobalIDFromUserMetadataID(value._id)
const userId = getGlobalIDFromUserMetadataID(user._id)
return expected === userId
2021-05-12 18:37:09 +02:00
}
exports.getAllLocks = async () => {
const locks = await devAppClient.scan()
return locks.map(lock => ({
appId: lock.key,
user: lock.value,
}))
}
exports.updateLock = async (devAppId, user) => {
// make sure always global user ID
const globalId = getGlobalIDFromUserMetadataID(user._id)
const inputUser = {
...user,
userId: globalId,
_id: globalId,
}
await devAppClient.store(devAppId, inputUser, APP_DEV_LOCK_SECONDS)
2021-05-12 18:37:09 +02:00
}
exports.clearLock = async (devAppId, user) => {
2021-05-12 18:37:09 +02:00
const value = await devAppClient.get(devAppId)
if (!value) {
return
}
const userId = getGlobalIDFromUserMetadataID(user._id)
2021-05-12 18:37:09 +02:00
if (value !== userId) {
throw "User does not hold lock, cannot clear it."
}
await devAppClient.delete(devAppClient)
}