uzen
Version:
General-purpose GraphQL subscription server library
53 lines (52 loc) • 1.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
function extractToken(request) {
let aT;
let clientType = 'web';
const cookies = request.headers.get('cookie')?.split('; ') || [];
const cookieMap = Object.fromEntries(cookies.map((c) => c.split('=')));
if (cookieMap.access_token) {
aT = cookieMap.access_token;
}
else if (request.headers.get('authorization')) {
const authHeader = request.headers.get('authorization');
aT = authHeader?.match(/Bearer\s+(\S+)/)?.[1];
}
return { aT, clientType };
}
function sendErrorResponse(fetchAPI, endResponse, message) {
endResponse(new fetchAPI.Response(JSON.stringify({ error: message }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
}));
}
function isValidAuth(auth, clientType) {
return Boolean(!!auth && auth.id && auth.tenant && auth.type === clientType);
}
const useAuth = ({ aTs }) => {
return {
async onRequest({ request, fetchAPI, endResponse }) {
const { aT, clientType } = extractToken(request);
console.log('aT: ', aT);
if (!aT) {
sendErrorResponse(fetchAPI, endResponse, 'Unauthorized: No token provided');
return;
}
let auth;
try {
auth = aTs.verify(aT);
}
catch {
sendErrorResponse(fetchAPI, endResponse, 'Unauthorized: Invalid token');
return;
}
if (!isValidAuth(auth, clientType)) {
sendErrorResponse(fetchAPI, endResponse, 'Unauthorized: Invalid token or client type');
return;
}
console.log('auth: ', auth);
request.authorization = auth;
},
};
};
exports.default = useAuth;