Guest User

Untitled

a guest
Sep 18th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. import express from 'express'
  2. import { ApolloServer } from 'apollo-server-express'
  3.  
  4. import passport from 'passport'
  5. import passportJWT from 'passport-jwt'
  6.  
  7. import schema from './schemas'
  8.  
  9. const { JWT_SECRET } = process.env
  10.  
  11. const path = '/graphql'
  12.  
  13. // ...
  14.  
  15. const users = [
  16. {
  17. id: 1,
  18. name: 'John',
  19. email: 'john@mail.com',
  20. password: 'john123'
  21. },
  22. {
  23. id: 2,
  24. name: 'Sarah',
  25. email: 'sarah@mail.com',
  26. password: 'sarah123'
  27. }
  28. ]
  29.  
  30. // ...
  31.  
  32. const { Strategy, ExtractJwt } = passportJWT
  33.  
  34. const params = {
  35. secretOrKey: JWT_SECRET,
  36. jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
  37. }
  38.  
  39. // ...
  40.  
  41. const strategy = new Strategy(params, (payload, done) => {
  42. const user = users[payload.id] || null
  43.  
  44. if (user) {
  45. return done(null, {
  46. id: user.id
  47. })
  48. }
  49.  
  50. return done(new Error('The user has not been found'), null)
  51. })
  52.  
  53. passport.use(strategy)
  54.  
  55. // ...
  56.  
  57. const app = express()
  58.  
  59. passport.initialize()
  60.  
  61. app.use(path, passport.authenticate('jwt', { session: false }))
  62.  
  63. // ...
  64.  
  65. const server = new ApolloServer({
  66. schema
  67. })
  68.  
  69. server.applyMiddleware({
  70. app,
  71. path
  72. })
  73.  
  74. app.listen(
  75. {
  76. port: 4000
  77. },
  78. () => console.log(`The GraphQL server is running on port ${GRAPHQL_PORT}`)
  79. )
Add Comment
Please, Sign In to add comment