app.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. require("dotenv").config();
  3. const cors = require("cors");
  4. const express = require("express");
  5. const helmet = require("helmet");
  6. const http = require("http");
  7. const jwksClient = require("jwks-rsa");
  8. const jwt = require("jsonwebtoken");
  9. const { ApolloServer, AuthenticationError, gql } = require("apollo-server-express");
  10. const { ApolloServerPluginDrainHttpServer } = require("apollo-server-core");
  11. const corsOrigins = process.env.APP_CORS_ORIGINS.split(",");
  12. const app = express();
  13. app.enable("trust proxy");
  14. app.use(cors({ origin: corsOrigins }));
  15. if (app.get("env") === "production") {
  16. app.use(helmet());
  17. app.use(helmet.contentSecurityPolicy());
  18. }
  19. const httpServer = http.createServer(app);
  20. const typeDefs = gql`
  21. type Hello {
  22. message: String
  23. }
  24. type Query {
  25. hello: Hello
  26. }
  27. `;
  28. const resolvers = {
  29. Query: {
  30. hello: _ => ({ message: "Hello World!" })
  31. }
  32. };
  33. let client = jwksClient({ jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json` });
  34. const authentication = async context => {
  35. const token = context.req.headers.authorization || "";
  36. if (!token) throw new AuthenticationError("Authentication required");
  37. const keys = await client.getSigningKeys();
  38. const user = await jwt.verify(token, keys[0].getPublicKey(), { algorithms: [ "RS256" ] });
  39. if (!user.email) throw new AuthenticationError("Wrong token presented");
  40. return { user };
  41. }
  42. const apollo = new ApolloServer({
  43. typeDefs,
  44. resolvers,
  45. plugin: [ApolloServerPluginDrainHttpServer({ httpServer })],
  46. context: authentication
  47. });
  48. apollo.start().then(_ => {
  49. apollo.applyMiddleware({ app });
  50. app.all("*", (request, response) => response.send(""));
  51. httpServer.listen(process.env.APP_PORT);
  52. let apolloData = httpServer.address();
  53. console.log(`GraphQL service listening on ${apolloData.address}:${apolloData.port}${apollo.graphqlPath}`);
  54. }).catch(error => console.log(error.message));