2021-02-19 23:32:24 +13:00
|
|
|
const { outputProcessing } = require("../../utilities/rowProcessor")
|
2021-04-10 04:33:21 +12:00
|
|
|
const { InternalTables } = require("../../db/utils")
|
2021-04-13 02:54:14 +12:00
|
|
|
const { getFullUser } = require("../../utilities/users")
|
2022-01-11 08:33:00 +13:00
|
|
|
const { BUILTIN_ROLE_IDS } = require("@budibase/backend-core/roles")
|
2022-01-28 13:05:39 +13:00
|
|
|
const { getAppDB, getAppId } = require("@budibase/backend-core/context")
|
2020-04-08 07:34:21 +12:00
|
|
|
|
2021-05-04 22:32:22 +12:00
|
|
|
exports.fetchSelf = async ctx => {
|
2021-06-04 23:13:29 +12:00
|
|
|
let userId = ctx.user.userId || ctx.user._id
|
2021-03-11 01:20:07 +13:00
|
|
|
/* istanbul ignore next */
|
2022-03-25 02:04:49 +13:00
|
|
|
if (!userId || !ctx.isAuthenticated) {
|
2021-01-29 03:29:35 +13:00
|
|
|
ctx.body = {}
|
2021-02-19 23:32:24 +13:00
|
|
|
return
|
|
|
|
}
|
2021-04-13 22:56:57 +12:00
|
|
|
|
2021-04-20 03:26:33 +12:00
|
|
|
const user = await getFullUser(ctx, userId)
|
2021-11-04 11:23:00 +13:00
|
|
|
// this shouldn't be returned by the app self
|
|
|
|
delete user.roles
|
2022-01-26 11:54:50 +13:00
|
|
|
// forward the csrf token from the session
|
|
|
|
user.csrfToken = ctx.user.csrfToken
|
2021-04-14 04:11:55 +12:00
|
|
|
|
2022-01-28 13:05:39 +13:00
|
|
|
if (getAppId()) {
|
|
|
|
const db = getAppDB()
|
2021-04-14 04:11:55 +12:00
|
|
|
// remove the full roles structure
|
|
|
|
delete user.roles
|
|
|
|
try {
|
|
|
|
const userTable = await db.get(InternalTables.USER_METADATA)
|
|
|
|
const metadata = await db.get(userId)
|
2022-01-26 11:54:50 +13:00
|
|
|
// make sure there is never a stale csrf token
|
|
|
|
delete metadata.csrfToken
|
2021-04-14 04:11:55 +12:00
|
|
|
// specifically needs to make sure is enriched
|
2022-02-01 06:00:22 +13:00
|
|
|
ctx.body = await outputProcessing(userTable, {
|
2021-04-14 04:11:55 +12:00
|
|
|
...user,
|
|
|
|
...metadata,
|
|
|
|
})
|
|
|
|
} catch (err) {
|
2021-10-22 05:23:10 +13:00
|
|
|
let response
|
2021-10-08 03:49:26 +13:00
|
|
|
// user didn't exist in app, don't pretend they do
|
|
|
|
if (user.roleId === BUILTIN_ROLE_IDS.PUBLIC) {
|
2021-10-22 05:23:10 +13:00
|
|
|
response = {}
|
2021-10-08 03:49:26 +13:00
|
|
|
}
|
|
|
|
// user has a role of some sort, return them
|
2021-10-22 05:23:10 +13:00
|
|
|
else if (err.status === 404) {
|
|
|
|
const metadata = {
|
2021-11-04 11:23:00 +13:00
|
|
|
...user,
|
2021-10-22 05:23:10 +13:00
|
|
|
_id: userId,
|
|
|
|
}
|
|
|
|
const dbResp = await db.put(metadata)
|
|
|
|
user._rev = dbResp.rev
|
|
|
|
response = user
|
|
|
|
} else {
|
|
|
|
response = user
|
2021-10-08 03:49:26 +13:00
|
|
|
}
|
2021-10-22 05:23:10 +13:00
|
|
|
ctx.body = response
|
2021-04-14 04:11:55 +12:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
ctx.body = user
|
2021-01-29 03:29:35 +13:00
|
|
|
}
|
|
|
|
}
|