Generated
+6629
-1334
File diff suppressed because it is too large
Load Diff
@@ -12,19 +12,21 @@
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/express-session": "^1.19.0",
|
||||
"@types/node": "^25.7.0",
|
||||
"prisma": "^7.8.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/adapter-better-sqlite3": "^7.8.0",
|
||||
"@prisma/client": "^7.8.0",
|
||||
"dotenv": "^17.4.2",
|
||||
"@adminjs/express": "^6.1.1",
|
||||
"@adminjs/prisma": "^5.0.4",
|
||||
"@prisma/client": "^6.19.3",
|
||||
"adminjs": "^7.8.17",
|
||||
"express": "^5.2.1",
|
||||
"express-session": "^1.19.0",
|
||||
"mqtt": "^5.15.1",
|
||||
"prisma": "^6.19.3",
|
||||
"redis": "^5.12.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- RedefineTables
|
||||
PRAGMA defer_foreign_keys=ON;
|
||||
PRAGMA foreign_keys=OFF;
|
||||
CREATE TABLE "new_User" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"firstName" TEXT NOT NULL,
|
||||
"lastName" TEXT NOT NULL,
|
||||
"faceEmbedding" TEXT
|
||||
);
|
||||
INSERT INTO "new_User" ("faceEmbedding", "firstName", "id", "lastName") SELECT "faceEmbedding", "firstName", "id", "lastName" FROM "User";
|
||||
DROP TABLE "User";
|
||||
ALTER TABLE "new_User" RENAME TO "User";
|
||||
PRAGMA foreign_keys=ON;
|
||||
PRAGMA defer_foreign_keys=OFF;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- RedefineTables
|
||||
PRAGMA defer_foreign_keys=ON;
|
||||
PRAGMA foreign_keys=OFF;
|
||||
CREATE TABLE "new_Tag" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"userId" TEXT NOT NULL,
|
||||
CONSTRAINT "Tag_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
INSERT INTO "new_Tag" ("id", "userId") SELECT "id", "userId" FROM "Tag";
|
||||
DROP TABLE "Tag";
|
||||
ALTER TABLE "new_Tag" RENAME TO "Tag";
|
||||
CREATE UNIQUE INDEX "Tag_userId_key" ON "Tag"("userId");
|
||||
PRAGMA foreign_keys=ON;
|
||||
PRAGMA defer_foreign_keys=OFF;
|
||||
@@ -1,24 +1,24 @@
|
||||
generator client {
|
||||
provider = "prisma-client"
|
||||
output = "../src/generated/prisma"
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
firstName String
|
||||
lastName String
|
||||
faceEmbedding Bytes?
|
||||
faceEmbedding String?
|
||||
tag Tag?
|
||||
}
|
||||
|
||||
model Tag {
|
||||
id String @id @default(uuid())
|
||||
userId String @unique
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
||||
}
|
||||
|
||||
model Room {
|
||||
|
||||
@@ -3,8 +3,7 @@ import { getEntities, getEntitiesOfType, getEntity } from "./livedata.controller
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get("/entities", getEntities);
|
||||
router.get("/entities", getEntitiesOfType);
|
||||
router.get("/entities", getEntities, getEntitiesOfType);
|
||||
router.get("/entities/:urn", getEntity);
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import AdminJS from "adminjs";
|
||||
import AdminJSExpress from "@adminjs/express";
|
||||
import * as AdminJSPrisma from "@adminjs/prisma";
|
||||
import session from "express-session";
|
||||
import { componentLoader, Components } from './components.js'
|
||||
|
||||
import userResource from "./resources/adminjs.user.resource.js";
|
||||
import tagResource from "./resources/adminjs.tag.resource.js";
|
||||
import roomResource from "./resources/adminjs.room.resource.js";
|
||||
|
||||
AdminJS.registerAdapter({
|
||||
Database: AdminJSPrisma.Database,
|
||||
Resource: AdminJSPrisma.Resource,
|
||||
})
|
||||
|
||||
async function createAdmin() {
|
||||
const admin = new AdminJS({
|
||||
rootPath: "/admin",
|
||||
resources: [userResource, tagResource, roomResource],
|
||||
branding: { companyName: "OfficeSense", logo: false },
|
||||
dashboard: { component: Components.Dashboard },
|
||||
componentLoader,
|
||||
});
|
||||
|
||||
await admin.watch();
|
||||
|
||||
const router = AdminJSExpress.buildAuthenticatedRouter(
|
||||
admin,
|
||||
{
|
||||
authenticate: async (email, password) => {
|
||||
if (
|
||||
email === process.env.ADMIN_EMAIL &&
|
||||
password === process.env.ADMIN_PASSWORD
|
||||
) {
|
||||
return { email }
|
||||
}
|
||||
return null
|
||||
},
|
||||
cookieName: 'adminjs',
|
||||
cookiePassword: process.env.ADMIN_COOKIE_SECRET ?? 'change-me',
|
||||
},
|
||||
null,
|
||||
{
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
secret: process.env.ADMIN_COOKIE_SECRET ?? 'change-me',
|
||||
}
|
||||
)
|
||||
|
||||
return { admin, router }
|
||||
}
|
||||
|
||||
const sessionMiddleware = session({
|
||||
secret: process.env.ADMIN_COOKIE_SECRET ?? "change-me",
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
});
|
||||
|
||||
export { createAdmin, sessionMiddleware }
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ComponentLoader } from 'adminjs'
|
||||
import { fileURLToPath } from 'url'
|
||||
import path from 'path'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
export const componentLoader = new ComponentLoader()
|
||||
|
||||
export const Components = {
|
||||
Dashboard: componentLoader.add('Dashboard', path.join(__dirname, './components/Dashboard.tsx'), 'components'),
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { Box, H2, Text, Loader } from '@adminjs/design-system'
|
||||
import { ApiClient } from 'adminjs'
|
||||
|
||||
type Session = {
|
||||
realUserId: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
pseudoId: string
|
||||
pseudoName: string
|
||||
}
|
||||
|
||||
const Dashboard = () => {
|
||||
const [sessions, setSessions] = useState<Session[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [updated, setUpdated] = useState<string>('')
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
const res = await fetch('/admin/map', { credentials: 'include' })
|
||||
const data = await res.json()
|
||||
setSessions(data)
|
||||
setUpdated(new Date().toLocaleTimeString())
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
const interval = setInterval(load, 10000)
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
const initials = (first: string, last: string) =>
|
||||
((first?.[0] ?? '') + (last?.[0] ?? '')).toUpperCase() || '?'
|
||||
|
||||
return (
|
||||
<Box padding="xl">
|
||||
<Box display="flex" alignItems="center" justifyContent="space-between" marginBottom="xl">
|
||||
<Box>
|
||||
<H2>OfficeSense Admin Dashboard</H2>
|
||||
<Text color="grey60">Live Redis sessions mapped to registered users</Text>
|
||||
</Box>
|
||||
<Box display="flex" alignItems="center">
|
||||
<Text color="grey60" fontSize="sm" marginRight="md">Updated {updated}</Text>
|
||||
<Box
|
||||
as="button"
|
||||
onClick={load}
|
||||
style={{
|
||||
padding: '6px 14px',
|
||||
borderRadius: '6px',
|
||||
border: '1px solid #e5e7eb',
|
||||
background: '#fff',
|
||||
cursor: 'pointer',
|
||||
fontSize: '13px',
|
||||
}}
|
||||
>
|
||||
Refresh
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{loading ? (
|
||||
<Loader />
|
||||
) : sessions.length === 0 ? (
|
||||
<Text color="grey60">No active sessions.</Text>
|
||||
) : (
|
||||
<Box
|
||||
style={{
|
||||
background: '#fff',
|
||||
border: '1px solid #e5e7eb',
|
||||
borderRadius: '12px',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '13px' }}>
|
||||
<thead>
|
||||
<tr style={{ background: '#fafafa' }}>
|
||||
{['User', 'Real UUID', 'Pseudo UUID', 'Pseudo name'].map(h => (
|
||||
<th key={h} style={{
|
||||
textAlign: 'left', padding: '10px 16px',
|
||||
fontSize: '11px', color: '#9ca3af',
|
||||
textTransform: 'uppercase', letterSpacing: '0.05em',
|
||||
borderBottom: '1px solid #f3f4f6', fontWeight: 500,
|
||||
}}>{h}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sessions.map(s => (
|
||||
<tr key={s.realUserId} style={{ borderBottom: '1px solid #f9fafb' }}>
|
||||
<td style={{ padding: '12px 16px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<div style={{
|
||||
width: 28, height: 28, borderRadius: '50%',
|
||||
background: '#eff6ff', color: '#2563eb',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: '11px', fontWeight: 600, flexShrink: 0,
|
||||
}}>
|
||||
{initials(s.firstName, s.lastName)}
|
||||
</div>
|
||||
{s.firstName} {s.lastName}
|
||||
</div>
|
||||
</td>
|
||||
<td style={{ padding: '12px 16px', fontFamily: 'monospace', fontSize: '12px', color: '#6b7280' }}>{s.realUserId}</td>
|
||||
<td style={{ padding: '12px 16px', fontFamily: 'monospace', fontSize: '12px', color: '#6b7280' }}>{s.pseudoId}</td>
|
||||
<td style={{ padding: '12px 16px' }}>{s.pseudoName ?? '—'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default Dashboard
|
||||
@@ -0,0 +1,16 @@
|
||||
import { prisma } from "../../../lib/prisma.js";
|
||||
import { getModelByName } from "@adminjs/prisma";
|
||||
|
||||
export default {
|
||||
resource: {
|
||||
model: getModelByName("Room"),
|
||||
client: prisma,
|
||||
},
|
||||
options: {
|
||||
navigation: { icon: "Map" },
|
||||
listProperties: ["id", "name"],
|
||||
showProperties: ["id", "name"],
|
||||
editProperties: ["name"],
|
||||
filterProperties: ["name"],
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { prisma } from "../../../lib/prisma.js";
|
||||
import { getModelByName } from "@adminjs/prisma";
|
||||
|
||||
export default {
|
||||
resource: {
|
||||
model: getModelByName("Tag"),
|
||||
client: prisma,
|
||||
},
|
||||
options: {
|
||||
navigation: { icon: "Tag" },
|
||||
listProperties: ["id", "user"],
|
||||
showProperties: ["id", "user"],
|
||||
editProperties: ["user"],
|
||||
filterProperties: ["user"],
|
||||
properties: {
|
||||
user: {
|
||||
reference: "User",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { prisma } from "../../../lib/prisma.js";
|
||||
import { getModelByName } from "@adminjs/prisma";
|
||||
|
||||
export default {
|
||||
resource: {
|
||||
model: getModelByName("User"),
|
||||
client: prisma,
|
||||
},
|
||||
options: {
|
||||
titleProperty: "id",
|
||||
navigation: { icon: "User" },
|
||||
listProperties: ["id", "firstName", "lastName"],
|
||||
showProperties: ["id", "firstName", "lastName"],
|
||||
editProperties: ["firstName", "lastName"],
|
||||
filterProperties: ["firstName", "lastName"],
|
||||
properties: {
|
||||
faceEmbedding: {
|
||||
isVisible: false,
|
||||
type: "string"
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
import { generateMap } from "./mapper.repository.js";
|
||||
|
||||
export function checkSession(req: Request, res: Response, next: NextFunction) {
|
||||
if (!(req.session as any)?.adminUser) {
|
||||
return res.status(401).json({ error: 'Unauthorized' })
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
export async function getRedisMapping(req: Request, res: Response) {
|
||||
try {
|
||||
res.status(200).send(await generateMap());
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: 'Failed to fetch sessions' })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { getRedis } from "../../redis/redis.js";
|
||||
import { prisma } from "../../lib/prisma.js";
|
||||
|
||||
export async function generateMap() {
|
||||
const redis = getRedis();
|
||||
|
||||
const keys = await redis.keys('user:*')
|
||||
|
||||
const sessions = await Promise.all(keys.map(async (key) => {
|
||||
const raw = await redis.get(key)
|
||||
const session = JSON.parse(raw!)
|
||||
const realUserId = key.replace('user:', '')
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: realUserId },
|
||||
select: { id: true, firstName: true, lastName: true }
|
||||
})
|
||||
|
||||
return {
|
||||
realUserId,
|
||||
firstName: user?.firstName ?? 'Unknown',
|
||||
lastName: user?.lastName ?? 'Unknown',
|
||||
pseudoId: session.userID,
|
||||
pseudoName: session.name
|
||||
}
|
||||
}))
|
||||
|
||||
return sessions;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import express from "express";
|
||||
import { getRedisMapping, checkSession } from "./mapper.controller.js";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get("/map", checkSession, getRedisMapping);
|
||||
|
||||
export default router;
|
||||
@@ -1,14 +1,22 @@
|
||||
import express from "express";
|
||||
import lookupRoutes from "./api/lookup/lookup.routes.js";
|
||||
import livedataRoutes from "./api/livedata/livadata.routes.js"
|
||||
import lookupRouter from "./api/lookup/lookup.routes.js";
|
||||
import livedataRouter from "./api/livedata/livadata.routes.js"
|
||||
import mapperRouter from "./api/mapper/mapper.routes.js"
|
||||
import { createAdmin, sessionMiddleware } from './api/management/adminjs.routes.js'
|
||||
import config from "./config/config.js";
|
||||
import { bootstrap } from "./core/bootstrap.js";
|
||||
|
||||
(async () => {
|
||||
const app = express();
|
||||
|
||||
app.use("/lookup", lookupRoutes);
|
||||
app.use("/livedata", livedataRoutes);
|
||||
const { admin, router: adminRouter } = await createAdmin();
|
||||
|
||||
app.use(sessionMiddleware);
|
||||
|
||||
app.use("/lookup", lookupRouter);
|
||||
app.use("/livedata", livedataRouter);
|
||||
app.use("/admin", mapperRouter);
|
||||
app.use("/admin", adminRouter);
|
||||
|
||||
app.listen(config.api.port, config.api.address, () => {
|
||||
console.log(`Server listening on ${config.api.address}:${config.api.port}`);
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import "dotenv/config";
|
||||
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
|
||||
import { PrismaClient } from "../generated/prisma/client.js";
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const connectionString = `${process.env.DATABASE_URL}`;
|
||||
|
||||
const adapter = new PrismaBetterSqlite3({ url: connectionString });
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
export { prisma };
|
||||
Reference in New Issue
Block a user