2021-05-14 16:43:41 +02:00
|
|
|
const { Client, utils } = require("@budibase/auth/redis")
|
2021-05-13 13:16:09 +02:00
|
|
|
const { getGlobalIDFromUserMetadataID } = require("../db/utils")
|
2021-05-12 18:37:09 +02:00
|
|
|
|
|
|
|
const APP_DEV_LOCK_SECONDS = 600
|
2021-05-21 14:07:10 +02:00
|
|
|
let devAppClient, debounceClient
|
2021-05-12 18:37:09 +02:00
|
|
|
|
|
|
|
// we init this as we want to keep the connection open all the time
|
|
|
|
// reduces the performance hit
|
|
|
|
exports.init = async () => {
|
2021-05-21 14:07:10 +02:00
|
|
|
devAppClient = await new Client(utils.Databases.DEV_LOCKS).init()
|
|
|
|
debounceClient = await new Client(utils.Databases).init()
|
2021-05-12 18:37:09 +02:00
|
|
|
}
|
|
|
|
|
2021-05-13 13:16:09 +02:00
|
|
|
exports.doesUserHaveLock = async (devAppId, user) => {
|
2021-05-12 18:37:09 +02:00
|
|
|
const value = await devAppClient.get(devAppId)
|
2021-05-13 13:16:09 +02:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-05-13 13:16: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
|
2021-05-13 15:17:04 +02:00
|
|
|
const globalId = getGlobalIDFromUserMetadataID(user._id)
|
2021-05-13 13:16:09 +02:00
|
|
|
const inputUser = {
|
|
|
|
...user,
|
2021-05-13 15:17:04 +02:00
|
|
|
userId: globalId,
|
|
|
|
_id: globalId,
|
2021-05-13 13:16:09 +02:00
|
|
|
}
|
|
|
|
await devAppClient.store(devAppId, inputUser, APP_DEV_LOCK_SECONDS)
|
2021-05-12 18:37:09 +02:00
|
|
|
}
|
|
|
|
|
2021-05-13 13:16: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
|
|
|
|
}
|
2021-05-13 13:16:09 +02:00
|
|
|
const userId = getGlobalIDFromUserMetadataID(user._id)
|
2021-05-13 15:24:55 +02:00
|
|
|
if (value._id !== userId) {
|
2021-05-12 18:37:09 +02:00
|
|
|
throw "User does not hold lock, cannot clear it."
|
|
|
|
}
|
2021-05-13 15:34:04 +02:00
|
|
|
await devAppClient.delete(devAppId)
|
2021-05-12 18:37:09 +02:00
|
|
|
}
|
2021-05-21 14:07:10 +02:00
|
|
|
|
|
|
|
exports.checkDebounce = async id => {
|
|
|
|
return debounceClient.get(id)
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.setDebounce = async (id, seconds) => {
|
|
|
|
await debounceClient.store(id, "debouncing", seconds)
|
|
|
|
}
|