Swapping admin -> global in worker to reduce confusion in API url naming.

This commit is contained in:
mike12345567 2021-07-22 12:56:47 +01:00
parent 371e38fcb9
commit 27b2a13817
50 changed files with 180 additions and 179 deletions

View File

@ -26,7 +26,7 @@ static_resources:
cluster: couchdb-service cluster: couchdb-service
prefix_rewrite: "/" prefix_rewrite: "/"
- match: { prefix: "/api/admin/" } - match: { prefix: "/api/global/" }
route: route:
cluster: worker-dev cluster: worker-dev

View File

@ -38,7 +38,7 @@ static_resources:
cluster: app-service cluster: app-service
# special case for worker admin API # special case for worker admin API
- match: { prefix: "/api/admin/" } - match: { prefix: "/api/global/" }
route: route:
cluster: worker-service cluster: worker-service

View File

@ -29,7 +29,7 @@ describe("google", () => {
it("should create successfully create a google strategy", async () => { it("should create successfully create a google strategy", async () => {
const google = require("../google") const google = require("../google")
await google.strategyFactory(googleConfig, `/api/admin/auth/${TENANT_ID}/google/callback`) await google.strategyFactory(googleConfig, `/api/global/auth/${TENANT_ID}/google/callback`)
const expectedOptions = { const expectedOptions = {
clientID: googleConfig.clientID, clientID: googleConfig.clientID,

View File

@ -24,7 +24,7 @@
try { try {
adminUser.tenantId = tenantId adminUser.tenantId = tenantId
// Save the admin user // Save the admin user
const response = await api.post(`/api/admin/users/init`, adminUser) const response = await api.post(`/api/global/users/init`, adminUser)
const json = await response.json() const json = await response.json()
if (response.status !== 200) { if (response.status !== 200) {
throw new Error(json.message) throw new Error(json.message)

View File

@ -11,7 +11,7 @@
{#if show} {#if show}
<ActionButton <ActionButton
on:click={() => window.open(`/api/admin/auth/${tenantId}/google`, "_blank")} on:click={() => window.open(`/api/global/auth/${tenantId}/google`, "_blank")}
> >
<div class="inner"> <div class="inner">
<img src={GoogleLogo} alt="google icon" /> <img src={GoogleLogo} alt="google icon" />

View File

@ -31,7 +31,7 @@
{#if show} {#if show}
<ActionButton <ActionButton
on:click={() => on:click={() =>
window.open(`/api/admin/auth/oidc/configs/${$oidc.uuid}`, "_blank")} window.open(`/api/global/auth/oidc/configs/${$oidc.uuid}`, "_blank")}
> >
<div class="inner"> <div class="inner">
<img {src} alt="oidc icon" /> <img {src} alt="oidc icon" />

View File

@ -39,7 +39,7 @@
name: "callbackURL", name: "callbackURL",
label: "Callback URL", label: "Callback URL",
readonly: true, readonly: true,
placeholder: `/api/admin/auth/${tenantId}/google/callback`, placeholder: `/api/global/auth/${tenantId}/google/callback`,
}, },
], ],
} }
@ -53,7 +53,7 @@
name: "callbackURL", name: "callbackURL",
label: "Callback URL", label: "Callback URL",
readonly: true, readonly: true,
placeholder: `/api/admin/auth/${tenantId}/oidc/callback`, placeholder: `/api/global/auth/${tenantId}/oidc/callback`,
}, },
], ],
} }
@ -129,7 +129,7 @@
let data = new FormData() let data = new FormData()
data.append("file", file) data.append("file", file)
const res = await api.post( const res = await api.post(
`/api/admin/configs/upload/logos_oidc/${file.name}`, `/api/global/configs/upload/logos_oidc/${file.name}`,
data, data,
{} {}
) )
@ -163,7 +163,7 @@
`Please fill in all required ${ConfigTypes.OIDC} fields` `Please fill in all required ${ConfigTypes.OIDC} fields`
) )
} else { } else {
calls.push(api.post(`/api/admin/configs`, element)) calls.push(api.post(`/api/global/configs`, element))
// turn the save button grey when clicked // turn the save button grey when clicked
oidcSaveButtonDisabled = true oidcSaveButtonDisabled = true
originalOidcDoc = cloneDeep(providers.oidc) originalOidcDoc = cloneDeep(providers.oidc)
@ -178,7 +178,7 @@
) )
} else { } else {
delete element.config.callbackURL delete element.config.callbackURL
calls.push(api.post(`/api/admin/configs`, element)) calls.push(api.post(`/api/global/configs`, element))
googleSaveButtonDisabled = true googleSaveButtonDisabled = true
originalGoogleDoc = cloneDeep(providers.google) originalGoogleDoc = cloneDeep(providers.google)
} }
@ -211,7 +211,7 @@
await organisation.init() await organisation.init()
// fetch the configs for oauth // fetch the configs for oauth
const googleResponse = await api.get( const googleResponse = await api.get(
`/api/admin/configs/${ConfigTypes.Google}` `/api/global/configs/${ConfigTypes.Google}`
) )
const googleDoc = await googleResponse.json() const googleDoc = await googleResponse.json()
@ -228,7 +228,7 @@
//Get the list of user uploaded logos and push it to the dropdown options. //Get the list of user uploaded logos and push it to the dropdown options.
//This needs to be done before the config call so they're available when the dropdown renders //This needs to be done before the config call so they're available when the dropdown renders
const res = await api.get(`/api/admin/configs/logos_oidc`) const res = await api.get(`/api/global/configs/logos_oidc`)
const configSettings = await res.json() const configSettings = await res.json()
if (configSettings.config) { if (configSettings.config) {
@ -243,7 +243,7 @@
}) })
}) })
} }
const oidcResponse = await api.get(`/api/admin/configs/${ConfigTypes.OIDC}`) const oidcResponse = await api.get(`/api/global/configs/${ConfigTypes.OIDC}`)
const oidcDoc = await oidcResponse.json() const oidcDoc = await oidcResponse.json()
if (!oidcDoc._id) { if (!oidcDoc._id) {
providers.oidc = { providers.oidc = {

View File

@ -53,7 +53,7 @@
delete smtp.config.auth delete smtp.config.auth
} }
// Save your SMTP config // Save your SMTP config
const response = await api.post(`/api/admin/configs`, smtp) const response = await api.post(`/api/global/configs`, smtp)
if (response.status !== 200) { if (response.status !== 200) {
const error = await response.text() const error = await response.text()
@ -75,7 +75,7 @@
async function fetchSmtp() { async function fetchSmtp() {
loading = true loading = true
// fetch the configs for smtp // fetch the configs for smtp
const smtpResponse = await api.get(`/api/admin/configs/${ConfigTypes.SMTP}`) const smtpResponse = await api.get(`/api/global/configs/${ConfigTypes.SMTP}`)
const smtpDoc = await smtpResponse.json() const smtpDoc = await smtpResponse.json()
if (!smtpDoc._id) { if (!smtpDoc._id) {

View File

@ -45,8 +45,8 @@
}) })
let selectedApp let selectedApp
const userFetch = fetchData(`/api/admin/users/${userId}`) const userFetch = fetchData(`/api/global/users/${userId}`)
const apps = fetchData(`/api/admin/roles`) const apps = fetchData(`/api/global/roles`)
async function deleteUser() { async function deleteUser() {
const res = await users.delete(userId) const res = await users.delete(userId)

View File

@ -37,7 +37,7 @@
async function uploadLogo(file) { async function uploadLogo(file) {
let data = new FormData() let data = new FormData()
data.append("file", file) data.append("file", file)
const res = await post("/api/admin/configs/upload/settings/logo", data, {}) const res = await post("/api/global/configs/upload/settings/logo", data, {})
return await res.json() return await res.json()
} }

View File

@ -9,7 +9,7 @@ export function createAdminStore() {
try { try {
const tenantId = get(auth).tenantId const tenantId = get(auth).tenantId
const response = await api.get( const response = await api.get(
`/api/admin/configs/checklist?tenantId=${tenantId}` `/api/global/configs/checklist?tenantId=${tenantId}`
) )
const json = await response.json() const json = await response.json()
@ -38,7 +38,7 @@ export function createAdminStore() {
async function multiTenancyEnabled() { async function multiTenancyEnabled() {
let enabled = false let enabled = false
try { try {
const response = await api.get(`/api/admin/tenants/enabled`) const response = await api.get(`/api/global/tenants/enabled`)
const json = await response.json() const json = await response.json()
enabled = json.enabled enabled = json.enabled
} catch (err) { } catch (err) {

View File

@ -68,7 +68,7 @@ export function createAuthStore() {
setOrganisation(tenantId) setOrganisation(tenantId)
}, },
checkAuth: async () => { checkAuth: async () => {
const response = await api.get("/api/admin/users/self") const response = await api.get("/api/global/users/self")
if (response.status !== 200) { if (response.status !== 200) {
setUser(null) setUser(null)
} else { } else {
@ -79,7 +79,7 @@ export function createAuthStore() {
login: async creds => { login: async creds => {
const tenantId = get(store).tenantId const tenantId = get(store).tenantId
const response = await api.post( const response = await api.post(
`/api/admin/auth/${tenantId}/login`, `/api/global/auth/${tenantId}/login`,
creds creds
) )
const json = await response.json() const json = await response.json()
@ -91,7 +91,7 @@ export function createAuthStore() {
return json return json
}, },
logout: async () => { logout: async () => {
const response = await api.post(`/api/admin/auth/logout`) const response = await api.post(`/api/global/auth/logout`)
if (response.status !== 200) { if (response.status !== 200) {
throw "Unable to create logout" throw "Unable to create logout"
} }
@ -100,7 +100,7 @@ export function createAuthStore() {
}, },
updateSelf: async fields => { updateSelf: async fields => {
const newUser = { ...get(auth).user, ...fields } const newUser = { ...get(auth).user, ...fields }
const response = await api.post("/api/admin/users/self", newUser) const response = await api.post("/api/global/users/self", newUser)
if (response.status === 200) { if (response.status === 200) {
setUser(newUser) setUser(newUser)
} else { } else {
@ -109,7 +109,7 @@ export function createAuthStore() {
}, },
forgotPassword: async email => { forgotPassword: async email => {
const tenantId = get(store).tenantId const tenantId = get(store).tenantId
const response = await api.post(`/api/admin/auth/${tenantId}/reset`, { const response = await api.post(`/api/global/auth/${tenantId}/reset`, {
email, email,
}) })
if (response.status !== 200) { if (response.status !== 200) {
@ -120,7 +120,7 @@ export function createAuthStore() {
resetPassword: async (password, code) => { resetPassword: async (password, code) => {
const tenantId = get(store).tenantId const tenantId = get(store).tenantId
const response = await api.post( const response = await api.post(
`/api/admin/auth/${tenantId}/reset/update`, `/api/global/auth/${tenantId}/reset/update`,
{ {
password, password,
resetCode: code, resetCode: code,
@ -132,7 +132,7 @@ export function createAuthStore() {
await response.json() await response.json()
}, },
createUser: async user => { createUser: async user => {
const response = await api.post(`/api/admin/users`, user) const response = await api.post(`/api/global/users`, user)
if (response.status !== 200) { if (response.status !== 200) {
throw "Unable to create user" throw "Unable to create user"
} }

View File

@ -9,11 +9,11 @@ export function createEmailStore() {
templates: { templates: {
fetch: async () => { fetch: async () => {
// fetch the email template definitions // fetch the email template definitions
const response = await api.get(`/api/admin/template/definitions`) const response = await api.get(`/api/global/template/definitions`)
const definitions = await response.json() const definitions = await response.json()
// fetch the email templates themselves // fetch the email templates themselves
const templatesResponse = await api.get(`/api/admin/template/email`) const templatesResponse = await api.get(`/api/global/template/email`)
const templates = await templatesResponse.json() const templates = await templatesResponse.json()
store.set({ store.set({
@ -23,7 +23,7 @@ export function createEmailStore() {
}, },
save: async template => { save: async template => {
// Save your template config // Save your template config
const response = await api.post(`/api/admin/template`, template) const response = await api.post(`/api/global/template`, template)
const json = await response.json() const json = await response.json()
if (response.status !== 200) throw new Error(json.message) if (response.status !== 200) throw new Error(json.message)
template._rev = json._rev template._rev = json._rev

View File

@ -15,7 +15,7 @@ export function createOidcStore() {
async function init() { async function init() {
const tenantId = get(auth).tenantId const tenantId = get(auth).tenantId
const res = await api.get( const res = await api.get(
`/api/admin/configs/public/oidc?tenantId=${tenantId}` `/api/global/configs/public/oidc?tenantId=${tenantId}`
) )
const json = await res.json() const json = await res.json()

View File

@ -17,7 +17,7 @@ export function createOrganisationStore() {
async function init() { async function init() {
const tenantId = get(auth).tenantId const tenantId = get(auth).tenantId
const res = await api.get(`/api/admin/configs/public?tenantId=${tenantId}`) const res = await api.get(`/api/global/configs/public?tenantId=${tenantId}`)
const json = await res.json() const json = await res.json()
if (json.status === 400) { if (json.status === 400) {
@ -28,7 +28,7 @@ export function createOrganisationStore() {
} }
async function save(config) { async function save(config) {
const res = await api.post("/api/admin/configs", { const res = await api.post("/api/global/configs", {
type: "settings", type: "settings",
config: { ...get(store), ...config }, config: { ...get(store), ...config },
_rev: get(store)._rev, _rev: get(store)._rev,

View File

@ -6,7 +6,7 @@ export function createUsersStore() {
const { subscribe, set } = writable([]) const { subscribe, set } = writable([])
async function init() { async function init() {
const response = await api.get(`/api/admin/users`) const response = await api.get(`/api/global/users`)
const json = await response.json() const json = await response.json()
set(json) set(json)
} }
@ -23,12 +23,12 @@ export function createUsersStore() {
global: true, global: true,
} }
} }
const response = await api.post(`/api/admin/users/invite`, body) const response = await api.post(`/api/global/users/invite`, body)
return await response.json() return await response.json()
} }
async function acceptInvite(inviteCode, password) { async function acceptInvite(inviteCode, password) {
const response = await api.post("/api/admin/users/invite/accept", { const response = await api.post("/api/global/users/invite/accept", {
inviteCode, inviteCode,
password, password,
}) })
@ -47,20 +47,20 @@ export function createUsersStore() {
if (admin) { if (admin) {
body.admin = { global: true } body.admin = { global: true }
} }
const response = await api.post("/api/admin/users", body) const response = await api.post("/api/global/users", body)
await init() await init()
return await response.json() return await response.json()
} }
async function del(id) { async function del(id) {
const response = await api.delete(`/api/admin/users/${id}`) const response = await api.delete(`/api/global/users/${id}`)
update(users => users.filter(user => user._id !== id)) update(users => users.filter(user => user._id !== id))
return await response.json() return await response.json()
} }
async function save(data) { async function save(data) {
try { try {
const res = await post(`/api/admin/users`, data) const res = await post(`/api/global/users`, data)
return await res.json() return await res.json()
} catch (error) { } catch (error) {
console.log(error) console.log(error)

View File

@ -13,7 +13,7 @@ export const logIn = async ({ email, password }) => {
return API.error("Please enter your password") return API.error("Please enter your password")
} }
return await API.post({ return await API.post({
url: "/api/admin/auth", url: "/api/global/auth",
body: { username: email, password }, body: { username: email, password },
}) })
} }
@ -23,7 +23,7 @@ export const logIn = async ({ email, password }) => {
*/ */
export const fetchSelf = async () => { export const fetchSelf = async () => {
const user = await API.get({ url: "/api/self" }) const user = await API.get({ url: "/api/self" })
if (user?._id) { if (user && user._id) {
if (user.roleId === "PUBLIC") { if (user.roleId === "PUBLIC") {
// Don't try to enrich a public user as it will 403 // Don't try to enrich a public user as it will 403
return user return user

View File

@ -16,7 +16,7 @@ module FetchMock {
} }
} }
if (url.includes("/api/admin")) { if (url.includes("/api/global")) {
return json({ return json({
email: "test@test.com", email: "test@test.com",
_id: "us_test@test.com", _id: "us_test@test.com",

View File

@ -9,8 +9,9 @@ const { DocumentTypes } = require("../../db/utils")
async function redirect(ctx, method) { async function redirect(ctx, method) {
const { devPath } = ctx.params const { devPath } = ctx.params
const queryString = ctx.originalUrl.split("?")[1] || ""
const response = await fetch( const response = await fetch(
checkSlashesInUrl(`${env.WORKER_URL}/api/admin/${devPath}`), checkSlashesInUrl(`${env.WORKER_URL}/api/global/${devPath}?${queryString}`),
request( request(
ctx, ctx,
{ {

View File

@ -8,9 +8,9 @@ const router = Router()
if (env.isDev() || env.isTest()) { if (env.isDev() || env.isTest()) {
router router
.get("/api/admin/:devPath(.*)", controller.redirectGet) .get("/api/global/:devPath(.*)", controller.redirectGet)
.post("/api/admin/:devPath(.*)", controller.redirectPost) .post("/api/global/:devPath(.*)", controller.redirectPost)
.delete("/api/admin/:devPath(.*)", controller.redirectDelete) .delete("/api/global/:devPath(.*)", controller.redirectDelete)
} }
router router

View File

@ -30,7 +30,7 @@ exports.request = request
exports.sendSmtpEmail = async (tenantId, to, from, subject, contents) => { exports.sendSmtpEmail = async (tenantId, to, from, subject, contents) => {
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + `/api/admin/email/send`), checkSlashesInUrl(env.WORKER_URL + `/api/global/email/send`),
request(null, { request(null, {
method: "POST", method: "POST",
body: { body: {
@ -74,7 +74,7 @@ exports.getDeployedApps = async ctx => {
} }
exports.getGlobalSelf = async (ctx, appId = null) => { exports.getGlobalSelf = async (ctx, appId = null) => {
const endpoint = `/api/admin/users/self` const endpoint = `/api/global/users/self`
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + endpoint), checkSlashesInUrl(env.WORKER_URL + endpoint),
// we don't want to use API key when getting self // we don't want to use API key when getting self
@ -96,11 +96,11 @@ exports.addAppRoleToUser = async (ctx, appId, roleId, userId = null) => {
body = {} body = {}
if (!userId) { if (!userId) {
user = await exports.getGlobalSelf(ctx) user = await exports.getGlobalSelf(ctx)
endpoint = `/api/admin/users/self` endpoint = `/api/global/users/self`
} else { } else {
user = await getGlobalUser(ctx, appId, userId) user = await getGlobalUser(ctx, appId, userId)
body._id = userId body._id = userId
endpoint = `/api/admin/users` endpoint = `/api/global/users`
} }
body = { body = {
...body, ...body,
@ -125,7 +125,7 @@ exports.addAppRoleToUser = async (ctx, appId, roleId, userId = null) => {
exports.removeAppFromUserRoles = async (ctx, appId) => { exports.removeAppFromUserRoles = async (ctx, appId) => {
const deployedAppId = getDeployedAppID(appId) const deployedAppId = getDeployedAppID(appId)
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + `/api/admin/roles/${deployedAppId}`), checkSlashesInUrl(env.WORKER_URL + `/api/global/roles/${deployedAppId}`),
request(ctx, { request(ctx, {
method: "DELETE", method: "DELETE",
}) })

View File

@ -103,7 +103,7 @@ exports.logout = async ctx => {
exports.googlePreAuth = async (ctx, next) => { exports.googlePreAuth = async (ctx, next) => {
const tenantId = ctx.params.tenantId const tenantId = ctx.params.tenantId
const db = getGlobalDB(tenantId) const db = getGlobalDB(tenantId)
const callbackUrl = `/api/admin/auth/${tenantId}/google/callback` const callbackUrl = `/api/global/auth/${tenantId}/google/callback`
const config = await authPkg.db.getScopedConfig(db, { const config = await authPkg.db.getScopedConfig(db, {
type: Configs.GOOGLE, type: Configs.GOOGLE,
@ -119,7 +119,7 @@ exports.googlePreAuth = async (ctx, next) => {
exports.googleAuth = async (ctx, next) => { exports.googleAuth = async (ctx, next) => {
const tenantId = ctx.params.tenantId const tenantId = ctx.params.tenantId
const db = getGlobalDB(tenantId) const db = getGlobalDB(tenantId)
const callbackUrl = `/api/admin/auth/${tenantId}/google/callback` const callbackUrl = `/api/global/auth/${tenantId}/google/callback`
const config = await authPkg.db.getScopedConfig(db, { const config = await authPkg.db.getScopedConfig(db, {
type: Configs.GOOGLE, type: Configs.GOOGLE,
@ -148,7 +148,7 @@ async function oidcStrategyFactory(ctx, configId) {
const chosenConfig = config.configs.filter(c => c.uuid === configId)[0] const chosenConfig = config.configs.filter(c => c.uuid === configId)[0]
const callbackUrl = `${ctx.protocol}://${ctx.host}/api/admin/auth/${tenantId}/oidc/callback` const callbackUrl = `${ctx.protocol}://${ctx.host}/api/global/auth/${tenantId}/oidc/callback`
return oidc.strategyFactory(chosenConfig, callbackUrl) return oidc.strategyFactory(chosenConfig, callbackUrl)
} }

View File

@ -230,7 +230,7 @@ exports.configChecklist = async function (ctx) {
const oidcConfig = await getScopedFullConfig(db, { const oidcConfig = await getScopedFullConfig(db, {
type: Configs.OIDC, type: Configs.OIDC,
}) })
// They have set up an admin user // They have set up an global user
const users = await db.allDocs( const users = await db.allDocs(
getGlobalUserParams(null, { getGlobalUserParams(null, {
include_docs: true, include_docs: true,

View File

@ -149,7 +149,7 @@ exports.adminUser = async ctx => {
) )
if (response.rows.some(row => row.doc.admin)) { if (response.rows.some(row => row.doc.admin)) {
ctx.throw(403, "You cannot initialise once an admin user has been created.") ctx.throw(403, "You cannot initialise once an global user has been created.")
} }
const user = { const user = {
@ -280,7 +280,7 @@ exports.invite = async ctx => {
exports.inviteAccept = async ctx => { exports.inviteAccept = async ctx => {
const { inviteCode, password, firstName, lastName } = ctx.request.body const { inviteCode, password, firstName, lastName } = ctx.request.body
try { try {
// info is an extension of the user object that was stored by admin // info is an extension of the user object that was stored by global
const { email, info } = await checkInviteCode(inviteCode) const { email, info } = await checkInviteCode(inviteCode)
// only pass through certain props for accepting // only pass through certain props for accepting
ctx.request.body = { ctx.request.body = {

View File

@ -7,33 +7,33 @@ const { buildAuthMiddleware, auditLog } = require("@budibase/auth").auth
const PUBLIC_ENDPOINTS = [ const PUBLIC_ENDPOINTS = [
{ {
// this covers all of the POST auth routes // this covers all of the POST auth routes
route: "/api/admin/auth/:tenantId", route: "/api/global/auth/:tenantId",
method: "POST", method: "POST",
}, },
{ {
// this covers all of the GET auth routes // this covers all of the GET auth routes
route: "/api/admin/auth/:tenantId", route: "/api/global/auth/:tenantId",
method: "GET", method: "GET",
}, },
{ {
// this covers all of the public config routes // this covers all of the public config routes
route: "/api/admin/configs/public", route: "/api/global/configs/public",
method: "GET", method: "GET",
}, },
{ {
route: "api/admin/tenants/enabled", route: "api/global/tenants/enabled",
method: "GET", method: "GET",
}, },
{ {
route: "/api/admin/configs/checklist", route: "/api/global/configs/checklist",
method: "GET", method: "GET",
}, },
{ {
route: "/api/admin/users/init", route: "/api/global/users/init",
method: "POST", method: "POST",
}, },
{ {
route: "/api/admin/users/invite/accept", route: "/api/global/users/invite/accept",
method: "POST", method: "POST",
}, },
] ]

View File

@ -1,11 +0,0 @@
const Router = require("@koa/router")
const controller = require("../../controllers/admin/roles")
const adminOnly = require("../../../middleware/adminOnly")
const router = Router()
router
.get("/api/admin/roles", adminOnly, controller.fetch)
.get("/api/admin/roles/:appId", adminOnly, controller.find)
module.exports = router

View File

@ -1,14 +0,0 @@
const Router = require("@koa/router")
const controller = require("../../controllers/admin/sessions")
const adminOnly = require("../../../middleware/adminOnly")
const router = Router()
router
.get("/api/admin/sessions", adminOnly, controller.fetch)
.get("/api/admin/sessions/self", controller.selfSessions)
.get("/api/admin/sessions/:userId", adminOnly, controller.find)
.delete("/api/admin/sessions/:userId", adminOnly, controller.invalidateUser)
.delete("/api/admin/sessions/self/:sessionId", controller.invalidateSession)
module.exports = router

View File

@ -1,12 +0,0 @@
const Router = require("@koa/router")
const controller = require("../../controllers/admin/tenants")
const adminOnly = require("../../../middleware/adminOnly")
const router = Router()
router
.get("/api/admin/tenants/enabled", controller.multiTenancyEnabled)
.get("/api/admin/tenants/:tenantId/exists", controller.exists)
.get("/api/admin/tenants", adminOnly, controller.fetch)
module.exports = router

View File

@ -1,5 +1,5 @@
const Router = require("@koa/router") const Router = require("@koa/router")
const authController = require("../../controllers/admin/auth") const authController = require("../../controllers/global/auth")
const joiValidator = require("../../../middleware/joi-validator") const joiValidator = require("../../../middleware/joi-validator")
const Joi = require("joi") const Joi = require("joi")
@ -30,27 +30,27 @@ function buildResetUpdateValidation() {
router router
.post( .post(
"/api/admin/auth/:tenantId/login", "/api/global/auth/:tenantId/login",
buildAuthValidation(), buildAuthValidation(),
authController.authenticate authController.authenticate
) )
.post( .post(
"/api/admin/auth/:tenantId/reset", "/api/global/auth/:tenantId/reset",
buildResetValidation(), buildResetValidation(),
authController.reset authController.reset
) )
.post( .post(
"/api/admin/auth/:tenantId/reset/update", "/api/global/auth/:tenantId/reset/update",
buildResetUpdateValidation(), buildResetUpdateValidation(),
authController.resetUpdate authController.resetUpdate
) )
.post("/api/admin/auth/logout", authController.logout) .post("/api/global/auth/logout", authController.logout)
.get("/api/admin/auth/:tenantId/google", authController.googlePreAuth) .get("/api/global/auth/:tenantId/google", authController.googlePreAuth)
.get("/api/admin/auth/:tenantId/google/callback", authController.googleAuth) .get("/api/global/auth/:tenantId/google/callback", authController.googleAuth)
.get( .get(
"/api/admin/auth/:tenantId/oidc/configs/:configId", "/api/global/auth/:tenantId/oidc/configs/:configId",
authController.oidcPreAuth authController.oidcPreAuth
) )
.get("/api/admin/auth/:tenantId/oidc/callback", authController.oidcAuth) .get("/api/global/auth/:tenantId/oidc/callback", authController.oidcAuth)
module.exports = router module.exports = router

View File

@ -1,5 +1,5 @@
const Router = require("@koa/router") const Router = require("@koa/router")
const controller = require("../../controllers/admin/configs") const controller = require("../../controllers/global/configs")
const joiValidator = require("../../../middleware/joi-validator") const joiValidator = require("../../../middleware/joi-validator")
const adminOnly = require("../../../middleware/adminOnly") const adminOnly = require("../../../middleware/adminOnly")
const Joi = require("joi") const Joi = require("joi")
@ -96,24 +96,24 @@ function buildConfigGetValidation() {
router router
.post( .post(
"/api/admin/configs", "/api/global/configs",
adminOnly, adminOnly,
buildConfigSaveValidation(), buildConfigSaveValidation(),
controller.save controller.save
) )
.delete("/api/admin/configs/:id/:rev", adminOnly, controller.destroy) .delete("/api/global/configs/:id/:rev", adminOnly, controller.destroy)
.get("/api/admin/configs", controller.fetch) .get("/api/global/configs", controller.fetch)
.get("/api/admin/configs/checklist", controller.configChecklist) .get("/api/global/configs/checklist", controller.configChecklist)
.get( .get(
"/api/admin/configs/all/:type", "/api/global/configs/all/:type",
buildConfigGetValidation(), buildConfigGetValidation(),
controller.fetch controller.fetch
) )
.get("/api/admin/configs/public", controller.publicSettings) .get("/api/global/configs/public", controller.publicSettings)
.get("/api/admin/configs/public/oidc", controller.publicOidc) .get("/api/global/configs/public/oidc", controller.publicOidc)
.get("/api/admin/configs/:type", buildConfigGetValidation(), controller.find) .get("/api/global/configs/:type", buildConfigGetValidation(), controller.find)
.post( .post(
"/api/admin/configs/upload/:type/:name", "/api/global/configs/upload/:type/:name",
adminOnly, adminOnly,
buildUploadValidation(), buildUploadValidation(),
controller.upload controller.upload

View File

@ -1,5 +1,5 @@
const Router = require("@koa/router") const Router = require("@koa/router")
const controller = require("../../controllers/admin/email") const controller = require("../../controllers/global/email")
const { EmailTemplatePurpose } = require("../../../constants") const { EmailTemplatePurpose } = require("../../../constants")
const joiValidator = require("../../../middleware/joi-validator") const joiValidator = require("../../../middleware/joi-validator")
const adminOnly = require("../../../middleware/adminOnly") const adminOnly = require("../../../middleware/adminOnly")
@ -20,7 +20,7 @@ function buildEmailSendValidation() {
} }
router.post( router.post(
"/api/admin/email/send", "/api/global/email/send",
buildEmailSendValidation(), buildEmailSendValidation(),
adminOnly, adminOnly,
controller.sendEmail controller.sendEmail

View File

@ -0,0 +1,11 @@
const Router = require("@koa/router")
const controller = require("../../controllers/global/roles")
const adminOnly = require("../../../middleware/adminOnly")
const router = Router()
router
.get("/api/global/roles", adminOnly, controller.fetch)
.get("/api/global/roles/:appId", adminOnly, controller.find)
module.exports = router

View File

@ -0,0 +1,14 @@
const Router = require("@koa/router")
const controller = require("../../controllers/global/sessions")
const adminOnly = require("../../../middleware/adminOnly")
const router = Router()
router
.get("/api/global/sessions", adminOnly, controller.fetch)
.get("/api/global/sessions/self", controller.selfSessions)
.get("/api/global/sessions/:userId", adminOnly, controller.find)
.delete("/api/global/sessions/:userId", adminOnly, controller.invalidateUser)
.delete("/api/global/sessions/self/:sessionId", controller.invalidateSession)
module.exports = router

View File

@ -1,5 +1,5 @@
const Router = require("@koa/router") const Router = require("@koa/router")
const controller = require("../../controllers/admin/templates") const controller = require("../../controllers/global/templates")
const joiValidator = require("../../../middleware/joi-validator") const joiValidator = require("../../../middleware/joi-validator")
const Joi = require("joi") const Joi = require("joi")
const { TemplatePurpose, TemplateTypes } = require("../../../constants") const { TemplatePurpose, TemplateTypes } = require("../../../constants")
@ -21,17 +21,17 @@ function buildTemplateSaveValidation() {
} }
router router
.get("/api/admin/template/definitions", controller.definitions) .get("/api/global/template/definitions", controller.definitions)
.post( .post(
"/api/admin/template", "/api/global/template",
adminOnly, adminOnly,
buildTemplateSaveValidation(), buildTemplateSaveValidation(),
controller.save controller.save
) )
.get("/api/admin/template", controller.fetch) .get("/api/global/template", controller.fetch)
.get("/api/admin/template/:type", controller.fetchByType) .get("/api/global/template/:type", controller.fetchByType)
.get("/api/admin/template/:ownerId", controller.fetchByOwner) .get("/api/global/template/:ownerId", controller.fetchByOwner)
.get("/api/admin/template/:id", controller.find) .get("/api/global/template/:id", controller.find)
.delete("/api/admin/template/:id/:rev", adminOnly, controller.destroy) .delete("/api/global/template/:id/:rev", adminOnly, controller.destroy)
module.exports = router module.exports = router

View File

@ -0,0 +1,12 @@
const Router = require("@koa/router")
const controller = require("../../controllers/global/tenants")
const adminOnly = require("../../../middleware/adminOnly")
const router = Router()
router
.get("/api/global/tenants/enabled", controller.multiTenancyEnabled)
.get("/api/global/tenants/:tenantId/exists", controller.exists)
.get("/api/global/tenants", adminOnly, controller.fetch)
module.exports = router

View File

@ -1,5 +1,5 @@
const Router = require("@koa/router") const Router = require("@koa/router")
const controller = require("../../controllers/admin/users") const controller = require("../../controllers/global/users")
const joiValidator = require("../../../middleware/joi-validator") const joiValidator = require("../../../middleware/joi-validator")
const adminOnly = require("../../../middleware/adminOnly") const adminOnly = require("../../../middleware/adminOnly")
const Joi = require("joi") const Joi = require("joi")
@ -62,39 +62,39 @@ function buildInviteAcceptValidation() {
router router
.post( .post(
"/api/admin/users", "/api/global/users",
adminOnly, adminOnly,
buildUserSaveValidation(), buildUserSaveValidation(),
controller.save controller.save
) )
.get("/api/admin/users", adminOnly, controller.fetch) .get("/api/global/users", adminOnly, controller.fetch)
.delete("/api/admin/roles/:appId", adminOnly, controller.removeAppRole) .delete("/api/global/roles/:appId", adminOnly, controller.removeAppRole)
.delete("/api/admin/users/:id", adminOnly, controller.destroy) .delete("/api/global/users/:id", adminOnly, controller.destroy)
.get("/api/admin/roles/:appId") .get("/api/global/roles/:appId")
.post( .post(
"/api/admin/users/invite", "/api/global/users/invite",
adminOnly, adminOnly,
buildInviteValidation(), buildInviteValidation(),
controller.invite controller.invite
) )
// non-admin endpoints // non-global endpoints
.post( .post(
"/api/admin/users/self", "/api/global/users/self",
buildUserSaveValidation(true), buildUserSaveValidation(true),
controller.updateSelf controller.updateSelf
) )
.post( .post(
"/api/admin/users/invite/accept", "/api/global/users/invite/accept",
buildInviteAcceptValidation(), buildInviteAcceptValidation(),
controller.inviteAccept controller.inviteAccept
) )
.post( .post(
"/api/admin/users/init", "/api/global/users/init",
buildAdminInitValidation(), buildAdminInitValidation(),
controller.adminUser controller.adminUser
) )
.get("/api/admin/users/self", controller.getSelf) .get("/api/global/users/self", controller.getSelf)
// admin endpoint but needs to come at end (blocks other endpoints otherwise) // global endpoint but needs to come at end (blocks other endpoints otherwise)
.get("/api/admin/users/:id", adminOnly, controller.find) .get("/api/global/users/:id", adminOnly, controller.find)
module.exports = router module.exports = router

View File

@ -1,5 +1,5 @@
const Router = require("@koa/router") const Router = require("@koa/router")
const controller = require("../../controllers/admin/workspaces") const controller = require("../../controllers/global/workspaces")
const joiValidator = require("../../../middleware/joi-validator") const joiValidator = require("../../../middleware/joi-validator")
const adminOnly = require("../../../middleware/adminOnly") const adminOnly = require("../../../middleware/adminOnly")
const Joi = require("joi") const Joi = require("joi")
@ -26,13 +26,13 @@ function buildWorkspaceSaveValidation() {
router router
.post( .post(
"/api/admin/workspaces", "/api/global/workspaces",
adminOnly, adminOnly,
buildWorkspaceSaveValidation(), buildWorkspaceSaveValidation(),
controller.save controller.save
) )
.delete("/api/admin/workspaces/:id", adminOnly, controller.destroy) .delete("/api/global/workspaces/:id", adminOnly, controller.destroy)
.get("/api/admin/workspaces", controller.fetch) .get("/api/global/workspaces", controller.fetch)
.get("/api/admin/workspaces/:id", controller.find) .get("/api/global/workspaces/:id", controller.find)
module.exports = router module.exports = router

View File

@ -1,12 +1,12 @@
const userRoutes = require("./admin/users") const userRoutes = require("./global/users")
const configRoutes = require("./admin/configs") const configRoutes = require("./global/configs")
const workspaceRoutes = require("./admin/workspaces") const workspaceRoutes = require("./global/workspaces")
const templateRoutes = require("./admin/templates") const templateRoutes = require("./global/templates")
const tenantsRoutes = require("./admin/tenants") const tenantsRoutes = require("./global/tenants")
const emailRoutes = require("./admin/email") const emailRoutes = require("./global/email")
const authRoutes = require("./admin/auth") const authRoutes = require("./global/auth")
const roleRoutes = require("./admin/roles") const roleRoutes = require("./global/roles")
const sessionRoutes = require("./admin/sessions") const sessionRoutes = require("./global/sessions")
const appRoutes = require("./app") const appRoutes = require("./app")
exports.routes = [ exports.routes = [

View File

@ -5,7 +5,7 @@ const TENANT_ID = "default"
jest.mock("nodemailer") jest.mock("nodemailer")
const sendMailMock = setup.emailMock() const sendMailMock = setup.emailMock()
describe("/api/admin/auth", () => { describe("/api/global/auth", () => {
let request = setup.getRequest() let request = setup.getRequest()
let config = setup.getConfig() let config = setup.getConfig()
let code let code
@ -26,7 +26,7 @@ describe("/api/admin/auth", () => {
await config.saveSettingsConfig() await config.saveSettingsConfig()
await config.createUser("test@test.com") await config.createUser("test@test.com")
const res = await request const res = await request
.post(`/api/admin/auth/${TENANT_ID}/reset`) .post(`/api/global/auth/${TENANT_ID}/reset`)
.send({ .send({
email: "test@test.com", email: "test@test.com",
}) })
@ -43,7 +43,7 @@ describe("/api/admin/auth", () => {
it("should allow resetting user password with code", async () => { it("should allow resetting user password with code", async () => {
const res = await request const res = await request
.post(`/api/admin/auth/${TENANT_ID}/reset/update`) .post(`/api/global/auth/${TENANT_ID}/reset/update`)
.send({ .send({
password: "newpassword", password: "newpassword",
resetCode: code, resetCode: code,
@ -76,13 +76,13 @@ describe("/api/admin/auth", () => {
afterEach(() => { afterEach(() => {
expect(strategyFactory).toBeCalledWith( expect(strategyFactory).toBeCalledWith(
chosenConfig, chosenConfig,
`http://127.0.0.1:4003/api/admin/auth/${TENANT_ID}/oidc/callback` // calculated url `http://127.0.0.1:4003/api/global/auth/${TENANT_ID}/oidc/callback` // calculated url
) )
}) })
describe("oidc configs", () => { describe("oidc configs", () => {
it("should load strategy and delegate to passport", async () => { it("should load strategy and delegate to passport", async () => {
await request.get(`/api/admin/auth/${TENANT_ID}/oidc/configs/${configId}`) await request.get(`/api/global/auth/${TENANT_ID}/oidc/configs/${configId}`)
expect(passportSpy).toBeCalledWith(mockStrategyReturn, { expect(passportSpy).toBeCalledWith(mockStrategyReturn, {
scope: ["profile", "email"], scope: ["profile", "email"],
@ -93,7 +93,7 @@ describe("/api/admin/auth", () => {
describe("oidc callback", () => { describe("oidc callback", () => {
it("should load strategy and delegate to passport", async () => { it("should load strategy and delegate to passport", async () => {
await request.get(`/api/admin/auth/${TENANT_ID}/oidc/callback`) await request.get(`/api/global/auth/${TENANT_ID}/oidc/callback`)
.set(config.getOIDConfigCookie(configId)) .set(config.getOIDConfigCookie(configId))
expect(passportSpy).toBeCalledWith(mockStrategyReturn, { expect(passportSpy).toBeCalledWith(mockStrategyReturn, {

View File

@ -8,7 +8,7 @@ nodemailer.createTransport.mockReturnValue({
verify: jest.fn() verify: jest.fn()
}) })
describe("/api/admin/configs/checklist", () => { describe("/api/global/configs/checklist", () => {
let request = setup.getRequest() let request = setup.getRequest()
let config = setup.getConfig() let config = setup.getConfig()
@ -24,7 +24,7 @@ describe("/api/admin/configs/checklist", () => {
await config.saveSmtpConfig() await config.saveSmtpConfig()
const res = await request const res = await request
.get(`/api/admin/configs/checklist`) .get(`/api/global/configs/checklist`)
.set(config.defaultHeaders()) .set(config.defaultHeaders())
.expect("Content-Type", /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)

View File

@ -10,7 +10,7 @@ nodemailer.createTransport.mockReturnValue({
verify: jest.fn() verify: jest.fn()
}) })
describe("/api/admin/email", () => { describe("/api/global/email", () => {
let request = setup.getRequest() let request = setup.getRequest()
let config = setup.getConfig() let config = setup.getConfig()
@ -25,7 +25,7 @@ describe("/api/admin/email", () => {
await config.saveSmtpConfig() await config.saveSmtpConfig()
await config.saveSettingsConfig() await config.saveSettingsConfig()
const res = await request const res = await request
.post(`/api/admin/email/send`) .post(`/api/global/email/send`)
.send({ .send({
email: "test@test.com", email: "test@test.com",
purpose: EmailTemplatePurpose.INVITATION, purpose: EmailTemplatePurpose.INVITATION,

View File

@ -6,7 +6,7 @@ const fetch = require("node-fetch")
// need a longer timeout for getting these // need a longer timeout for getting these
jest.setTimeout(30000) jest.setTimeout(30000)
describe("/api/admin/email", () => { describe("/api/global/email", () => {
let request = setup.getRequest() let request = setup.getRequest()
let config = setup.getConfig() let config = setup.getConfig()
@ -21,7 +21,7 @@ describe("/api/admin/email", () => {
await config.saveSettingsConfig() await config.saveSettingsConfig()
const user = await config.getUser("test@test.com") const user = await config.getUser("test@test.com")
const res = await request const res = await request
.post(`/api/admin/email/send`) .post(`/api/global/email/send`)
.send({ .send({
email: "test@test.com", email: "test@test.com",
purpose, purpose,

View File

@ -3,7 +3,7 @@ const setup = require("./utilities")
jest.mock("nodemailer") jest.mock("nodemailer")
const sendMailMock = setup.emailMock() const sendMailMock = setup.emailMock()
describe("/api/admin/users", () => { describe("/api/global/users", () => {
let request = setup.getRequest() let request = setup.getRequest()
let config = setup.getConfig() let config = setup.getConfig()
let code let code
@ -19,7 +19,7 @@ describe("/api/admin/users", () => {
await config.saveSmtpConfig() await config.saveSmtpConfig()
await config.saveSettingsConfig() await config.saveSettingsConfig()
const res = await request const res = await request
.post(`/api/admin/users/invite`) .post(`/api/global/users/invite`)
.send({ .send({
email: "invite@test.com", email: "invite@test.com",
}) })
@ -37,7 +37,7 @@ describe("/api/admin/users", () => {
it("should be able to create new user from invite", async () => { it("should be able to create new user from invite", async () => {
const res = await request const res = await request
.post(`/api/admin/users/invite/accept`) .post(`/api/global/users/invite/accept`)
.send({ .send({
password: "newpassword", password: "newpassword",
inviteCode: code, inviteCode: code,

View File

@ -1,7 +1,7 @@
module.exports = { module.exports = {
email: require("../../../controllers/admin/email"), email: require("../../../controllers/global/email"),
workspaces: require("../../../controllers/admin/workspaces"), workspaces: require("../../../controllers/global/workspaces"),
config: require("../../../controllers/admin/configs"), config: require("../../../controllers/global/configs"),
templates: require("../../../controllers/admin/templates"), templates: require("../../../controllers/global/templates"),
users: require("../../../controllers/admin/users"), users: require("../../../controllers/global/users"),
} }