Skip to content
Snippets Groups Projects
Commit 5b485db3 authored by Yannis Barlas's avatar Yannis Barlas
Browse files

feat(server): do not throw error when subscriptions do not provide an auth token

BREAKING CHANGE:
allow unauthenticated subscriptions
parent f9223c90
No related branches found
No related tags found
1 merge request!123v4
const { StatusCodes } = require('http-status-codes')
class AuthenticationError extends Error {
constructor(message, status) {
super(message)
Error.captureStackTrace(this, 'AuthenticationError')
this.name = 'AuthenticationError'
this.message = message
this.status = status || StatusCodes.UNAUTHORIZED
}
}
module.exports = AuthenticationError
module.exports.NotFoundError = require('./NotFoundError')
module.exports.AuthorizationError = require('./AuthorizationError')
module.exports.ConflictError = require('./ConflictError')
module.exports.NotFoundError = require('./NotFoundError')
module.exports.ValidationError = require('./ValidationError')
module.exports.AuthorizationError = require('./AuthorizationError')
......@@ -4,13 +4,14 @@ const { useServer } = require('graphql-ws/lib/use/ws')
const { WebSocketServer } = require('ws')
const { expressMiddleware } = require('@apollo/server/express4')
const { ApolloServer } = require('@apollo/server')
const config = require('config')
const jwt = require('jsonwebtoken')
const {
ApolloServerPluginDrainHttpServer,
} = require('@apollo/server/plugin/drainHttpServer')
const { token } = require('../authentication')
const logger = require('../logger')
const AuthenticationError = require('../errors/AuthenticationError')
const schema = require('./schema')
const loaders = require('./loaders')
......@@ -24,18 +25,24 @@ const setup = async (httpServer, app, passport) => {
})
const getDynamicContext = async (ctx, msg, args) => {
if (!ctx.connectionParams.authToken) throw new Error('Missing auth token')
return new Promise((resolve, reject) => {
token.verify(ctx.connectionParams.authToken, (_, id) => {
if (!id) {
logger.info('Bad auth token')
reject(new Error('Bad auth token'))
}
resolve({ user: id })
})
})
const context = { user: null }
if (ctx.connectionParams.authToken) {
try {
const decodedToken = jwt.verify(
ctx.connectionParams.authToken,
config.get('secret'),
)
context.user = decodedToken.id
} catch (e) {
throw new AuthenticationError(
'Subscription authentication token invalid',
)
}
}
return context
}
// store it in a variable so it can be cleaned up on shutdown
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment