Skip to content

Commit

Permalink
authorize API requests
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Jan 29, 2025
1 parent 71b95bf commit 77eaac3
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 10 deletions.
39 changes: 38 additions & 1 deletion express.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,44 @@ module.exports = async function(apiUrl, conn, options) {
apiUrl = apiUrl || '/admin/api';
const backend = Backend(conn);

router.use('/api', express.json(), objectRouter(backend, toRoute));
router.use(
'/api',
function authorize(req, res, next) {
if (!workspace) {
next();
return;
}
const authorization = req.headers.authorization;
const params = {
method: 'POST',
body: JSON.stringify({ workspaceId: workspace._id }),
headers: {
'Authorization': authorization,
'Content-Type': 'application/json'
}
};
fetch(`${mothershipUrl}/me`, params)
.then(response => {
if (response.status < 200 || response.status >= 400) {
return response.json().then(data => {
throw new Error(`Mongoose Studio API Key Error ${response.status}: ${require('util').inspect(data)}`);
});
}
return response;
})
.then(res => res.json())
.then(({ user, roles }) => {
if (!user || !roles) {
throw new Error('Not authorized');
}

next();
})
.catch(err => next(err));
},
express.json(),
objectRouter(backend, toRoute)
);

console.log('Workspace', workspace);
frontend(apiUrl, false, options, workspace);
Expand Down
16 changes: 7 additions & 9 deletions frontend/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,14 @@ const client = axios.create({
});

window.apiClient = client;
if (typeof config__setAuthorizationHeaderFrom === 'string' && config__setAuthorizationHeaderFrom) {
client.interceptors.request.use(req => {
const accessToken = window.localStorage.getItem(config__setAuthorizationHeaderFrom) || null;
if (accessToken) {
req.headers.authorization = accessToken;
}
client.interceptors.request.use(req => {
const accessToken = window.localStorage.getItem('_mongooseStudioAccessToken') || null;
if (accessToken) {
req.headers.authorization = accessToken;
}

return req;
});
}
return req;
});

client.interceptors.response.use(
res => res,
Expand Down

0 comments on commit 77eaac3

Please sign in to comment.