Skip to content

Instantly share code, notes, and snippets.

@FBI23
Created September 20, 2018 07:19
Show Gist options
  • Save FBI23/388b4124cc432b5267e8131c2731cfe3 to your computer and use it in GitHub Desktop.
Save FBI23/388b4124cc432b5267e8131c2731cfe3 to your computer and use it in GitHub Desktop.
Basic Auth Apollo server Node Js Lambda Serverless
import { graphqlLambda } from "apollo-server-lambda";
import { makeExecutableSchema } from "graphql-tools";
import resolvers from "../resolvers";
import typeDefs from "../schema.graphql";
import { renderPlaygroundPage } from "graphql-playground-html";
const graphql = graphqlLambda((event, context) => {
const headers = event.headers;
const functionName = context.functionName;
context.callbackWaitsForEmptyEventLoop = false;
return {
schema: makeExecutableSchema({
typeDefs,
resolvers
}),
context: { headers, functionName, event, context }
};
});
const basicAuthMiddleware = () => {};
const playgroundMiddleware = (options = {}) => {
return async (event, context, callback) => {
const headers = JSON.parse(JSON.stringify(event)).headers;
// TODO: move to config
const authUser = "user";
const authPass = "pass";
// construct the basic auth string
const authString =
"Basic " + new Buffer(authUser + ":" + authPass).toString("base64");
// require basic authentication
if (headers.Authorization && headers.Authorization === authString) {
// set playground version
const middlewareOptions = {
...options,
version: require("../../package.json").dependencies[
"graphql-playground-middleware-lambda"
]
};
callback(null, {
statusCode: 200,
headers: {
"Content-Type": "text/html"
},
body: await renderPlaygroundPage(middlewareOptions)
});
} else {
const body = "Unauthorized";
const response = {
statusCode: 401,
statusDescription: "Unauthorized",
body: body,
headers: {
"WWW-Authenticate": "Basic"
}
};
callback(null, response);
}
};
};
const playground = playgroundMiddleware({
endpointURL: "/graphql"
});
const hello = async (event, context, callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: `Hello World`
})
};
callback(null, response);
};
const generatePolicy = (principalId, effect, resource) => {
const authResponse = {};
authResponse.principalId = principalId;
if (effect && resource) {
const policyDocument = {};
policyDocument.Version = "2012-10-17";
policyDocument.Statement = [];
const statementOne = {};
statementOne.Action = "execute-api:Invoke";
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
}
return authResponse;
};
const authorizer = async (event, context, callback) => {
callback(null, generatePolicy("yat", "Allow", event.methodArn));
};
export { hello, graphql, playground, authorizer };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment