Skip to content

Commit

Permalink
Merge pull request #36 from Mala1180/feature/frontend-creator-ids
Browse files Browse the repository at this point in the history
Refactor charts in frontend, link right creator id to new security rules
  • Loading branch information
Mala1180 authored Feb 1, 2024
2 parents 268d9dd + 08d6fe2 commit 9e6957a
Show file tree
Hide file tree
Showing 10 changed files with 118 additions and 69 deletions.
4 changes: 2 additions & 2 deletions auth/db/auth-init.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ db.user.insertMany([
surname: 'Matteini',
username: 'mattia',
password: '$2a$10$QmASVIA1cy65TArhkhINte52vrNuJMlSpdO2FVLqI/OM32LmK6jHS',
token: '',
token: 'apikey-dev',
refreshToken: '',
contacts: [{ type: 'SMS', value: '33344455678' }],
deviceIds: [
Expand All @@ -23,7 +23,7 @@ db.user.insertMany([
surname: 'Rossi',
username: 'paga16',
password: '$2a$10$eHwL5cAfFPqBAbQyAqH/nOK94EyttraZx/xjEwQQiQP.hyB/XT64.', //passwordprova hashed
token: '',
token: 'apikey-dev',
refreshToken: '',
contact: [
{
Expand Down
4 changes: 2 additions & 2 deletions auth/src/controller/userAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ export const userAccessController = {
login: async (
username: string,
password: string
): Promise<{ accessToken: string; refreshToken: string }> => {
): Promise<{ userId: string; accessToken: string; refreshToken: string }> => {
const user: User = await userManager.getUserByUsername(username)
if (!user) throw new Error('User not found')
const match: boolean = await bcrypt.compare(password, user.password)
if (!match) throw new Error('Wrong password')
user.token = jwtManager.generateAccessToken({ id: user.id, username: user.username })
user.refreshToken = jwtManager.generateRefreshToken({ id: user.id, username: user.username })
await userManager.updateUser(user)
return { accessToken: user.token, refreshToken: user.refreshToken }
return { userId: user.id, accessToken: user.token, refreshToken: user.refreshToken }
},

logout: async (token: string, username: string): Promise<void> => {
Expand Down
71 changes: 48 additions & 23 deletions frontend/src/components/devices/SensorData.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,61 +3,78 @@ import type { EnvironmentData, Sensor } from '@domain/device/core'
import { Measure } from '@domain/device/core'
import { getMeasureAcronym, getMeasureColor } from '@/utils/MeasureUtils'
import LineChart from '@/components/charts/LineChart.vue'
import { ref, watch } from 'vue'
import { onMounted, ref, toRaw, watch } from 'vue'
import { useBuffersStore } from '@/stores/buffers'
const { sensorData } = defineProps<{
sensorData: { sensor: Sensor; values: EnvironmentData[] }
}>()
const bufferLength: number = 20
const removeIfFull = (buffer: any[]): any[] => {
if (buffer.length > bufferLength) {
return buffer.shift()
const bufferStore = useBuffersStore()
const handleResize = () => {
if (window.innerWidth < 576) {
bufferStore.bufferLength = 80
} else if (window.innerWidth < 768) {
bufferStore.bufferLength = 120
} else if (window.innerWidth < 992) {
bufferStore.bufferLength = 150
} else if (window.innerWidth < 1200) {
bufferStore.bufferLength = 170
} else {
return buffer
bufferStore.bufferLength = 200
}
removeIfFull(bufferStore.temperatureBuffer)
removeIfFull(bufferStore.humidityBuffer)
removeIfFull(bufferStore.pressureBuffer)
console.log(bufferStore.bufferLength)
}
onMounted(() => {
window.addEventListener('resize', handleResize)
})
const removeIfFull = (buffer: any[]): void => {
while (buffer.length > bufferStore.bufferLength) {
buffer.shift()
}
}
let temperatureBuffer: number[] = []
let humidityBuffer: number[] = []
let pressureBuffer: number[] = []
let timestampsBuffer: string[] = []
watch(sensorData, newSensorData => {
newSensorData.values.forEach(value => {
switch (value.measure) {
case Measure.TEMPERATURE:
removeIfFull(temperatureBuffer)
temperatureBuffer.push(value.value)
removeIfFull(bufferStore.temperatureBuffer)
bufferStore.temperatureBuffer.push(value.value)
break
case Measure.HUMIDITY:
removeIfFull(humidityBuffer)
humidityBuffer.push(value.value)
removeIfFull(bufferStore.humidityBuffer)
bufferStore.humidityBuffer.push(value.value)
break
case Measure.PRESSURE:
removeIfFull(pressureBuffer)
pressureBuffer.push(value.value)
removeIfFull(bufferStore.pressureBuffer)
bufferStore.pressureBuffer.push(value.value)
break
}
removeIfFull(timestampsBuffer)
timestampsBuffer.push(value.timestamp.toLocaleString().split(' ')[1])
removeIfFull(bufferStore.timestampBuffer)
bufferStore.timestampBuffer.push(value.timestamp.toLocaleString().split(' ')[1])
chartData.value = {
labels: timestampsBuffer as never[],
labels: toRaw(bufferStore.timestampBuffer) as never[],
datasets: [
{
label: 'Temperature',
borderColor: 'red',
data: temperatureBuffer as never[]
data: toRaw(bufferStore.temperatureBuffer) as never[]
},
{
label: 'Humidity',
borderColor: 'orange',
data: humidityBuffer as never[]
data: toRaw(bufferStore.humidityBuffer) as never[]
},
{
label: 'Pressure',
borderColor: 'teal',
data: pressureBuffer as never[]
data: toRaw(bufferStore.pressureBuffer) as never[]
}
]
}
Expand Down Expand Up @@ -90,6 +107,14 @@ const chartData = ref({
const chartOptions = ref({
responsive: true,
maintainAspectRatio: false,
elements: {
line: {
borderWidth: 1.5
},
point: {
radius: 0
}
},
scales: {
x: {
display: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { Contact } from 'domain/dist/domain/monitoring/core'
import { type ExceedingRule, type IntrusionRule, ObjectClass } from 'domain/dist/domain/security-rule/core'
import { MeasureConverter, ObjectClassConverter } from 'domain/dist/utils'
import RequestHelper, { authHost, authPort, monitoringHost, monitoringPort } from '@/utils/RequestHelper'
import { useUserStore } from '@/stores/user'
const emit = defineEmits<{
(e: 'insert-exceeding-rule', exceedingRule: ExceedingRule): void
Expand Down Expand Up @@ -112,7 +113,7 @@ const addNewSecurityRule = () => {
measure.value,
'',
deviceIdFactory.createSensorId(toRaw(code.value).value),
'aaaaaaaaaaaaaaaaaaaaaaaa', // to put the id of the user taken from the pinia storage
useUserStore().userId,
toRaw(contacts.value).map((c: Contact) => {
return {
type: toRaw(c).label.split(':')[0],
Expand All @@ -129,8 +130,8 @@ const addNewSecurityRule = () => {
objectClass.value,
'',
deviceIdFactory.createCameraId(toRaw(code.value).value),
'aaaaaaaaaaaaaaaaaaaaaaaa', // to put the id of the user taken from the pinia storage
toRaw(contacts.value).map((c: Contact) => {
useUserStore().userId,
toRaw(contacts.value).map((c: { label: string; value: string }) => {
return {
type: toRaw(c).label,
value: toRaw(c).value
Expand Down
24 changes: 24 additions & 0 deletions frontend/src/stores/buffers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useBuffersStore = defineStore(
'buffers',
() => {
const bufferLength = ref<number>(200)
const temperatureBuffer = ref<number[]>([])
const humidityBuffer = ref<number[]>([])
const pressureBuffer = ref<number[]>([])
const timestampBuffer = ref<string[]>([])

return {
bufferLength,
temperatureBuffer,
humidityBuffer,
pressureBuffer,
timestampBuffer
}
},
{
persist: false
}
)
13 changes: 8 additions & 5 deletions frontend/src/stores/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,30 @@ import { defineStore } from 'pinia'
export const useUserStore = defineStore(
'user',
() => {
const isLoggedIn = ref(false)
let username = ref('')
let accessToken = ref('')
let refreshToken = ref('')
const isLoggedIn = ref<boolean>(false)
const userId = ref<string>('')
const username = ref<string>('')
const accessToken = ref<string>('')
const refreshToken = ref<string>('')

function clearFields(): void {
isLoggedIn.value = false
userId.value = ''
username.value = ''
accessToken.value = ''
refreshToken.value = ''
}

return {
isLoggedIn,
userId,
username,
accessToken,
refreshToken,
clearFields
}
},
{
persist: true
persist: false
}
)
28 changes: 13 additions & 15 deletions frontend/src/views/LoginView.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { ref } from 'vue'
import RequestHelper, { authHost, authPort } from '@/utils/RequestHelper'
import { HttpStatusCode as AxiosHttpStatusCode } from 'axios'
import { type AxiosResponse, HttpStatusCode as AxiosHttpStatusCode } from 'axios'
import router from '@/router'
import { useUserStore } from '@/stores/user'
Expand All @@ -10,23 +10,21 @@ const password = ref('')
const userStore = useUserStore()
const login = () => {
RequestHelper.post(`http://${authHost}:${authPort}/login`, {
const login = async () => {
const res: AxiosResponse = await RequestHelper.post(`http://${authHost}:${authPort}/login`, {
username: username.value,
password: password.value
})
.then((res): void => {
if (res.status == AxiosHttpStatusCode.Ok) {
userStore.username = username.value
userStore.accessToken = res.data.accessToken
userStore.refreshToken = res.data.refreshToken
userStore.isLoggedIn = true
router.push('/home')
} else {
console.log(`Login failed with status code ${res.status} and message ${res.data.message}`)
}
})
.catch((err): void => console.log(err))
if (res.status !== AxiosHttpStatusCode.Ok) {
console.log(`Login failed with status code ${res.status} and message ${res.data.message}`)
return
}
userStore.username = username.value
userStore.userId = res.data.userId
userStore.accessToken = res.data.accessToken
userStore.refreshToken = res.data.refreshToken
userStore.isLoggedIn = true
router.push('/home')
}
</script>

Expand Down
4 changes: 2 additions & 2 deletions monitoring/db/device-init.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ db.device.insert([{
},
'isCapturing': false,
'ipAddress': '192.168.1.10',
'intervalMillis': 1000,
'intervalMillis': 400,
'measures': [
'PRESSURE',
'TEMPERATURE',
Expand All @@ -35,7 +35,7 @@ db.device.insert([{
},
'isCapturing': false,
'ipAddress': '192.168.1.30',
'intervalMillis': 1000,
'intervalMillis': 300,
'measures': [
'PRESSURE',
'TEMPERATURE'
Expand Down
2 changes: 2 additions & 0 deletions monitoring/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { deviceRouter } from './routes/device.js'
import { jwtManager } from './utils/JWTManager.js'
import http, { Server as HttpServer } from 'http'
import { Server as SocketIOServer } from 'socket.io'
import { setupConsumers } from './consumer.js'

config()

Expand Down Expand Up @@ -66,5 +67,6 @@ if (process.env.NODE_ENV !== 'test') {
server.listen(PORT, async (): Promise<void> => {
console.log(`Monitoring server listening on ${process.env.MONITORING_PORT}`)
await mongoConnect()
await setupConsumers()
})
}
30 changes: 13 additions & 17 deletions sensor/src/producer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { EnvironmentDataFactoryImpl } from '@domain/device/factories/impl/Enviro
import { MeasureConverter } from '@utils/MeasureConverter.js'
import RequestHelper, { monitoringHost, monitoringPort } from './utils/RequestHelper.js'
import { Kafka, Partitioners, Producer } from 'kafkajs'
import { AxiosResponse, HttpStatusCode } from 'axios'

if (process.env.SENSOR_CODE === undefined && process.env.NODE_ENV !== 'develop') {
console.log('No sensor code provided')
Expand All @@ -18,26 +19,21 @@ const SENSOR_CODE: string = process.env.SENSOR_CODE || 'sen-01'
let sourceDevice: Sensor

export const getSensorInfo = async (): Promise<void> => {
// const monitoringHost: string = 'localhost' //process.env.MONITORING_HOST || 'localhost'
const monitoringUrl: string = `http://${monitoringHost}:${monitoringPort}`

RequestHelper.get(`${monitoringUrl}/devices/sensors/${SENSOR_CODE}`)
.then(res => {
console.log('Response:', res.data)
sourceDevice = new DeviceFactoryImpl().createSensor(
new DeviceIdFactoryImpl().createSensorId(res.data._id.code),
false,
res.data.ipAddress,
res.data.intervalMillis,
res.data.measures.map((measure: any) => {
return MeasureConverter.convertToMeasure(measure)
})
)
console.log(sourceDevice)
})
.catch(error => {
console.error('Error:', error.message)
const res: AxiosResponse = await RequestHelper.get(`${monitoringUrl}/devices/sensors/${SENSOR_CODE}`)
console.log('Response:', res.data)
if (res.status !== HttpStatusCode.Ok) throw new Error('Error while getting sensor info')
sourceDevice = new DeviceFactoryImpl().createSensor(
new DeviceIdFactoryImpl().createSensorId(res.data._id.code),
false,
res.data.ipAddress,
res.data.intervalMillis,
res.data.measures.map((measure: any) => {
return MeasureConverter.convertToMeasure(measure)
})
)
console.log(sourceDevice)
}

const kafkaContainer: string = process.env.KAFKA_CONTAINER || 'revue-kafka'
Expand Down

0 comments on commit 9e6957a

Please sign in to comment.