From c382b86fb28fc45a486033920ac323bc024d1571 Mon Sep 17 00:00:00 2001
From: mike12345567 <me@michaeldrury.co.uk>
Date: Thu, 22 Sep 2022 14:09:20 +0100
Subject: [PATCH] Self API in worker conversion to typescript.

---
 packages/backend-core/src/index.ts            |  2 +
 packages/backend-core/src/tenancy/tenancy.ts  |  2 +-
 .../controllers/global/{self.js => self.ts}   | 73 +++++++++----------
 .../api/routes/global/{self.js => self.ts}    |  0
 .../worker/src/api/routes/global/templates.js | 12 +--
 5 files changed, 44 insertions(+), 45 deletions(-)
 rename packages/worker/src/api/controllers/global/{self.js => self.ts} (66%)
 rename packages/worker/src/api/routes/global/{self.js => self.ts} (100%)

diff --git a/packages/backend-core/src/index.ts b/packages/backend-core/src/index.ts
index 2c234bd4b8..83b23b479d 100644
--- a/packages/backend-core/src/index.ts
+++ b/packages/backend-core/src/index.ts
@@ -18,6 +18,7 @@ import * as logging from "./logging"
 import pino from "./pino"
 import * as middleware from "./middleware"
 import plugins from "./plugin"
+import encryption from "./security/encryption"
 
 // mimic the outer package exports
 import * as db from "./pkg/db"
@@ -60,6 +61,7 @@ const core = {
   ...pino,
   ...errorClasses,
   middleware,
+  encryption,
 }
 
 export = core
diff --git a/packages/backend-core/src/tenancy/tenancy.ts b/packages/backend-core/src/tenancy/tenancy.ts
index 1c71935eb0..d318648a89 100644
--- a/packages/backend-core/src/tenancy/tenancy.ts
+++ b/packages/backend-core/src/tenancy/tenancy.ts
@@ -121,7 +121,7 @@ export const getTenantUser = async (
   return response
 }
 
-export const isUserInAppTenant = (appId: string, user: any) => {
+export const isUserInAppTenant = (appId: string, user?: any) => {
   let userTenantId
   if (user) {
     userTenantId = user.tenantId || DEFAULT_TENANT_ID
diff --git a/packages/worker/src/api/controllers/global/self.js b/packages/worker/src/api/controllers/global/self.ts
similarity index 66%
rename from packages/worker/src/api/controllers/global/self.js
rename to packages/worker/src/api/controllers/global/self.ts
index 4d71e636c9..8b7930a35d 100644
--- a/packages/worker/src/api/controllers/global/self.js
+++ b/packages/worker/src/api/controllers/global/self.ts
@@ -1,39 +1,36 @@
-const {
-  getGlobalDB,
-  getTenantId,
-  isUserInAppTenant,
-} = require("@budibase/backend-core/tenancy")
-const { generateDevInfoID, SEPARATOR } = require("@budibase/backend-core/db")
-const { user: userCache } = require("@budibase/backend-core/cache")
-const {
-  hash,
-  platformLogout,
-  getCookie,
-  clearCookie,
-} = require("@budibase/backend-core/utils")
-const { encrypt } = require("@budibase/backend-core/encryption")
-const { newid } = require("@budibase/backend-core/utils")
-const { users } = require("../../../sdk")
-const { Cookies } = require("@budibase/backend-core/constants")
-const { events, featureFlags } = require("@budibase/backend-core")
-const env = require("../../../environment")
+import { users } from "../../../sdk"
+import {
+  events,
+  featureFlags,
+  tenancy,
+  constants,
+  db as dbCore,
+  utils,
+  cache,
+  encryption,
+} from "@budibase/backend-core"
+import env from "../../../environment"
+const { hash, platformLogout, getCookie, clearCookie, newid } = utils
+const { user: userCache } = cache
 
 function newTestApiKey() {
   return env.ENCRYPTED_TEST_PUBLIC_API_KEY
 }
 
 function newApiKey() {
-  return encrypt(`${getTenantId()}${SEPARATOR}${newid()}`)
+  return encryption.encrypt(
+    `${tenancy.getTenantId()}${dbCore.SEPARATOR}${newid()}`
+  )
 }
 
-function cleanupDevInfo(info) {
+function cleanupDevInfo(info: any) {
   // user doesn't need to aware of dev doc info
   delete info._id
   delete info._rev
   return info
 }
 
-exports.generateAPIKey = async ctx => {
+exports.generateAPIKey = async (ctx: any) => {
   let userId
   let apiKey
   if (env.isTest() && ctx.request.body.userId) {
@@ -44,8 +41,8 @@ exports.generateAPIKey = async ctx => {
     apiKey = newApiKey()
   }
 
-  const db = getGlobalDB()
-  const id = generateDevInfoID(userId)
+  const db = tenancy.getGlobalDB()
+  const id = dbCore.generateDevInfoID(userId)
   let devInfo
   try {
     devInfo = await db.get(id)
@@ -57,9 +54,9 @@ exports.generateAPIKey = async ctx => {
   ctx.body = cleanupDevInfo(devInfo)
 }
 
-exports.fetchAPIKey = async ctx => {
-  const db = getGlobalDB()
-  const id = generateDevInfoID(ctx.user._id)
+exports.fetchAPIKey = async (ctx: any) => {
+  const db = tenancy.getGlobalDB()
+  const id = dbCore.generateDevInfoID(ctx.user._id)
   let devInfo
   try {
     devInfo = await db.get(id)
@@ -74,20 +71,20 @@ exports.fetchAPIKey = async ctx => {
   ctx.body = cleanupDevInfo(devInfo)
 }
 
-const checkCurrentApp = ctx => {
-  const appCookie = getCookie(ctx, Cookies.CurrentApp)
-  if (appCookie && !isUserInAppTenant(appCookie.appId)) {
+const checkCurrentApp = (ctx: any) => {
+  const appCookie = getCookie(ctx, constants.Cookies.CurrentApp)
+  if (appCookie && !tenancy.isUserInAppTenant(appCookie.appId)) {
     // there is a currentapp cookie from another tenant
     // remove the cookie as this is incompatible with the builder
     // due to builder and admin permissions being removed
-    clearCookie(ctx, Cookies.CurrentApp)
+    clearCookie(ctx, constants.Cookies.CurrentApp)
   }
 }
 
 /**
  * Add the attributes that are session based to the current user.
  */
-const addSessionAttributesToUser = ctx => {
+const addSessionAttributesToUser = (ctx: any) => {
   ctx.body.account = ctx.user.account
   ctx.body.license = ctx.user.license
   ctx.body.budibaseAccess = !!ctx.user.budibaseAccess
@@ -95,9 +92,9 @@ const addSessionAttributesToUser = ctx => {
   ctx.body.csrfToken = ctx.user.csrfToken
 }
 
-const sanitiseUserUpdate = ctx => {
+const sanitiseUserUpdate = (ctx: any) => {
   const allowed = ["firstName", "lastName", "password", "forceResetPassword"]
-  const resp = {}
+  const resp: { [key: string]: any } = {}
   for (let [key, value] of Object.entries(ctx.request.body)) {
     if (allowed.includes(key)) {
       resp[key] = value
@@ -106,7 +103,7 @@ const sanitiseUserUpdate = ctx => {
   return resp
 }
 
-exports.getSelf = async ctx => {
+exports.getSelf = async (ctx: any) => {
   if (!ctx.user) {
     ctx.throw(403, "User not logged in")
   }
@@ -121,14 +118,14 @@ exports.getSelf = async ctx => {
   ctx.body = await users.getUser(userId)
 
   // add the feature flags for this tenant
-  const tenantId = getTenantId()
+  const tenantId = tenancy.getTenantId()
   ctx.body.featureFlags = featureFlags.getTenantFeatureFlags(tenantId)
 
   addSessionAttributesToUser(ctx)
 }
 
-exports.updateSelf = async ctx => {
-  const db = getGlobalDB()
+exports.updateSelf = async (ctx: any) => {
+  const db = tenancy.getGlobalDB()
   const user = await db.get(ctx.user._id)
   let passwordChange = false
 
diff --git a/packages/worker/src/api/routes/global/self.js b/packages/worker/src/api/routes/global/self.ts
similarity index 100%
rename from packages/worker/src/api/routes/global/self.js
rename to packages/worker/src/api/routes/global/self.ts
diff --git a/packages/worker/src/api/routes/global/templates.js b/packages/worker/src/api/routes/global/templates.js
index 321e0543ad..b8cb636d39 100644
--- a/packages/worker/src/api/routes/global/templates.js
+++ b/packages/worker/src/api/routes/global/templates.js
@@ -1,9 +1,9 @@
-const Router = require("@koa/router")
-const controller = require("../../controllers/global/templates")
-const { joiValidator } = require("@budibase/backend-core/auth")
-const Joi = require("joi")
-const { TemplatePurpose, TemplateTypes } = require("../../../constants")
-const { adminOnly } = require("@budibase/backend-core/auth")
+import Router from "@koa/router"
+import controller from "../../controllers/global/templates"
+import { TemplatePurpose, TemplateTypes } from "../../../constants"
+import { auth as authCore } from "@budibase/backend-core"
+import Joi from "joi"
+const { adminOnly, joiValidator } = authCore
 
 const router = Router()