Files
baserow/web-frontend/modules/core/plugins/userSourceClientHandler.js
Peter Evans 864c6d6f51 feat: let visitors report abuse on published applications (#6715)
* feat: let visitors report abuse on published applications

* fix: let logged-in app users report published applications
2026-11-18 09:00:31 +00:00

79 lines
2.5 KiB
JavaScript

import { makeRefreshAuthInterceptor } from '@baserow/modules/core/plugins/clientAuthRefresh'
/**
* Adds the current user source token without overriding the authentication
* required by the request context. Requests to endpoints that don't accept user
* source tokens, like the instance settings, opt out with
* `skipUserSourceAuthorization`.
*/
export const prepareUserSourceRequestHeaders = (store) => (config) => {
if (config.skipUserSourceAuthorization) {
return config
}
const application = store.getters['userSourceUser/getCurrentApplication']
const isAuthenticated =
store.getters['userSourceUser/isAuthenticated'](application)
if (
!isAuthenticated ||
store.getters['userSourceUser/isRefreshing'](application)
) {
return config
}
config.headers ||= {}
const token = store.getters['userSourceUser/accessToken'](application)
const isBaserowUserAuthenticated = store.getters['auth/isAuthenticated']
if (isBaserowUserAuthenticated && !config.userSourceAuthAsPrimary) {
config.headers.UserSourceAuthorization = `JWT ${token}`
} else {
config.headers.Authorization = `JWT ${token}`
config.usesUserSourceAuthorization = true
}
return config
}
export default defineNuxtPlugin({
name: 'user-source-client-handler',
dependsOn: ['client-handler'],
setup(nuxtApp) {
const client = nuxtApp.$client
const store = nuxtApp.$store
client.interceptors.request.use(prepareUserSourceRequestHeaders(store))
const shouldInterceptRequest = () => {
const application = store.getters['userSourceUser/getCurrentApplication']
return (
!store.getters['auth/isAuthenticated'] &&
store.getters['userSourceUser/shouldRefreshToken'](application)
)
}
const shouldInterceptResponse = (error) => {
const application = store.getters['userSourceUser/getCurrentApplication']
return (
!store.getters['auth/isAuthenticated'] &&
store.getters['userSourceUser/isAuthenticated'](application) &&
error.response?.data?.error === 'ERROR_INVALID_ACCESS_TOKEN'
)
}
const refreshToken = async () =>
await store.dispatch('userSourceUser/refreshAuth', {
application: store.getters['userSourceUser/getCurrentApplication'],
})
const refreshAuthInterceptor = makeRefreshAuthInterceptor(
client,
refreshToken,
shouldInterceptRequest,
shouldInterceptResponse
)
client.interceptors.response.use(null, refreshAuthInterceptor)
},
})