Skip to content

Commit

Permalink
Add Graphql Apollo server to server_realtime_auth.
Browse files Browse the repository at this point in the history
  • Loading branch information
riclolsen committed Sep 13, 2024
1 parent ea1271a commit 32c0168
Show file tree
Hide file tree
Showing 6 changed files with 1,358 additions and 145 deletions.
1 change: 1 addition & 0 deletions src/server_realtime_auth/app/models/tag.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const Tag = mongoose.model(
protocolSourceCommonAddress: { type: mongoose.Mixed, default: '' },
protocolSourceConnectionNumber: { type: Double, default: 0.0 },
protocolSourceObjectAddress: { type: mongoose.Mixed, default: '' },
sourceDataUpdate: { type: Object, default: null },
stateTextFalse: { type: String, default: '' },
stateTextTrue: { type: String, default: '' },
substituted: { type: Boolean, default: false },
Expand Down
4 changes: 4 additions & 0 deletions src/server_realtime_auth/app/routes/auth.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,8 @@ module.exports = function (app, accessPoint) {
[authJwt.isAdmin],
controller.updateUser
)
app.post(
accessPoint + 'auth/changePassword',
controller.changePassword
)
}
129 changes: 129 additions & 0 deletions src/server_realtime_auth/graphql-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
const { ApolloServer } = require('@apollo/server')
const { expressMiddleware } = require('@apollo/server/express4')
const cors = require('cors')
const bodyParser = require('body-parser')
const { authJwt } = require('./app/middlewares')

async function initGQLServer(app, db) {
// Create an Apollo server
const srvApollo = new ApolloServer({
typeDefs: `#graphql
type Query {
getUsers: [User!]!
getUserByName(username: String!): User
}
type User {
_id: ID!
username: String!
email: String
roles: [ID!]
}
type Query {
getTags: [Tag!]!
getTag(tag: String!): Tag
}
type SourceDataUpdate {
valueAtSource: Float
valueStringAtSource: String
valueJsonAtSource: String
asduAtSource: String
causeOfTransmissionAtSource: String
timeTagAtSource: Float
timeTagAtSourceOk: Boolean
timeTag: Float
notTopicalAtSource: Boolean
invalidAtSource: Boolean
overflowAtSource: Boolean
blockedAtSource: Boolean
substitutedAtSource: Boolean
originator: String
}
type Tag {
_id: Float!
tag: String!
value: Float
valueString: String
valueJson: String
alarmDisabled: Boolean
alarmRange: Float
alarmState: Float
alarmed: Boolean
alerted: Boolean
alertState: String
annotation: String
commandBlocked: Boolean
commandOfSupervised: Float
commissioningRemarks: String
description: String
eventTextFalse: String
eventTextTrue: String
formula: Float
frozen: Boolean
frozenDetectTimeout: Float
group1: String
group2: String
group3: String
hihihiLimit: Float
hihiLimit: Float
hiLimit: Float
historianDeadBand: Float
historianPeriod: Float
historianLastValue: Float
hysteresis: Float
invalid: Boolean
invalidDetectTimeout: Float
isEvent: Boolean
kconv1: Float
kconv2: Float
loLimit: Float
loloLimit: Float
lololoLimit: Float
notes: String
origin: String
overflow: Boolean
priority: Float
stateTextFalse: String
stateTextTrue: String
substituted: Boolean
supervisedOfCommand: Float
timeTag:Float
timeTagAlarm: Float
timeTagAlertState: Float
timeTagAtSource: Float
timeTagAtSourceOk: Boolean
transient: Boolean
type: String
ungroupedDescription: String
unit: String
updatesCnt: Float
zeroDeadband: Float
sourceDataUpdate: SourceDataUpdate
}
`,
resolvers: {
Query: {
getUsers: async () => {
return await db.user.find()
},
getUserByName: async (_, qry) => {
return await db.user.findOne({ username: qry.username })
},
getTags: async () => {
return await db.tag.find()
},
getTag: async (_, qry) => {
return await db.tag.findOne({ tag: qry.tag })
},
},
},
})
await srvApollo.start()
app.use(cors(), bodyParser.json())
app.use('/apollo', [authJwt.verifyToken], expressMiddleware(srvApollo))
}

module.exports = initGQLServer
126 changes: 64 additions & 62 deletions src/server_realtime_auth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const opc = require('./opc_codes.js')
const { Pool } = require('pg')
const UserActionsQueue = require('./userActionsQueue')
const GetQueryPostgresql = require('./customJsonQueries')
const initGQLServer = require('./graphql-server.js')

const config = require('./app/config/auth.config.js')
if (process.env.JS_JWT_SECRET) config.secret = process.env.JS_JWT_SECRET
Expand All @@ -68,73 +69,74 @@ const EventsRemoveGuardSeconds = 20
const jsConfig = LoadConfig()
let HintMongoIsConnected = true

if (AUTHENTICATION) {
// JWT Auth Mongo Express https://bezkoder.com/node-js-mongodb-auth-jwt/
dbAuth.mongoose
.connect(jsConfig.mongoConnectionString, jsConfig.MongoConnectionOptions)
.then(() => {
Log.log('Successfully connect to MongoDB (via mongoose).')
// initial();
})
.catch((err) => {
console.error('Connection error', err)
process.exit()
})

app.use(cookieParser())
app.options(OPCAPI_AP, cors()) // enable pre-flight request
app.use(express.json())
app.use(
express.urlencoded({
extended: true,
})
)
} else {
Log.log('******* DISABLED AUTHENTICATION! ********')

// reverse proxy for grafana
app.use('/grafana', httpProxy(GRAFANA_SERVER))
// reverse proxy for grafana
app.use('/metabase', httpProxy(METABASE_SERVER))
// reverse proxy for log.io
app.use('/log-io', httpProxy(LOGIO_SERVER))
const wsProxy = createProxyMiddleware({
target: logioServer,
ws: true, // enable websocket proxy
})
app.use('/socket.io', wsProxy)
app.on('upgrade', wsProxy.upgrade)

// add charset for special sage displays
app.use(
'/sage-cepel-displays/',
express.static('../htdocs/sage-cepel-displays', {
setHeaders: function (res, path) {
if (/.*\.html/.test(path)) {
res.set({ 'content-type': 'text/html; charset=iso-8859-1' })
}
},
})
)
app.use(express.static('../htdocs')) // serve static files
app.options(OPCAPI_AP, cors()) // enable pre-flight request
app.use(express.json())
app.use(
express.urlencoded({
extended: true,
})
)
// Here we serve up the index page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '../htdocs/index.html'))
})
}

let db = null
let clientMongo = null
let pool = null

;(async () => {
if (AUTHENTICATION) {
// JWT Auth Mongo Express https://bezkoder.com/node-js-mongodb-auth-jwt/
dbAuth.mongoose
.connect(jsConfig.mongoConnectionString, jsConfig.MongoConnectionOptions)
.then(() => {
Log.log('Successfully connect to MongoDB (via mongoose).')
// initial();
})
.catch((err) => {
console.error('Connection error', err)
process.exit()
})

app.use(cookieParser())
app.options(OPCAPI_AP, cors()) // enable pre-flight request
app.use(express.json())
app.use(
express.urlencoded({
extended: true,
})
)
initGQLServer(app, dbAuth)
} else {
Log.log('******* DISABLED AUTHENTICATION! ********')

// reverse proxy for grafana
app.use('/grafana', httpProxy(GRAFANA_SERVER))
// reverse proxy for grafana
app.use('/metabase', httpProxy(METABASE_SERVER))
// reverse proxy for log.io
app.use('/log-io', httpProxy(LOGIO_SERVER))
const wsProxy = createProxyMiddleware({
target: logioServer,
ws: true, // enable websocket proxy
})
app.use('/socket.io', wsProxy)
app.on('upgrade', wsProxy.upgrade)

// add charset for special sage displays
app.use(
'/sage-cepel-displays/',
express.static('../htdocs/sage-cepel-displays', {
setHeaders: function (res, path) {
if (/.*\.html/.test(path)) {
res.set({ 'content-type': 'text/html; charset=iso-8859-1' })
}
},
})
)
app.use(express.static('../htdocs')) // serve static files
app.options(OPCAPI_AP, cors()) // enable pre-flight request
app.use(express.json())
app.use(
express.urlencoded({
extended: true,
})
)
// Here we serve up the index page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '../htdocs/index.html'))
})
}

app.listen(HTTP_PORT, IP_BIND, () => {
Log.log('listening on ' + HTTP_PORT)
})
Expand Down
Loading

0 comments on commit 32c0168

Please sign in to comment.