Skip to content

Commit

Permalink
fix(xo-server/rest-api): set apiContext
Browse files Browse the repository at this point in the history
This makes the REST API more closely resemblethe JSON-RPC API and addresses
several issues such as the broken _Rolling Pool Update_ pool action.

Fixes https://xcp-ng.org/forum/post/82867
  • Loading branch information
julien-f committed Sep 27, 2024
1 parent d520e53 commit eb39e14
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

> Users must be able to say: “I had this issue, happy to know it's fixed”
- [REST API] Fix broken _Rolling Pool Update_ pool action [Forum#82867](https://xcp-ng.org/forum/post/82867)

### Packages to release

> When modifying a package, add it here with its release type.
Expand Down
20 changes: 16 additions & 4 deletions packages/xo-server/src/xo-mixins/api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -316,18 +316,30 @@ export default class Api {
throw new MethodNotFound(name)
}

const apiContext = { __proto__: null, connection }

let user
const userId = connection.get('user_id', undefined)
if (userId !== undefined) {
const user = await this._app.getUser(userId)
user = await this._app.getUser(userId)
}

return this.runWithApiContext(user, () => {
this.apiContext.connection = connection

return this.#callApiMethod(name, method, params)
})
}

async runWithApiContext(user, fn) {
const apiContext = { __proto__: null }

if (user !== undefined) {
apiContext.user = user
apiContext.permission = user.permission
} else {
apiContext.permission = 'none'
}

return this.#apiContext.run(apiContext, () => this.#callApiMethod(name, method, params))
return this.#apiContext.run(apiContext, fn)
}

async #callApiMethod(name, method, params) {
Expand Down
5 changes: 2 additions & 3 deletions packages/xo-server/src/xo-mixins/rest-api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -461,8 +461,7 @@ export default class RestApi {
app.authenticateUser({ token: cookies.authenticationToken ?? cookies.token }, { ip }).then(
({ user }) => {
if (user.permission === 'admin') {
req.user = user
return next()
return app.runWithApiContext(user, next)
}

res.sendStatus(401)
Expand Down Expand Up @@ -658,7 +657,7 @@ export default class RestApi {
params.affinityHost = affinity
params.installRepository = install?.repository

const vm = await $xapi.createVm(template, params, undefined, req.user.id)
const vm = await $xapi.createVm(template, params, undefined, app.apiContext.user.id)
$defer.onFailure.call($xapi, 'VM_destroy', vm.$ref)

if (boot) {
Expand Down

0 comments on commit eb39e14

Please sign in to comment.