Efren Yevale Varela 3 лет назад
Родитель
Сommit
fe9b4600f4
1 измененных файлов с 24 добавлено и 7 удалено
  1. 24 7
      app.js

+ 24 - 7
app.js

@@ -2,13 +2,15 @@
 
 require("dotenv").config();
 
-const cors    = require("cors");
-const express = require("express");
-const helmet  = require("helmet");
-const http    = require("http");
+const cors       = require("cors");
+const express    = require("express");
+const helmet     = require("helmet");
+const http       = require("http");
+const jwksClient = require("jwks-rsa");
+const jwt        = require("jsonwebtoken");
 
-const { ApolloServer, gql }                 = require("apollo-server-express");
-const { ApolloServerPluginDrainHttpServer } = require("apollo-server-core");
+const { ApolloServer, AuthenticationError, gql } = require("apollo-server-express");
+const { ApolloServerPluginDrainHttpServer }      = require("apollo-server-core");
 
 const corsOrigins = process.env.APP_CORS_ORIGINS.split(",");
 
@@ -38,10 +40,25 @@ const resolvers = {
   }
 };
 
+let client = jwksClient({ jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json` });
+
+const authentication = async context => {
+  const token = context.req.headers.authorization || "";
+  if (!token) throw new AuthenticationError("Authentication required");
+
+  const keys = await client.getSigningKeys();
+
+  const user = await jwt.verify(token, keys[0].getPublicKey(), { algorithms: [ "RS256" ] });
+  if (!user.email) throw new AuthenticationError("Wrong token presented");
+
+  return { user };
+}
+
 const apollo = new ApolloServer({
   typeDefs,
   resolvers,
-  plugin: [ApolloServerPluginDrainHttpServer({ httpServer })]
+  plugin: [ApolloServerPluginDrainHttpServer({ httpServer })],
+  context: authentication
 });
 apollo.start().then(_ => {
   apollo.applyMiddleware({ app });