2021-07-06 19:10:04 +02:00
|
|
|
const redis = require("../redis/authRedis")
|
2021-08-05 10:59:08 +02:00
|
|
|
const { getTenantId, lookupTenantId, getGlobalDB } = require("../tenancy")
|
2021-09-20 12:26:19 +02:00
|
|
|
const env = require("../environment")
|
|
|
|
const accounts = require("../cloud/accounts")
|
2021-07-06 19:10:04 +02:00
|
|
|
|
|
|
|
const EXPIRY_SECONDS = 3600
|
|
|
|
|
2021-09-13 18:38:12 +02:00
|
|
|
/**
|
|
|
|
* The default populate user function
|
|
|
|
*/
|
2021-09-15 16:45:43 +02:00
|
|
|
const populateFromDB = async (userId, tenantId) => {
|
|
|
|
const user = await getGlobalDB(tenantId).get(userId)
|
|
|
|
user.budibaseAccess = true
|
2021-09-20 12:26:19 +02:00
|
|
|
|
2021-09-29 17:55:59 +02:00
|
|
|
if (!env.SELF_HOSTED && !env.DISABLE_ACCOUNT_PORTAL) {
|
2021-09-20 12:26:19 +02:00
|
|
|
const account = await accounts.getAccount(user.email)
|
|
|
|
if (account) {
|
|
|
|
user.account = account
|
|
|
|
user.accountPortalAccess = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-15 16:45:43 +02:00
|
|
|
return user
|
2021-09-13 18:38:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the requested user by id.
|
|
|
|
* Use redis cache to first read the user.
|
|
|
|
* If not present fallback to loading the user directly and re-caching.
|
|
|
|
* @param {*} userId the id of the user to get
|
|
|
|
* @param {*} tenantId the tenant of the user to get
|
2021-09-13 18:45:37 +02:00
|
|
|
* @param {*} populateUser function to provide the user for re-caching. default to couch db
|
2021-09-13 18:38:12 +02:00
|
|
|
* @returns
|
|
|
|
*/
|
|
|
|
exports.getUser = async (
|
|
|
|
userId,
|
|
|
|
tenantId = null,
|
|
|
|
populateUser = populateFromDB
|
|
|
|
) => {
|
2021-08-05 10:59:08 +02:00
|
|
|
if (!tenantId) {
|
|
|
|
try {
|
|
|
|
tenantId = getTenantId()
|
|
|
|
} catch (err) {
|
|
|
|
tenantId = await lookupTenantId(userId)
|
|
|
|
}
|
|
|
|
}
|
2021-07-06 19:10:04 +02:00
|
|
|
const client = await redis.getUserClient()
|
|
|
|
// try cache
|
|
|
|
let user = await client.get(userId)
|
|
|
|
if (!user) {
|
2021-09-13 18:38:12 +02:00
|
|
|
user = await populateUser(userId, tenantId)
|
2021-07-06 19:10:04 +02:00
|
|
|
client.store(userId, user, EXPIRY_SECONDS)
|
|
|
|
}
|
2021-09-06 16:14:46 +02:00
|
|
|
if (user && !user.tenantId && tenantId) {
|
|
|
|
// make sure the tenant ID is always correct/set
|
|
|
|
user.tenantId = tenantId
|
|
|
|
}
|
2021-07-06 19:10:04 +02:00
|
|
|
return user
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.invalidateUser = async userId => {
|
|
|
|
const client = await redis.getUserClient()
|
|
|
|
await client.delete(userId)
|
|
|
|
}
|