Initial commit

This commit is contained in:
2025-03-06 12:24:20 +01:00
commit 7f3cefdc22
37 changed files with 6581 additions and 0 deletions

79
src/capability.ts Normal file
View File

@@ -0,0 +1,79 @@
import { NextFunction, Request, Response } from "express";
import { readFileSync } from "fs";
interface Options {
"news": boolean,
"menu": boolean,
"notif": boolean,
"groups": boolean,
"clean": boolean,
"key": boolean
}
enum Features {
News,
Menu,
Notif,
Groups,
Clean,
Key,
}
class Settings {
private _flags: number = 0
public settings: Options;
constructor () {
this.reloadSettings()
}
private optionsToFlags() {
this._flags = 0
this._flags += this.settings.news && 1
this._flags += this.settings.menu && 2
this._flags += this.settings.notif && 4
this._flags += this.settings.groups && 8
this._flags += this.settings.clean && 16
this._flags += this.settings.key && 32
}
public reloadSettings() {
this.settings = JSON.parse(readFileSync('./config/options.json', 'utf-8'))
this.optionsToFlags()
}
public get flags() : number {
return this._flags;
}
public mw(f: Features) {
return (_req: Request, res: Response, next: NextFunction) => {
switch (f) {
case Features.News:
if (this.settings.news) return next()
break;
case Features.Menu:
if (this.settings.menu) return next()
break;
case Features.Notif:
if (this.settings.notif) return next()
break;
case Features.Groups:
if (this.settings.groups) return next()
break;
case Features.Clean:
if (this.settings.clean) return next()
break;
case Features.Key:
if (this.settings.key) return next()
break;
default:
break;
}
res.sendStatus(406)
}
}
}
export default new Settings()
export { Features }

90
src/index.ts Normal file
View File

@@ -0,0 +1,90 @@
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import passport from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import session from "express-session";
import bcrypt from 'bcryptjs';
import MongoStore from "connect-mongo";
import mongoose from "mongoose"
import User from "./schemas/User";
import routes from "./routes/index";
import process from "node:process"
const connectionString = process.env.ATLAS_URI || "mongodb://mongodb:27017/ipwa";
if (!process.env.ORIGIN) {
console.log("CORS origin undefined")
process.exit(1)
}
declare global {
namespace Express {
export interface User {
_id: mongoose.Types.ObjectId;
pass: string;
uname: string;
admin?: number;
locked?: boolean;
room?: number
}
}
}
//#region express initialization
var app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors({
origin: ["http://localhost:4200", "http://localhost:3000", process.env.ORIGIN,],
credentials: true
}))
app.use(session({
resave: false,
rolling: true,
secret: process.env.SECRET,
saveUninitialized: false,
store: MongoStore.create({mongoUrl: connectionString, dbName: "ipwa", collectionName: "sessions", touchAfter: 60, autoRemove: 'disabled'}),
cookie: {
maxAge: 1209600000,
}
}))
app.use(passport.session())
//#endregion
//#region Passport strategies initialization
passport.use("normal",new LocalStrategy(async function verify(uname,pass,done) {
let query = await User.findOne({uname: uname.toLowerCase()})
if (query.locked == true) return done(null, false)
if (query) {
if (await bcrypt.compare(pass, query.pass)) {
return done(null, query)
} else done(null, false)
} else {
done(null, false)
}
}))
//#endregion
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(async function(id, done) {
let query = await User.findById(id)
if (query) {
done(null, query)
} else {
done(null, false)
}
});
app.listen(8080, async () => {
await mongoose.connect(connectionString);
if (process.send) process.send("ready")
})
app.use('/', routes)
process.on('SIGINT', () => {
mongoose.disconnect().then(() => process.exit(0), () => process.exit(1))
})

60
src/notif.ts Normal file
View File

@@ -0,0 +1,60 @@
import { PushSubscription, RequestOptions, SendResult, sendNotification } from "web-push";
import { readFileSync } from "fs";
import Notification from "./schemas/Notification";
import { allNotif, groupNotif, roomNotif, userNotif } from "./pipelines/notif";
export class NotifcationHelper {
private options: RequestOptions
constructor () {
let keys = JSON.parse(readFileSync("./config/keys.json", 'utf-8'))
this.options = {
vapidDetails: {
subject: "CHANGE ME",
privateKey: keys.privateKey,
publicKey: keys.publicKey
}
}
}
private async send(message: string, subscriptions: PushSubscription[]) {
var count = 0;
var subslen = subscriptions.length
for (const v of subscriptions) {
var result
try {
result = await sendNotification(v, message, this.options)
count++
} catch (error) {
if (error.statusCode == 410) {
console.log("GONE")
await Notification.findOneAndDelete({endpoint: v.endpoint, keys: v.keys})
subslen--
}
else console.log(error)
}
}
return {sent: count, possible: subslen}
}
private rcpt(message: string) {
return {
user: async (uname: string) => {
return await this.send(message, await Notification.aggregate(userNotif(uname)))
},
room: async (room: number) => {
return await this.send(message, await Notification.aggregate(roomNotif(room)))
},
group: async (group: string) => {
return await this.send(message, await Notification.aggregate(groupNotif(group)))
},
withRoom: async () => {
return await this.send(message, await Notification.aggregate(allNotif()))
}
}
}
simpleMessage(title: string, body: string) {
return this.rcpt(JSON.stringify({notification: {title: title, body: body}}))
}
}

151
src/pipelines/notif.ts Normal file
View File

@@ -0,0 +1,151 @@
import { PipelineStage, Types } from "mongoose"
function userNotif(uname: string) {
var pipeline: PipelineStage[] = [
{
"$match": {
uname: uname
}
}
]
return pipeline
}
function roomNotif(room: number) {
var pipeline: PipelineStage[] = [
{
$lookup: {
from: "logins",
localField: "uname",
foreignField: "uname",
as: "user",
},
},
{
$unwind: {
path: "$user",
preserveNullAndEmptyArrays: false,
},
},
{
$addFields: {
rooms: "$user.room",
},
},
{
$match:
{
rooms: room,
},
},
{
$unset:
["user", "uname", "rooms"],
},
]
return pipeline
}
function allNotif() {
var pipeline: PipelineStage[] = [
{
$lookup: {
from: "logins",
localField: "uname",
foreignField: "uname",
as: "user",
},
},
{
$unwind: {
path: "$user",
preserveNullAndEmptyArrays: false,
},
},
{
$addFields: {
rooms: "$user.room",
},
},
{
$match:
{
rooms: {$exists: true},
},
},
{
$unset:
["user", "uname", "rooms"],
},
]
return pipeline
}
function groupNotif(group: string) {
var pipeline: PipelineStage[] = [
{
$match:
{
_id: new Types.ObjectId(group)
}
},
{
$graphLookup:
{
from: "logins",
startWith: "$rooms",
connectFromField: "rooms",
connectToField: "room",
as: "logins",
},
},
{
$set: {
unames: {
$function: {
body: "function (arg, arg2) { if (!arg2) arg2 = []; return [...arg2,...arg.map((s) => s.uname)];}",
args: ["$logins", "$unames"],
lang: "js",
},
},
},
},
{
$unwind:
{
path: "$unames",
},
},
{
$graphLookup:
{
from: "notifications",
startWith: "$unames",
connectFromField: "unames",
connectToField: "uname",
as: "notif",
},
},
{
$project:
{
notif: 1,
},
},
{
$unwind:
{
path: "$notif",
},
},
{
$replaceRoot:
{
newRoot: "$notif",
},
},
]
return pipeline
}
export { userNotif, roomNotif, allNotif, groupNotif }

74
src/pipelines/vote.ts Normal file
View File

@@ -0,0 +1,74 @@
import { PipelineStage, Types } from "mongoose";
function vote(date: Date, userId: Types.ObjectId) {
var pipeline: PipelineStage[] = [
{
'$match': {
'day': date
}
}, {
'$lookup': {
'from': 'votes',
'localField': 'day',
'foreignField': 'dom',
'as': 'result',
'pipeline': [
{
'$match': {
'tom': 'ob',
'user': new Types.ObjectId(userId)
}
}, {
'$project': {
'_id': 0,
'vote': 1
}
}
]
}
}, {
'$unwind': {
'path': '$result',
'preserveNullAndEmptyArrays': true
}
}, {
'$set': {
'obv': '$result.vote'
}
}, {
'$lookup': {
'from': 'votes',
'localField': 'day',
'foreignField': 'dom',
'as': 'result',
'pipeline': [
{
'$match': {
'tom': 'kol',
'user': new Types.ObjectId(userId)
}
}, {
'$project': {
'_id': 0,
'vote': 1
}
}
]
}
}, {
'$unwind': {
'path': '$result',
'preserveNullAndEmptyArrays': true
}
}, {
'$set': {
'kolv': '$result.vote'
}
}, {
'$unset': 'result'
}
]
return pipeline
}
export { vote }

View File

@@ -0,0 +1,83 @@
import User from "@schemas/User";
import { Router } from "express"
import { Perms, adminCond, adminPerm } from "@/utility";
const accsRouter = Router()
accsRouter.use(adminPerm(Perms.Accs))
accsRouter.get('/', async (req, res)=> {
if (req.user.admin) {
res.send(await User.find({"uname": {"$ne": req.user.uname}}, {pass: 0}))
return
}
res.send(await User.find({"uname": {"$ne": req.user.uname}}, {pass: 0, admin: 0}))
})
accsRouter.post('/', async (req, res)=> {
if (req.body.uname == "admin") return res.status(400).send("This name is reserved").end()
if (req.body.flags) {
if (adminCond(req.user.admin, Perms.Superadmin)) {
if (adminCond(req.body.flags, Perms.Superadmin)) {
res.status(400).send("Cannot set superadmin")
} else {
await User.create({uname: req.body.uname, room: req.body.room, admin: req.body.flags, fname: req.body.fname, surname: req.body.surname})
res.status(201).send({status: 201})
}
}
} else {
await User.create({uname: req.body.uname, room: req.body.room, fname: req.body.fname, surname: req.body.surname})
res.status(201).send({status: 201})
}
})
accsRouter.put('/:id', async (req, res)=> {
let user = await User.findById(req.params.id)
if (!user) {
res.status(404).send("User not found")
return
}
if (req.body.flags != undefined) {
if (adminCond(req.user.admin, Perms.Superadmin)) {
if (adminCond(user.admin, Perms.Superadmin)) {
res.status(400).send("Cannot edit other superadmins")
} else {
if (adminCond(req.body.flags, Perms.Superadmin)) {
res.status(400).send("Cannot set superadmin")
} else {
await user.set({uname: req.body.uname, room: req.body.room, admin: req.body.flags, fname: req.body.fname, surname: req.body.surname}).save()
res.send({status: 200})
}
}
} else {
res.sendStatus(403)
}
} else {
await user.set(req.body).save()
res.send({status: 200})
}
})
accsRouter.patch('/:id/reset', async (req, res) => {
let user = await User.findById(req.params.id)
if (!user) {
res.status(404).send("User not found")
return
}
if (await user.set({pass: "$2y$10$miwF6PrsbLpRzFsj8XKjY.0flJWzWDQJ7iT81HuX1ic/1s0mfmvk."}).save()) { // Pass: reset
res.send({status: 200}).end()
return
} else {
res.sendStatus(500)
}
})
accsRouter.delete('/:id', async (req, res) => {
if (await User.findByIdAndDelete(req.params.id)) {
res.send({status: 200}).end()
} else {
res.sendStatus(404)
}
})
export {accsRouter};

View File

@@ -0,0 +1,71 @@
import { Router } from "express";
import { Perms, adminPerm } from "@/utility";
import capability, { Features } from "@/capability";
import usettings from "@/usettings";
import Grade from "@schemas/Grade";
const cleanRouter = Router()
cleanRouter.use(adminPerm(Perms.Clean))
cleanRouter.use(capability.mw(Features.Clean))
cleanRouter.get("/:date/:room", async (req, res) => {
res.send(await Grade.findOne({
date: new Date(req.params.date),
room: req.params.room
}))
})
cleanRouter.post("/", async (req, res) => {
let obj = {
...req.body,
date: new Date(req.body.date),
gradeDate: new Date(),
}
await Grade.findOneAndReplace({
date: new Date(req.body.date),
room: req.body.room,
}, obj, {upsert: true})
res.send({status: 200})
})
cleanRouter.get("/summary/:start/:stop", async (req, res) => {
var data = await Grade.find({
date: {
$gte: new Date(req.params.start),
$lte: new Date(req.params.stop)
}
})
data = data.map(v => v.toJSON())
var byRoom: {[room: number]: any[]} = {}
data.forEach((v) => {
let roomarray = byRoom[v.room] ? byRoom[v.room] : [];
byRoom[v.room] = [...roomarray, {...v, room: undefined}]
})
var stat: {room: number, avg: number}[] = []
for (let i in byRoom) {
var sum: number = 0
for (let j of byRoom[i]) {
sum += j.grade
}
let avrg = sum/byRoom[i].length
stat.push({room: Number.parseInt(i), avg: avrg})
}
res.send(stat)
})
cleanRouter.delete("/:id", async (req, res) => {
if (await Grade.findByIdAndDelete(req.params.id)) {
res.send({status: 200})
} else {
res.sendStatus(500)
}
})
cleanRouter.get('/config', (req, res) => {
res.send({
rooms: usettings.settings.rooms,
things: usettings.settings.cleanThings
})
})
export {cleanRouter}

View File

@@ -0,0 +1,16 @@
import { Router } from "express";
import Menu from "@schemas/Menu";
const editorRouter = Router()
editorRouter.get('/', async (req, res) => {
if (req.query.start && req.query.end) {
const start = new Date(req.query.start.toString())
const end = new Date(req.query.end.toString())
res.send(await Menu.find({day: {$gte: start, $lte: end}}))
} else {
res.status(400).end()
}
})
export { editorRouter }

View File

@@ -0,0 +1,42 @@
import Group from "@schemas/Group";
import { Router } from "express"
import { Perms, adminPerm } from "@/utility";
import capability, { Features } from "@/capability";
const groupsRouter = Router()
groupsRouter.use(adminPerm(Perms.Groups))
groupsRouter.use(capability.mw(Features.Groups))
groupsRouter.get('/', async (req, res)=> {
res.send(await Group.find({}))
})
groupsRouter.post('/', async (req, res)=> {
if (await Group.create({name: req.body.name})) {
res.status(201).send({status: 201})
} else {
res.sendStatus(500)
}
})
groupsRouter.put('/:id', async (req, res) => {
let group = await Group.findById(req.params.id)
if (!group) {
res.status(404).send("Group not found")
return
}
if (await group.set(req.body).save()) {
res.send({status: 200}).end()
return
} else {
res.sendStatus(500)
}
})
groupsRouter.delete('/:id', async (req, res) => {
await Group.findByIdAndRemove(req.params.id)
res.send({status: 200})
})
export {groupsRouter};

View File

@@ -0,0 +1,52 @@
import { Router } from "express";
import capability, { Features } from "@/capability";
import Key from "@schemas/Key";
import usettings from "@/usettings";
import User from "@schemas/User";
import { Perms, adminPerm } from "@/utility";
const keysRouter = Router()
keysRouter.use(capability.mw(Features.Key))
keysRouter.use(adminPerm(Perms.Key))
keysRouter.get("/", async (req, res) => {
var keys = await Key.find({}, {}, {sort: {borrow: -1}}).populate("whom", {uname: 1, _id: 1, room: 1})
res.send(keys)
})
keysRouter.post("/", async (req, res) => {
var newKey: {
room: string;
whom: string;
} = req.body
var user = await User.findOne({uname: newKey.whom})
if (user) {
newKey.whom = user._id.toString()
} else {
return res.status(404).send("User not found").end()
}
if (await Key.create(newKey)) {
res.status(201).send({status: 201})
} else {
res.sendStatus(500)
}
})
keysRouter.get("/available", async (req, res) => {
var taken = await Key.find({tb: {$exists: false}}, {}, {sort: {borrow: -1}})
var occ = Array.from(new Set(taken.map((v) => v.room)))
var all = Array.from(new Set(usettings.settings.keyrooms))
var free = all.filter(x => !occ.includes(x))
res.send(free)
})
keysRouter.put("/:id", async (req, res) => {
if (await Key.findByIdAndUpdate(req.params.id, req.body)) {
res.send({status: 200})
} else {
res.sendStatus(500)
}
})
export { keysRouter }

View File

@@ -0,0 +1,204 @@
import { Router } from "express"
import { Perms, adminPerm, project } from "@/utility"
import multer from "multer"
import * as XLSX from "xlsx"
import Menu from "@schemas/Menu"
import Vote from "@schemas/Vote"
import capability, { Features } from "@/capability"
import { editorRouter } from "./editor"
const menuRouter = Router()
const storage = multer.memoryStorage()
const upload = multer({storage: storage})
interface sheetObject {
day: string;
sn: string;
sn2: string;
ob: string;
kol: string;
}
menuRouter.use(adminPerm(Perms.Menu))
menuRouter.use(capability.mw(Features.Menu))
menuRouter.get('/', async (req, res) => {
if (req.query.start && req.query.end) {
const start = new Date(req.query.start.toString())
const end = new Date(req.query.end.toString())
res.send(await Menu.find({day: {$gte: start, $lte: end}}, undefined, {sort: {day: 1}}))
} else {
res.status(400).end()
}
})
function dayName(date: Date) {
switch (date.getDay()) {
case 0:
return "Niedziela"
case 1:
return "Poniedziałek"
case 2:
return "Wtorek"
case 3:
return "Środa"
case 4:
return "Czwartek"
case 5:
return "Piątek"
case 6:
return "Sobota"
default:
break;
}
}
menuRouter.get('/print', async (req, res) => {
if (req.query.start && req.query.end) {
const start = new Date(req.query.start.toString())
const end = new Date(req.query.end.toString())
var meals = await Menu.find({day: {$gte: start, $lte: end}}, undefined, {sort: {day: 1}})
var doc = meals.map(s => `<tr>
<th>${dayName(s.day)}<br>${s.day.getDate()}.${s.day.getMonth()}.${s.day.getFullYear()}r.<br>${s.dayTitle}</th>
<td>${s.sn.fancy.join('<br>')}<br>${s.sn.second}</td>
<td>
Z: ${s.ob.soup}<br>
V: ${s.ob.vege}<br>
${s.ob.meal}<br>
${s.ob.condiments.length != 0 ? s.ob.condiments.join('<br>') + "<br>" : ""}
${s.ob.drink}<br>
${s.ob.other.join('<br>')}
</td>
<td>${s.day.getUTCDay() == 5 ? "<b>Kolacja w domu!</b>" : s.kol}</td>
</tr>`)
var html = `<html><head><meta charset="UTF-8"><style>table,th,td{border: 1px solid;}td{line-height: 1.5;}</style></head><body><table><caption>Jadłospis dekadowy</caption><thead><tr><th>Dzień</th><th>Śniadanie</th><th>Obiad</th><th>Kolacja</th></tr></thead><tbody>${doc.join('\n')}</tbody></table></body></html>`
res.type('html').send(html)
} else {
res.status(400).end()
}
})
menuRouter.get('/opts', async (req, res) => {
var all = await Menu.find()
var g = {
sn: {
fancy: Array.from(new Set(all.flatMap(v => v.sn.fancy).filter(v => v != ""))),
second: Array.from(new Set(all.map(v => v.sn.second).filter(v => v != "")))
},
ob: {
soup: Array.from(new Set(all.map(v => v.ob.soup).filter(v => v != ""))),
vege: Array.from(new Set(all.map(v => v.ob.vege).filter(v => v != ""))),
meal: Array.from(new Set(all.map(v => v.ob.meal).filter(v => v != ""))),
condiments: Array.from(new Set(all.flatMap(v => v.ob.condiments).filter(v => v != ""))),
drink: Array.from(new Set(all.map(v => v.ob.drink).filter(v => v != ""))),
other: Array.from(new Set(all.flatMap(v => v.ob.other).filter(v => v != "")))
},
kol: Array.from(new Set(all.map(v => v.kol).filter(v => v != "")))
}
res.send(g)
})
menuRouter.post('/:date', async (req, res) => {
if (await Menu.create({day: new Date(req.params.date)})) {
res.status(201).send({status: 201})
} else {
res.sendStatus(500);
}
})
menuRouter.post('/:start/:count', async (req, res) => {
var dates: any[] = []
for (let i = 0; i < Number(req.params.count); i++) {
var date = new Date(req.params.start)
dates.push({day: date.setDate(date.getDate() + i)})
}
if (await Menu.create(dates)) {
res.status(201).send({status: 201})
} else {
res.sendStatus(500);
}
})
menuRouter.post('/upload', upload.single('menu'), async (req,res)=> {
if (!req.file) {
res.status(400).send("File required")
return
}
var sheet = XLSX.read(req.file.buffer)
var data: sheetObject[] = XLSX.utils.sheet_to_json(sheet.Sheets[sheet.SheetNames[0]], {raw: true, header: ["day", "sn", "sn2", "ob", "kol"], range: 2})
data = data.map((val, i) => {
var result: any = {}
var dateparts = val.day.match(/(\d{2})\.(\d{2})\.(\d{4})/)
if (dateparts) {
var date = new Date(parseInt(dateparts[3]),parseInt(dateparts[2])-1,parseInt(dateparts[1]))
date.setUTCHours(0,0,0,0)
} else {
res.sendStatus(500)
return
}
result.day = date
result.sn = val.sn.split('\n')
result.sn.push(val.sn2)
//#region ob
var ob = val.ob
ob = ob.replace(/^\s*\n/gm, "")
ob = ob.replace(/ \/ /gm, "\n")
ob = ob.replace(/:(?!\s)/gm, ": ")
result.ob = ob.split('\n')
//#endregion
result.kol = val.kol
if (date.getUTCDay() == 5) {
result.kol = null
}
return result
})
if (await Menu.insertMany(data)) {
res.status(201).send({status: 201})
} else {
res.sendStatus(500)
}
})
menuRouter.put('/:id', async (req, res) => {
let menu = await Menu.findById(req.params.id)
if (!menu) {
res.status(404).send("Menu not found")
return
}
let projField = project(req.body, Menu.schema.obj)
if (projField) {
try {
await menu.set(projField).save()
res.send({status: 200}).end()
} catch (error) {
res.status(500).send(error)
}
} else {
res.status(400).send("No valid fields set")
return
}
})
menuRouter.get('/:id/votes/:m', async (req, res) => {
let votes = await Vote.find({dom: new Date(req.params.id)})
if (!votes) {
res.end()
return
}
var fvotes = votes.filter(i => i.tom == req.params.m)
var ycount = fvotes.filter(i => i.vote == "+").length
var ncount = fvotes.filter(i => i.vote == "-").length
res.send({
y: ycount,
n: ncount,
})
})
menuRouter.use('/editor', editorRouter)
export {menuRouter};

View File

@@ -0,0 +1,27 @@
import { Router } from "express";
import News from "@schemas/News"
import { Perms, adminPerm } from "@/utility";
import capability, { Features } from "@/capability";
const newsRouter = Router()
newsRouter.use(adminPerm(Perms.News))
newsRouter.use(capability.mw(Features.News))
newsRouter.get('/', async (req,res)=>{
res.send(await News.find({},null,{sort: {pinned: -1 ,date: -1}}))
})
newsRouter.post('/', async (req,res)=>{
await News.create({title: req.body.title, content: req.body.content})
res.status(201).send({status: 201})
})
newsRouter.delete('/:id', async (req,res)=>{
await News.findByIdAndDelete(req.params.id)
res.send({status: 200})
})
newsRouter.put('/:id', async (req,res)=>{
await News.findByIdAndUpdate(req.params.id, req.body)
res.send({status: 200})
})
export {newsRouter};

View File

@@ -0,0 +1,54 @@
import { Router } from "express";
import { Perms, adminPerm } from "@/utility";
import Group from "@schemas/Group";
import { NotifcationHelper } from "@/notif";
import capability, { Features } from "@/capability";
const notifRouter = Router()
const nh = new NotifcationHelper()
notifRouter.use(adminPerm(Perms.Notif))
notifRouter.use(capability.mw(Features.Notif))
notifRouter.post("/send", async (req, res) => {
const message = nh.simpleMessage(req.body.title, req.body.body)
let recp: string | number
let result;
switch (req.body.recp.type) {
case "uname":
recp = req.body.recp.uname as string
result = await message.user(recp);
break;
case "room":
recp = req.body.recp.room as number
result = await message.room(recp)
break;
case "all":
recp = "all"
result = await message.withRoom()
break;
case "group":
if (!capability.settings.groups) return res.sendStatus(406).end()
recp = req.body.recp.group as string
result = await message.group(recp)
break;
default:
res.status(400).end()
break;
}
console.log(`
From: ${req.user.uname} (${req.user._id})
To: ${recp}
Subject: ${req.body.title}
${req.body.body}
`);
res.send(result)
})
notifRouter.get("/groups", async (req,res) => {
res.send(await Group.find({}, {name: 1, _id: 1}))
})
export {notifRouter}

View File

@@ -0,0 +1,21 @@
import { Router } from "express";
import { adminPerm, Perms, project } from "@/utility";
import usettings from "@/usettings";
export const settingsRouter = Router()
settingsRouter.use(adminPerm(Perms.Superadmin))
settingsRouter.get('/', (req, res) => {
res.send(usettings.settings)
})
settingsRouter.post('/', (req, res) => {
usettings.settings = project(req.body, {keyrooms: true, cleanThings: true, rooms: true})
res.send({status: 200})
})
settingsRouter.get('/reload', (req, res) => {
usettings.reload()
res.send({status: 200})
})

View File

@@ -0,0 +1,29 @@
import { Router } from "express";
import { islogged, isadmin} from "@/utility";
import { newsRouter } from "./admin/news";
import { accsRouter } from "./admin/accs";
import { menuRouter } from "./admin/menu";
import { groupsRouter } from "./admin/groups";
import { notifRouter } from "./admin/notif";
import { keysRouter } from "./admin/keys";
import { cleanRouter } from "./admin/clean";
import { settingsRouter } from "./admin/settings";
const adminRouter = Router()
adminRouter.use(islogged, isadmin)
adminRouter.use('/news', newsRouter)
adminRouter.use('/accs', accsRouter)
adminRouter.use('/menu', menuRouter)
adminRouter.use('/groups', groupsRouter)
adminRouter.use('/notif', notifRouter)
adminRouter.use('/keys', keysRouter)
adminRouter.use('/clean', cleanRouter)
adminRouter.use('/settings', settingsRouter)
adminRouter.get('/usearch', (req, res) => {
// TODO: Add search
res.send([req.query['q']])
})
export {adminRouter};

View File

@@ -0,0 +1,78 @@
import { Router } from "express";
import { islogged } from "@/utility";
import News from "@schemas/News";
import Menu from "@schemas/Menu";
import Vote from "@schemas/Vote";
import { vote } from "@/pipelines/vote";
import capability, { Features } from "@/capability";
import Key from "@schemas/Key";
import usettings from "@/usettings";
import Grade from "@schemas/Grade";
import { createHash } from "node:crypto";
const appRouter = Router();
appRouter.use(islogged)
appRouter.get("/news", capability.mw(Features.News), async (req, res) => {
var news = await News.find({"visible": {"$ne": false}}, {_id: 0, visible: 0}, {sort: {pinned: -1 ,date: -1}})
res.send(news)
})
appRouter.get("/news/check", capability.mw(Features.News), async (req, res) => {
var news = await News.find({"visible": {"$ne": false}}, {_id: 0, visible: 0}, {sort: {pinned: -1 ,date: -1}})
const hash = createHash('sha1')
var newsha = hash.update(news.toString()).digest('hex');
var check: { hash: string; count: number; } = {hash: newsha, count: news.length}
res.send(check)
})
appRouter.get("/menu/:timestamp", capability.mw(Features.Menu), async (req, res) => {
var item = await Menu.aggregate(vote(new Date(Number.parseInt(req.params.timestamp)),req.user!._id))
var votes = await Vote.find({dom: new Date(Number.parseInt(req.params.timestamp))})
var grouped = votes.reduce((x, y) => {
x[y.tom].push(y)
return x
}, {ob: [], kol: []})
var count = {
ob: (grouped.ob.filter(v=>v.vote == "+").length / grouped.ob.length * 100).toFixed(2),
kol: (grouped.kol.filter(v=>v.vote == "+").length / grouped.kol.length * 100).toFixed(2)
}
var final = {
...item[0],
stat: count
}
res.send(final)
})
appRouter.post("/menu/:timestamp", capability.mw(Features.Menu), async (req, res) => {
const vote = await Vote.findOneAndUpdate({user: req.user._id, dom: new Date(req.params.timestamp), tom: req.body.tom}, {
...req.body,
user: req.user._id,
dom: new Date(req.params.timestamp),
}, {upsert: true, new: true})
if (vote) {
res.send({status: 200})
} else {
res.sendStatus(500)
}
})
appRouter.get("/keys", capability.mw(Features.Key), async (req, res) => {
var keys = (await Key.find({tb: {$exists: false}}, {_id: 0, room: 1, whom: 0}, {sort: {room: 1}}))
var occ = keys.map(x=>x.room)
var all = usettings.settings.keyrooms
var free = all.filter(x=>!occ.includes(x)).sort().map(x => {
return { room: x }
})
var final = [...keys, ...free]
res.send(final)
})
appRouter.get("/clean/:date", capability.mw(Features.Clean), async (req, res) => {
res.send(await Grade.findOne({
room: req.user.room,
date: new Date(req.params.date)
}))
})
export {appRouter};

58
src/routes/auth/index.ts Normal file
View File

@@ -0,0 +1,58 @@
import { Router } from "express";
import passport from "passport";
import User from "@schemas/User";
import { islogged } from "@/utility";
import bcrypt from "bcryptjs"
import cap from "@/capability";
import usettings from "@/usettings";
const authRouter = Router()
authRouter.post("/login", passport.authenticate('normal'), (req, res) => {
if (req.user.admin != null) res.send({status: 200, admin: req.user.admin})
else res.send({status: 200})
})
authRouter.post("/chpass", islogged, async (req,res) => {
var id = req.user._id
if (!await bcrypt.compare(req.body.oldPass, req.user.pass)) {
res.sendStatus(401)
return
}
var newpass = bcrypt.hashSync(req.body.newPass, 10)
const update = await User.findByIdAndUpdate(id, {
pass: newpass
})
if (update) {
} else {
}
req.logOut((err) => {
if (err) {
res.sendStatus(500)
console.error(err)
return
}
})
res.sendStatus(200)
})
authRouter.delete("/logout", (req, res, next) => {
req.logout((err) => {
if (err) {next(err)}
res.send({"status": 200})
})
})
authRouter.get("/check", islogged, (req, res, next) => {
if (req.user.locked) {
req.logout((err) => {
if (err) next(err)
res.status(401).send("Your account has been locked.")
})
}
res.send({"admin": req.user.admin, "features": cap.flags, "room": req.user.room, "menu": {"defaultItems": usettings.settings.menu.defaultItems}})
})
export { authRouter };

21
src/routes/index.ts Normal file
View File

@@ -0,0 +1,21 @@
import { Router } from "express";
import Notification from "@schemas/Notification";
import { islogged } from "@/utility";
import { adminRouter } from "./api/adminRouter";
import { appRouter } from "./api/appRouter";
import { authRouter } from "./auth/index";
import capability, { Features } from "@/capability";
const router = Router();
router.use('/app', appRouter)
router.use('/admin', adminRouter)
router.use('/auth', authRouter)
router.post("/notif", islogged, capability.mw(Features.Notif), async (req, res) => {
var obj = {uname: req.user.uname, ...req.body}
await Notification.findOneAndUpdate(obj, obj, {upsert: true})
res.send({"status": 200})
})
export default router;

26
src/schemas/Grade.ts Normal file
View File

@@ -0,0 +1,26 @@
import { ObjectId, Schema, model } from "mongoose"
export interface GradeNote {
label: string;
weight: number;
}
interface IGrade {
grade?: number;
date: Date;
gradeDate?: Date;
room: number;
notes?: GradeNote[];
tips: string;
}
const gradeSchema = new Schema<IGrade>({
grade: Number,
date: {type: Date, required: true},
gradeDate: Date,
room: {type: Number, required: true},
notes: [Object],
tips: String,
})
export default model("grade", gradeSchema)

15
src/schemas/Group.ts Normal file
View File

@@ -0,0 +1,15 @@
import { ObjectId, Schema, model } from "mongoose"
interface IGroup {
name: string;
rooms?: number[];
unames?: string[];
}
const groupSchema = new Schema<IGroup>({
name: {type: String, required: true},
rooms: [Schema.Types.Number],
unames: [Schema.Types.String]
})
export default model("group", groupSchema)

17
src/schemas/Key.ts Normal file
View File

@@ -0,0 +1,17 @@
import { ObjectId, Schema, model } from "mongoose"
interface IKey {
room: string;
whom: ObjectId;
borrow: Date;
tb?: Date;
}
const keySchema = new Schema<IKey>({
room: {type: String, required: true},
whom: {type: Schema.Types.ObjectId, ref: "logins", required: true},
borrow: {type: Date, default: Date.now, required: true},
tb: {type: Date}
})
export default model("key", keySchema)

39
src/schemas/Menu.ts Normal file
View File

@@ -0,0 +1,39 @@
import mongoose, { Schema } from "mongoose"
interface IMenu {
sn: {
fancy: string[];
second: string;
};
ob: {
soup: string;
vege: string;
meal: string;
condiments: string[];
drink: string;
other: string[];
};
kol: string;
day: Date;
dayTitle?: string;
}
const menuSchema = new Schema<IMenu>({
sn: {
fancy: {type: [String]},
second: {type: String, default: ""}
},
ob: {
soup: {type: String, default: ""},
vege: {type: String, default: ""},
meal: {type: String, default: ""},
condiments: {type: [String]},
drink: {type: String, default: ""},
other: {type: [String]},
},
kol: {type: String, default: ""},
day: {type: Date, required: true},
dayTitle: {type: String, default: ""}
})
export default mongoose.model("menu", menuSchema, "menu")

19
src/schemas/News.ts Normal file
View File

@@ -0,0 +1,19 @@
import mongoose, { Schema } from "mongoose"
interface INews {
content: string;
title: string;
date: Date;
visible?: boolean;
pinned?: boolean
}
const newsSchema = new Schema<INews>({
content: {type: String, required: true},
title: {type: String, required: true},
date: {type: Date, requred: true, default: Date.now},
visible: {type: Boolean, default: false},
pinned: {type: Boolean, default: false}
})
export default mongoose.model("news", newsSchema)

View File

@@ -0,0 +1,23 @@
import mongoose, { Schema } from "mongoose"
interface INotification {
endpoint: string;
keys: {
auth: string;
p256dh: string;
};
uname: string
expirationTime?: number
}
const notifSchema = new Schema<INotification>({
endpoint: {type: String, required: true},
keys: {
auth: String,
p256dh: String,
},
uname: {type: String, required: true},
expirationTime: Number
})
export default mongoose.model("Notification", notifSchema)

25
src/schemas/User.ts Normal file
View File

@@ -0,0 +1,25 @@
import mongoose, { Schema } from "mongoose"
// TODO: Unify `fname` and `surename` into single field
interface IUser {
uname: string;
pass: string;
room?: number;
admin?: number;
locked?: boolean;
fname?: string;
surname?: string;
}
const userSchema = new Schema<IUser>({
uname: {type: String, required: true},
pass: {type: String, required: true, default: "$2y$10$wxDhf.XiXkmdKrFqYUEa0.F4Bf.pDykZaMmgjvyLyeRP3E/Xy0hbC"},
room: Number,
admin: Number,
locked: {type: Boolean, default: false},
fname: String,
surname: String
})
export default mongoose.model("logins", userSchema)

19
src/schemas/Vote.ts Normal file
View File

@@ -0,0 +1,19 @@
import mongoose, { Schema } from "mongoose";
interface IVote {
doc: Date;
user: mongoose.Types.ObjectId;
dom: Date;
tom: "ob" | "kol";
vote: "-" | "+" | "n";
}
const voteSchema = new Schema<IVote>({
doc: {type: Date, required: true},
user: {type: mongoose.Schema.Types.ObjectId, required: true},
dom: {type: Date, required: true},
tom: {type: String, required: true},
vote: {type: String, required: true},
})
export default mongoose.model("vote", voteSchema)

38
src/usettings.ts Normal file
View File

@@ -0,0 +1,38 @@
import { readFileSync, writeFileSync } from "node:fs";
interface IUSettings {
keyrooms: string[];
rooms: number[];
cleanThings: string[];
menu: {
defaultItems: {
sn: string[];
kol: string[];
}
}
}
class UOptions {
private _settings: IUSettings;
public get settings(): IUSettings {
return this._settings;
}
public set settings(value: IUSettings) {
this._settings = value;
this.save()
}
constructor() {
this.reload()
}
private save() {
writeFileSync("./config/usettings.json", JSON.stringify(this.settings, undefined, 2))
}
reload() {
this.settings = JSON.parse(readFileSync("./config/usettings.json", {encoding: "utf-8"}))
console.log("Reloaded user settings");
}
}
export default new UOptions();

49
src/utility.ts Normal file
View File

@@ -0,0 +1,49 @@
import { NextFunction, Request, Response } from "express"
var islogged = (req: Request, res: Response, next: NextFunction) => {
if (req.isAuthenticated()) {
return next()
}
res.sendStatus(401)
}
var isadmin = (req: Request, res: Response, next: NextFunction) => {
if (req.user.admin != null) {
return next()
}
res.sendStatus(401)
}
enum Perms {
News = 1,
Menu = 2,
Notif = 4,
Groups = 8,
Accs = 16,
Superadmin = 32,
Key = 64,
Clean = 128,
}
var adminPerm = (perm: Perms) => {
return (req: Request, res: Response, next: NextFunction) => {
if (adminCond(req.user.admin, perm)) {
return next()
}
res.sendStatus(401)
}
}
var adminCond = (adminInt = 0, perm: Perms) => {
return (adminInt & perm) == perm
}
var project = (obj: any, projection: any) => {
let obj2: any = {}
for (let key in projection) {
if (key in obj) obj2[key] = obj[key]
}
return obj2
}
export {islogged, isadmin, adminPerm, Perms, adminCond, project};