Open
Description
We need to support requests without Parse session token but a JWT from Auth0. We have a hack but wonder if there is a better way to do this. We don't like the part that we have to call db twice to find the user and then the session. We would have called the db even more times if the user or session does not exist. We had to give the session an insane long expiration time, but I hope that is not a problem. Lastly, we are not sure if setting the x-parse-session-token header is the right way to become that user on the server-side.
Here we share our hack
const express = require('express');
const app = express();
const ParseServer = require('parse-server').ParseServer;
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const jwtMiddleware = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: 'http://your-app.auth0.com/.well-known/jwks.json'
}),
// Validate the audience and the issuer.
audience: 'https://api.your-domain.com/v1',
issuer: 'https://your-app.auth0.com/',
algorithms: ['RS256'],
credentialsRequired: false,
})
app.use('/parse', jwtMiddleware)
const addParseSessionHeader = async (req) => {
if (!req.user) {
return
}
const username = req.user.sub
const userQuery = new Parse.Query('_User')
userQuery.equalTo('username', username)
let users
try {
users = await userQuery.find()
}
catch(e) {
console.log('Exception when search for user: ', e)
return
}
if (!users || users.length === 0) {
// TODO: need to creat user
return
}
const user = users[0]
const sessionQuery = new Parse.Query('_Session')
sessionQuery.equalTo('user', user)
let sessions
try {
sessions = await sessionQuery.find({ useMasterKey: true })
}
catch(e) {
console.log('Exception when search session for user: ', e)
return
}
if (!sessions || sessions.length === 0) {
// TODO: need to login to create session
return
}
const session = sessions[0]
const sessionToken = session.get('sessionToken')
req.headers['x-parse-session-token'] = sessionToken
}
app.use('/parse', async (req, res, next) => {
await addParseSessionHeader(req, res)
next()
})
const parseApi = new ParseServer({
...your configs
});
app.use('/parse', parseApi);
app.listen(port, () => console.log(`Listening on port ${port}`));