This repository has been archived by the owner on Apr 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
basic.js
78 lines (59 loc) · 1.87 KB
/
basic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const fs = require('fs')
const path = require('path')
const express = require('express')
const session = require('express-session')
const Keycloak = require('keycloak-connect')
const { KeycloakContext, KeycloakTypeDefs, KeycloakSchemaDirectives } = require('../')
const { ApolloServer, gql } = require('apollo-server-express')
const keycloakConfig = JSON.parse(fs.readFileSync(path.resolve(__dirname, './config/keycloak.json')))
const app = express()
const memoryStore = new session.MemoryStore()
const graphqlPath = '/graphql'
app.use(session({
secret: process.env.SESSION_SECRET_STRING || 'this should be a long secret',
resave: false,
saveUninitialized: true,
store: memoryStore
}))
const keycloak = new Keycloak({
store: memoryStore
}, keycloakConfig)
// Install general keycloak middleware
app.use(keycloak.middleware({
admin: graphqlPath
}))
// Protect the main route for all graphql services
// Disable unauthenticated access
app.use(graphqlPath, keycloak.protect())
const typeDefs = gql`
type Query {
hello: String @hasRole(role: "developer")
}
`
const resolvers = {
Query: {
hello: (obj, args, context, info) => {
// log some of the auth related info added to the context
console.log(context.kauth.isAuthenticated())
console.log(context.kauth.accessToken.content.name)
const name = context.kauth.accessToken.content.preferred_username || 'world'
return `Hello ${name}`
}
}
}
// Initialize the voyager server with our schema and context
const server = new ApolloServer({
typeDefs: [KeycloakTypeDefs, typeDefs],
schemaDirectives: KeycloakSchemaDirectives,
resolvers,
context: ({ req }) => {
return {
kauth: new KeycloakContext({ req })
}
}
})
server.applyMiddleware({ app })
const port = 4000
app.listen({ port }, () =>
console.log(`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`)
)