25 Commits

Author SHA1 Message Date
453ff9094f fix: changed dateselector and filter logic 2025-06-14 20:03:25 +02:00
8fc171b874 fix: News now display author 2025-06-13 16:07:11 +02:00
9e420e548e fix: Own account 2025-06-13 15:11:17 +02:00
2db19ee1e7 fix: Remade perms 2025-06-13 14:55:52 +02:00
3ba7460eee fix: split groups 2025-06-13 12:24:42 +02:00
681881097b fix: post now sends created user object in response 2025-06-12 12:04:36 +02:00
4d4c3993d9 feat: luxon related 2025-06-09 21:53:08 +02:00
e8b4e4634f chore: version numbers 2025-06-09 14:22:29 +02:00
647bc1c2ba fix: Made class abstract 2025-06-09 12:59:13 +02:00
aac85e3679 fix: Added a check for missing config files. Added FileHandler class. 2025-06-06 16:43:48 +02:00
93183799af v1.1.1 2025-06-06 10:07:38 +02:00
b299963570 Merge pull request #4 from Slasherss1/1.1.0
v1.1.0
2025-06-03 13:31:08 +02:00
5b87634813 chore: Bumped version numbers 2025-06-03 13:26:24 +02:00
b7c84fbe14 feat: Added unchecked room highlighting 2025-06-03 13:24:02 +02:00
d50aa79c5d feat: Added menu items and account security to settings 2025-06-01 21:48:49 +02:00
df745c78e2 feat: added user search to various components 2025-06-01 17:44:43 +02:00
ec24700b8a feat: Added user search component. 2025-06-01 13:54:54 +02:00
334402d8c5 feat: Added notification dialog on frontend 2025-05-31 19:56:38 +02:00
dd17fd5294 feat: Added notifications outbox to admin panel 2025-05-31 16:57:53 +02:00
ec787e2321 feat: Added a healthcheck to backend 2025-05-31 15:34:04 +02:00
4de7af4bc0 feat: Added redirect after login for users. 2025-05-24 11:27:12 +02:00
432b4dc4e5 fix: Redesigned user cards 2025-05-21 19:54:37 +02:00
92aaee9bcc fix: Removed redundant cors url 2025-05-20 20:57:41 +02:00
b708fe8c18 feat: Added brute force prevention. Closes #3 2025-05-16 00:39:55 +02:00
9efeba0010 fix: moved helpers to separate folder, added security to usettings (part of #3). 2025-05-15 15:58:44 +02:00
31 changed files with 682 additions and 297 deletions

5
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "backend2",
"version": "1.0.1",
"version": "1.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "backend2",
"version": "1.0.0",
"version": "1.2.0",
"license": "GPL-3.0-or-later",
"dependencies": {
"bcryptjs": "^2.4.3",
@@ -2499,6 +2499,7 @@
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.6.1.tgz",
"integrity": "sha512-tJLxrKJhO2ukZ5z0gyjY1zPh3Rh88Ej9P7jNrZiHMUXHae1yvI2imgOZtL1TO8TW6biMMKfTtAOoEJANgtWBMQ==",
"license": "MIT",
"engines": {
"node": ">=12"
}

View File

@@ -1,6 +1,6 @@
{
"name": "backend2",
"version": "1.0.1",
"version": "1.2.0",
"description": "",
"main": "src/index.js",
"type": "module",

View File

@@ -25,14 +25,14 @@ class Attendence {
this.attendence.delete(room)
}
getRoom (room: string) {
getRoom (room: string): IAttendence | undefined {
return this.attendence.get(room)
}
summary () {
var summary: {room: string, hours: string[], notes: string}[] = []
var summary: {room: string, hours: string[], notes: string, auto: boolean}[] = []
this.attendence.forEach((v, k) => {
summary.push({room: k, hours: v.auto.map(i => i.hour), notes: v.notes})
summary.push({room: k, hours: v.auto.map(i => i.hour), notes: v.notes, auto: false})
})
return summary
}

View File

@@ -37,8 +37,21 @@ class Settings {
}
public reloadSettings() {
try {
this.settings = JSON.parse(readFileSync('./config/options.json', 'utf-8'))
this.optionsToFlags()
} catch (error) {
if (error instanceof Error) {
if ('code' in error) {
if (error.code == "ENOENT") {
console.warn("WARNING: Capability file 'options.json' not found, enabling all modules.")
console.info("INFO: This warning will dissapear in future release of this program.")
this.settings = { clean: true, groups: true, key: true, menu: true, news: true, notif: true }
this.optionsToFlags()
}
}
}
}
}
public get flags() : number {

View File

@@ -0,0 +1,46 @@
import { PathOrFileDescriptor, readFileSync, writeFileSync } from "node:fs";
export abstract class FileHandler<T> {
protected _value: T
public get value(): T {
return this._value;
}
public set value(value: T) {
this._value = value
this.save()
}
constructor(public path: PathOrFileDescriptor, public settings?: {
defaultContent?: T,
name?: string
}) {
try {
this._value = JSON.parse(readFileSync(path, 'utf-8'))
console.log("Loaded user settings");
} catch (error) {
if (error instanceof Error) {
if ('code' in error) {
if (error.code === "ENOENT") {
writeFileSync(path, JSON.stringify(settings.defaultContent, undefined, 2))
console.log(`Created ${settings.name}`);
}
}
}
}
}
private save() {
writeFileSync(this.path, JSON.stringify(this.construct(this._value), undefined, 2))
}
public reload() {
this._value = JSON.parse(readFileSync(this.path, { encoding: "utf-8" }))
console.log(`Reloaded ${this.settings.name}`);
}
/**
* Method that makes sure that object is the interface.
* @param value Input object
*/
abstract construct(value: T | any): T
}

57
src/helpers/security.ts Normal file
View File

@@ -0,0 +1,57 @@
import { Job, scheduleJob } from "node-schedule";
import usettings from "./usettings";
import { Types } from "mongoose";
interface IAccTimeout {
firstAttempt: Date;
expire: Job;
attempts: number;
}
class SecurityHelper {
private timeouts = new Map<string, IAccTimeout>();
private onTimeout = new Map<string, Job>(); // key: user id, value: unlock date
constructor () { }
addAttempt (userId: Types.ObjectId) {
var uid = userId.toString()
if (this.timeouts.has(uid)) {
var t = this.timeouts.get(uid)
t.attempts += 1
if (t.attempts > usettings.value.security.loginTimeout.attempts) {
this.onTimeout.set(uid, scheduleJob(new Date(Date.now() + usettings.value.security.loginTimeout.lockout * 1000), () => {
this.onTimeout.get(uid).cancel()
this.onTimeout.delete(uid)
}))
} else {
this.timeouts.set(uid, t)
}
} else {
this.timeouts.set(uid, {
attempts: 1,
firstAttempt: new Date(),
expire: scheduleJob(new Date(Date.now() + usettings.value.security.loginTimeout.time * 1000), () => {
this.timeouts.get(uid).expire.cancel()
this.timeouts.delete(uid)
})
})
}
}
check(userId: Types.ObjectId) {
var timeout = this.onTimeout.get(userId.toString())
if (timeout) {
// @ts-ignore
return timeout.nextInvocation().toDate().valueOf() - Date.now().valueOf()
} else {
return false
}
}
clearAcc(userId: string) {
return this.onTimeout.delete(userId)
}
}
export default new SecurityHelper()

66
src/helpers/usettings.ts Normal file
View File

@@ -0,0 +1,66 @@
import { FileHandler } from "./filehandler";
export interface IUSettings {
keyrooms: string[];
rooms: string[];
cleanThings: string[];
menu: {
defaultItems: {
sn: string[];
kol: string[];
}
},
security: {
loginTimeout: {
attempts: number;
time: number;
lockout: number;
}
}
}
class UOptions extends FileHandler<IUSettings> {
construct(value: IUSettings | any): IUSettings {
return {
keyrooms: value.keyrooms ?? [],
rooms: value.rooms ?? [],
cleanThings: value.cleanThings ?? [],
menu: {
defaultItems: {
sn: value.menu.defaultItems.sn ?? [],
kol: value.menu.defaultItems.kol ?? []
}
},
security: {
loginTimeout: {
attempts: value.security.loginTimeout.attempts ?? 0,
time: value.security.loginTimeout.time ?? 0,
lockout: value.security.loginTimeout.lockout ?? 0
}
}
}
}
constructor() {
const defaultSettings: IUSettings = {
keyrooms: [],
rooms: [],
cleanThings: [],
menu: {
defaultItems: {
sn: [],
kol: [],
}
},
security: {
loginTimeout: {
attempts: 0,
time: 0,
lockout: 0
}
}
}
super("./config/usettings.json", {defaultContent: defaultSettings, name: "user settings"})
}
}
export default new UOptions();

View File

@@ -7,9 +7,10 @@ import session from "express-session";
import bcrypt from 'bcryptjs';
import MongoStore from "connect-mongo";
import mongoose from "mongoose"
import User from "./schemas/User";
import User, { IUser } from "./schemas/User";
import routes from "./routes/index";
import process from "node:process"
import security from "./helpers/security";
const connectionString = process.env.ATLAS_URI || "mongodb://mongodb:27017/ipwa";
if (!process.env.DOMAIN) {
@@ -19,13 +20,8 @@ if (!process.env.DOMAIN) {
declare global {
namespace Express {
export interface User {
export interface User extends IUser {
_id: mongoose.Types.ObjectId;
pass: string;
uname: string;
admin?: number;
locked?: boolean;
room?: string
}
}
}
@@ -35,7 +31,7 @@ var app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cors({
origin: ["http://localhost:4200", "http://localhost:3000", `https://${process.env.DOMAIN}`,],
origin: ["http://localhost:4200", `https://${process.env.DOMAIN}`,],
credentials: true
}))
app.use(session({
@@ -55,12 +51,20 @@ app.use(passport.session())
passport.use("normal", new LocalStrategy(async function verify(uname, pass, done) {
let query = await User.findOne({ uname: uname.toLowerCase() })
if (query) {
if (query.locked == true) return done(null, false)
if (query.locked == true) return done({ type: "locked", message: "Twoje konto jest zablokowane. Skontaktuj się z administratorem." }, false)
var timeout = security.check(query._id)
if (timeout) {
timeout = Math.ceil(timeout / 1000 / 60)
return done({ type: "timeout", message: `Zbyt wiele nieudanych prób logowania. Odczekaj ${timeout} minut lub skontaktuj się z administratorem.` }, false)
}
if (await bcrypt.compare(pass, query.pass)) {
return done(null, query)
} else done(null, false)
} else {
done(null, false)
security.addAttempt(query._id)
done({ type: "unf" }, false)
}
} else {
done({ type: "unf" }, false)
}
}))
//#endregion
@@ -78,13 +82,35 @@ passport.deserializeUser(async function(id, done) {
}
});
app.listen(8080, async () => {
var server = app.listen(8080, async () => {
await mongoose.connect(connectionString);
await dataMigration()
if (process.send) process.send("ready")
})
app.use('/', routes)
process.on('SIGINT', () => {
server.close()
mongoose.disconnect().then(() => process.exit(0), () => process.exit(1))
})
async function dataMigration() {
//#region User
var users = await User.find({ admin: { $type: "int" } }).lean()
users.forEach(async v => {
var oldFlags = v.admin as unknown as number
var newFlags: string[] | undefined = []
if ((oldFlags & 1) == 1) newFlags.push("news")
if ((oldFlags & 2) == 2) newFlags.push("menu")
if ((oldFlags & 4) == 4) newFlags.push("notif")
if ((oldFlags & 8) == 8) newFlags.push("groups")
if ((oldFlags & 16) == 16) newFlags.push("accs")
if ((oldFlags & 32) == 32) newFlags.push("super")
if ((oldFlags & 64) == 64) newFlags.push("keys")
if ((oldFlags & 128) == 128) newFlags.push("grades")
if (newFlags.length == 0) newFlags = undefined
await User.findByIdAndUpdate(v._id, { $set: { admin: newFlags } })
})
//#endregion
}

View File

@@ -1,11 +1,27 @@
import { PushSubscription, RequestOptions, VapidKeys, WebPushError, sendNotification } from "web-push";
import { RequestOptions, SendResult, VapidKeys, WebPushError, sendNotification } from "web-push";
import Notification from "./schemas/Notification";
import vapidKeys from "./vapidKeys";
import { IUser } from "./schemas/User";
import User, { IUser } from "./schemas/User";
import Inbox from "./schemas/Inbox";
import { Types } from "mongoose";
export class NotifcationHelper {
export interface SimpleMessage {
title: string;
body: string;
}
export interface PushResult {
sent: number;
possible: number;
}
export class Message {
private options: RequestOptions
constructor () {
private message: { notification: SimpleMessage }
private rcptType: "uid" | "room" | "group"
private rcpt: string
constructor (title: string, body: string, rcptType: "uid" | "room" | "group", rcpt: string) {
let keys: VapidKeys = vapidKeys.keys
this.options = {
vapidDetails: {
@@ -14,27 +30,66 @@ export class NotifcationHelper {
publicKey: keys.publicKey
}
}
this.message = { notification: { title: title, body: body } }
this.rcptType = rcptType
this.rcpt = rcpt
}
private async send(message: string, subscriptions: PushSubscription[]) {
async findUserNotif(uid: string) {
var notif = await Notification.find().populate<{user: Pick<IUser, 'uname'> & {_id: Types.ObjectId}}>('user', ['uname', '_id']).exec()
return notif.filter(val => val.user._id.toString() == uid)
}
async findRoomNotif(room: string) {
var notif = await Notification.find().populate<{user: Pick<IUser, 'room'> & {_id: Types.ObjectId}}>('user', ['room', '_id']).exec()
return notif.filter(val => val.user.room == room)
}
async findGroupNotif(groupId: string) {
var notif = await Notification.find().populate<{user: Pick<IUser, 'groups'> & {_id: Types.ObjectId}}>('user', ['groups', '_id']).exec()
return notif.filter(val => val.user.groups.find(x => x.toString() == groupId))
}
public async send(): Promise<PushResult> {
var subscriptions
var rcptIds: Types.ObjectId[]
switch (this.rcptType) {
case "uid":
subscriptions = await this.findUserNotif(this.rcpt)
rcptIds = [new Types.ObjectId(this.rcpt)]
break;
case "room":
subscriptions = await this.findRoomNotif(this.rcpt)
rcptIds = (await User.find({room: this.rcpt})).map(v => v._id)
break;
case "group":
subscriptions = await this.findGroupNotif(this.rcpt)
rcptIds = (await User.find({groups: this.rcpt})).map(v => v._id)
break;
default:
throw new Error(`Wrong recipient type used: ${this.rcptType}`);
}
await Inbox.create({message: this.message.notification, rcpt: rcptIds})
var count = 0;
var subslen = subscriptions.length
for (const v of subscriptions) {
var result
var result: SendResult
try {
result = await sendNotification(v, message, this.options)
result = await sendNotification(v, JSON.stringify(this.message), this.options)
count++
} catch (error) {
if (error instanceof WebPushError) {
switch (error.statusCode) {
case 410:
console.log("GONE")
await Notification.findOneAndDelete({endpoint: v.endpoint, keys: v.keys})
await Notification.findByIdAndRemove(v._id)
subslen--
break;
case 404:
console.warn("NOT FOUND", error.message)
await Notification.findOneAndDelete(v)
await Notification.findByIdAndRemove(v._id)
subslen--
break;
default:
@@ -44,39 +99,7 @@ export class NotifcationHelper {
}
}
}
return {sent: count, possible: subslen}
}
private rcpt(message: string) {
return {
user: async (uname: string) => {
return await this.send(message, await this.findUserNotif(uname))
},
room: async (room: string) => {
return await this.send(message, await this.findRoomNotif(room))
},
group: async (group: string) => {
return await this.send(message, await this.findGroupNotif(group))
}
}
}
simpleMessage(title: string, body: string) {
return this.rcpt(JSON.stringify({notification: {title: title, body: body}}))
}
async findUserNotif(uname: string): Promise<Array<any>> {
var notif = await Notification.find().populate<{user: Pick<IUser, 'uname'>}>('user', 'uname').exec()
return notif.filter(val => val.user.uname == uname)
}
async findRoomNotif(room: string): Promise<Array<any>> {
var notif = await Notification.find().populate<{user: Pick<IUser, 'room'>}>('user', 'room').exec()
return notif.filter(val => val.user.room == room)
}
async findGroupNotif(groupId: string): Promise<Array<any>> {
var notif = await Notification.find().populate<{user: Pick<IUser, 'groups'>}>('user', 'groups').exec()
return notif.filter(val => val.user.groups.find(x => x.toString() == groupId))
}
}

View File

@@ -1,36 +1,41 @@
import User from "@schemas/User";
import { Router } from "express"
import { Perms, adminCond, adminPerm } from "@/utility";
import capability from "@/capability";
import Group from "@/schemas/Group";
import security from "@/helpers/security";
import { Types } from "mongoose";
const accsRouter = Router()
accsRouter.use(adminPerm(Perms.Accs))
accsRouter.get('/', async (req, res)=> {
var data = {
users: await User.find({"uname": {"$ne": req.user.uname}}, {pass: 0}),
groups: capability.settings.groups ? await Group.find() : undefined
}
res.send(data)
res.send(await User.find(undefined, {pass: 0}))
})
accsRouter.get('/:id', async (req, res) => {
res.send({
...(await User.findById(req.params.id, {pass: 0})).toJSON(),
lockout: !!security.check(new Types.ObjectId(req.params.id))
})
})
accsRouter.post('/', async (req, res)=> {
if (req.body.uname == "admin") return res.status(400).send("This name is reserved").end()
if (req.body.flags) {
var createdUser
if (req.body.admin) {
if (adminCond(req.user.admin, Perms.Superadmin)) {
if (adminCond(req.body.flags, Perms.Superadmin)) {
if (adminCond(req.body.admin, 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})
createdUser = await User.create({uname: req.body.uname, room: req.body.room, admin: req.body.admin, fname: req.body.fname, surname: req.body.surname})
}
}
} 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})
createdUser = await User.create({uname: req.body.uname, room: req.body.room, fname: req.body.fname, surname: req.body.surname})
}
var responseCandidate = createdUser.toJSON()
delete responseCandidate.pass
res.status(201).send(responseCandidate)
})
accsRouter.put('/:id', async (req, res)=> {
@@ -39,15 +44,15 @@ accsRouter.put('/:id', async (req, res)=> {
res.status(404).send("User not found")
return
}
if (req.body.flags != undefined) {
if (req.body.admin) {
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)) {
if (adminCond(req.body.admin, 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, groups: req.body.groups}).save()
await user.set({uname: req.body.uname, room: req.body.room, admin: req.body.admin, fname: req.body.fname, surname: req.body.surname, groups: req.body.groups}).save()
res.send({status: 200})
}
}
@@ -82,4 +87,12 @@ accsRouter.delete('/:id', async (req, res) => {
}
})
accsRouter.delete('/:id/lockout', async (req, res) => {
if (security.clearAcc(req.params.id)) {
res.send({status: 200}).end()
} else {
res.sendStatus(400)
}
})
export {accsRouter};

View File

@@ -1,16 +1,16 @@
import { Router } from "express";
import { Perms, adminPerm } from "@/utility";
import capability, { Features } from "@/capability";
import usettings from "@/usettings";
import capability, { Features } from "@/helpers/capability";
import usettings from "@/helpers/usettings";
import Grade from "@schemas/Grade";
import User from "@/schemas/User";
import attendence from "@/attendence";
import attendence from "@/helpers/attendence";
const cleanRouter = Router()
cleanRouter.use(adminPerm(Perms.Clean))
cleanRouter.use(capability.mw(Features.Clean))
cleanRouter.get("/:date([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?([Zz]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)/:room", async (req, res) => {
cleanRouter.get("/:date([0-9]{4}-[0-9]{2}-[0-9]{2})/:room", async (req, res) => {
res.send(await Grade.findOne({
date: new Date(req.params.date),
room: req.params.room
@@ -65,8 +65,8 @@ cleanRouter.delete("/:id", async (req, res) => {
cleanRouter.get('/config', (req, res) => {
res.send({
rooms: usettings.settings.rooms,
things: usettings.settings.cleanThings
rooms: usettings.value.rooms,
things: usettings.value.cleanThings
})
})
@@ -88,7 +88,12 @@ cleanRouter.delete('/attendence/:room', async (req, res) => {
})
cleanRouter.get('/attendenceSummary', async (req, res) => {
res.send(attendence.summary())
var allRooms = usettings.value.rooms
var graded = (await Grade.find({date: new Date().setUTCHours(24,0,0,0)})).map(v => v.room)
var ungraded = allRooms.filter(x => !graded.includes(x))
var summary = attendence.summary()
var unchecked: typeof summary = ungraded.filter(x => !summary.map(v => v.room).includes(x)).map(v => ({room: v, hours: [] as string[], notes: "Nie sprawdzono", auto: true}))
res.send([...summary, ...unchecked])
})
export {cleanRouter}

View File

@@ -1,7 +1,7 @@
import Group from "@schemas/Group";
import { Router } from "express"
import { Perms, adminPerm } from "@/utility";
import capability, { Features } from "@/capability";
import capability, { Features } from "@/helpers/capability";
const groupsRouter = Router()

View File

@@ -0,0 +1,36 @@
import { Router } from "express";
import { islogged, isadmin} from "@/utility";
import { newsRouter } from "./news";
import { accsRouter } from "./accs";
import { menuRouter } from "./menu";
import { groupsRouter } from "./groups";
import { notifRouter } from "./notif";
import { keysRouter } from "./keys";
import { cleanRouter } from "./clean";
import { settingsRouter } from "./settings";
import User from "@/schemas/User";
import capability from "@/helpers/capability";
import Group from "@/schemas/Group";
export 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', async (req, res) => {
var results = await User.find({$text: {$search: req.query['q'].toString()}}, {uname: 1, surname: 1, fname: 1, room: 1})
res.send(results)
})
adminRouter.get('/sync', async (req, res) => {
res.send({
groups: capability.settings.groups ? await Group.find() : undefined
})
})

View File

@@ -1,7 +1,7 @@
import { Router } from "express";
import capability, { Features } from "@/capability";
import capability, { Features } from "@/helpers/capability";
import Key from "@schemas/Key";
import usettings from "@/usettings";
import usettings from "@/helpers/usettings";
import User, { IUser } from "@schemas/User";
import { Perms, adminPerm } from "@/utility";
@@ -16,17 +16,15 @@ keysRouter.get("/", async (req, res) => {
})
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 {
var user = await User.findById(req.body.whom._id)
if (!user) {
return res.status(404).send("User not found").end()
}
if (await Key.create(newKey)) {
const newKey = new Key({
room: req.body.room,
whom: user._id
})
if (await newKey.save()) {
res.status(201).send({status: 201})
} else {
res.sendStatus(500)
@@ -36,7 +34,7 @@ keysRouter.post("/", async (req, res) => {
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 all = Array.from(new Set(usettings.value.keyrooms))
var free = all.filter(x => !occ.includes(x))
res.send(free)
})

View File

@@ -4,9 +4,9 @@ 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 capability, { Features } from "@/helpers/capability"
import { editorRouter } from "./editor"
import usettings from "@/usettings"
import usettings from "@/helpers/usettings"
const menuRouter = Router()
@@ -62,7 +62,7 @@ menuRouter.get('/print', async (req, res) => {
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>${usettings.settings.menu.defaultItems.sn.join('<br>')}<br>${s.sn.fancy.join('<br>')}<br>${s.sn.second}</td>
<td>${usettings.value.menu.defaultItems.sn.join('<br>')}<br>${s.sn.fancy.join('<br>')}<br>${s.sn.second}</td>
<td>
<b>Z:</b> ${s.ob.soup}<br>
<b>V:</b> ${s.ob.vege}<br>
@@ -71,7 +71,7 @@ menuRouter.get('/print', async (req, res) => {
${s.ob.drink}<br>
${s.ob.other.join('<br>')}
</td>
<td>${s.day.getUTCDay() == 5 ? "<b>Kolacja w domu!</b>" : `${usettings.settings.menu.defaultItems.kol.join('<br>')}<br>${s.kol}`}</td>
<td>${s.day.getUTCDay() == 5 ? "<b>Kolacja w domu!</b>" : `${usettings.value.menu.defaultItems.kol.join('<br>')}<br>${s.kol}`}</td>
</tr>`)
var html = `<html><head><meta charset="UTF-8"><style>table,th,td{border: 0.4ch solid;}td{line-height: 1;}</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)

View File

@@ -1,7 +1,8 @@
import { Router } from "express";
import News from "@schemas/News"
import { Perms, adminPerm } from "@/utility";
import capability, { Features } from "@/capability";
import capability, { Features } from "@/helpers/capability";
import { IUser } from "@/schemas/User";
const newsRouter = Router()
@@ -9,10 +10,11 @@ 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}}))
var news = await News.find(undefined, undefined, { sort: { pinned: -1, date: -1 } }).populate<{ author: Pick<IUser, "fname" | "surname" | "uname"> }>("author", ["fname", "surname", "uname"])
res.send(news)
})
newsRouter.post('/', async (req, res) => {
await News.create({title: req.body.title, content: req.body.content})
await News.create({ title: req.body.title, content: req.body.content, author: req.user._id })
res.status(201).send({ status: 201 })
})
newsRouter.delete('/:id', async (req, res) => {
@@ -20,7 +22,7 @@ newsRouter.delete('/:id', async (req,res)=>{
res.send({ status: 200 })
})
newsRouter.put('/:id', async (req, res) => {
await News.findByIdAndUpdate(req.params.id, req.body)
await News.findByIdAndUpdate(req.params.id, { ...req.body, author: req.user._id })
res.send({ status: 200 })
})

View File

@@ -1,50 +0,0 @@
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
let result;
switch (req.body.recp.type) {
case "uname":
recp = req.body.recp.uname
result = await message.user(recp);
break;
case "room":
recp = req.body.recp.room
result = await message.room(recp)
break;
case "group":
if (!capability.settings.groups) return res.sendStatus(406).end()
recp = req.body.recp.group
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,56 @@
import { Request, Response, Router } from "express";
import { Perms, adminPerm } from "@/utility";
import Group from "@schemas/Group";
import { PushResult, Message } from "@/notif";
import capability, { Features } from "@/helpers/capability";
import { outboxRouter } from "./outbox";
const notifRouter = Router()
notifRouter.use(adminPerm(Perms.Notif))
notifRouter.use(capability.mw(Features.Notif))
type PushSendBody = {recp:
{type: "uid", uid: string} |
{type: "room", room: string} |
{type: "group", group: string},
title: string,
body: string
}
notifRouter.post("/send", async (req: Request<undefined, PushResult, PushSendBody>, res: Response<PushResult>) => {
let recp: string
switch (req.body.recp.type) {
case "uid":
recp = req.body.recp.uid
break;
case "room":
recp = req.body.recp.room
break;
case "group":
if (!capability.settings.groups) return res.sendStatus(406).end()
recp = req.body.recp.group
break;
default:
res.status(400).end()
break;
}
const message = new Message(req.body.title, req.body.body, req.body.recp.type, recp)
let result: PushResult = await message.send()
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 }))
})
notifRouter.use("/outbox", outboxRouter)
export { notifRouter }

View File

@@ -0,0 +1,35 @@
import Inbox from "@/schemas/Inbox";
import { IUser } from "@/schemas/User";
import { Response, Router } from "express";
export const outboxRouter = Router()
outboxRouter.get("/", async (req, res: Response) => {
var result = await Inbox.find({}, {message: 1, sentDate: 1}, {sort: {sentDate: -1}})
var final = result.map(v => {
return {
_id: v._id,
sentDate: v.sentDate,
title: v.message.title
}
})
res.send(final)
})
outboxRouter.get("/:id/message", async (req, res) => {
var msg = await Inbox.findById(req.params.id, {message: 1})
if (msg) {
res.send(msg.message.body)
} else {
res.status(404).send({message: "ERR: 404 Message id not found"})
}
})
outboxRouter.get("/:id/rcpts", async (req, res) => {
var msg = await Inbox.findById(req.params.id, {rcpt: 1}).populate<{rcpt: Pick<IUser, "uname" | "room" | "fname" | "surname">}>({path: "rcpt", select: ["uname", "room", "fname", "surname"]}).exec()
if (msg) {
res.send(msg.rcpt)
} else {
res.status(404).send({message: "ERR: 404 Message id not found"})
}
})

View File

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

View File

@@ -1,29 +0,0 @@
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

@@ -4,17 +4,20 @@ 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 capability, { Features } from "@/helpers/capability";
import Key, { IKey } from "@schemas/Key";
import usettings from "@/usettings";
import usettings from "@/helpers/usettings";
import Grade from "@schemas/Grade";
import { createHash } from "node:crypto";
const appRouter = Router();
import Inbox from "@/schemas/Inbox";
import { IUser } from "@/schemas/User";
export 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}})
var news = await News.find({"visible": {"$ne": false}}, {_id: 0, visible: 0}, {sort: {pinned: -1 ,date: -1}}).populate<{author: Pick<IUser, "fname" | "surname" | "uname">}>("author", ["fname", "surname", "uname"])
res.send(news)
})
@@ -26,9 +29,9 @@ appRouter.get("/news/check", capability.mw(Features.News), async (req, res) => {
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))})
appRouter.get("/menu/:date", capability.mw(Features.Menu), async (req, res) => {
var item = await Menu.aggregate(vote(new Date(req.params.date),req.user!._id))
var votes = await Vote.find({dom: new Date(req.params.date)})
var grouped = votes.reduce((x, y) => {
x[y.tom].push(y)
return x
@@ -60,7 +63,7 @@ appRouter.post("/menu/:timestamp", capability.mw(Features.Menu), async (req, res
appRouter.get("/keys", capability.mw(Features.Key), async (req, res) => {
var keys = await Key.find<Pick<IKey, "room">>({tb: {$exists: false}}, {room: 1}, {sort: {room: 1}})
var occ = keys.map(x=>x.room)
var all = usettings.settings.keyrooms
var all = usettings.value.keyrooms
var free = all.filter(x=>!occ.includes(x)).sort().map(x => {
return { room: x }
})
@@ -75,4 +78,26 @@ appRouter.get("/clean/:date", capability.mw(Features.Clean), async (req, res) =>
}))
})
export {appRouter};
appRouter.get("/notif/check", capability.mw(Features.Notif), async (req, res) => {
var result = await Inbox.find({rcpt: req.user._id, $nor: [{ack: req.user._id}]}, {message: 1, sentDate: 1})
if (result) {
res.send(result)
} else {
res.send([])
}
})
appRouter.post("/notif/:id/ack", capability.mw(Features.Notif), async (req, res) => {
var result = await Inbox.findById(req.params.id)
if (result) {
if (result.rcpt.includes(req.user._id) && !result.ack.includes(req.user._id)) {
result.ack.push(req.user._id)
await result.save({})
res.send({status: 200})
} else {
res.status(403).send({status: 401, message: "User doesn't have access or message already acknowledged"})
}
} else {
res.status(404).send({status: 404, message: "Message not found"})
}
})

8
src/routes/api/index.ts Normal file
View File

@@ -0,0 +1,8 @@
import { Router } from "express";
import { appRouter } from "./app";
import { adminRouter } from "./admin";
export const apiRouter = Router();
apiRouter.use("/app", appRouter)
apiRouter.use("/admin", adminRouter)

View File

@@ -3,16 +3,44 @@ 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";
import { readFileSync } from "node:fs";
import cap from "@/helpers/capability";
import usettings from "@/helpers/usettings";
import vapidKeys from "@/vapidKeys";
import { IVerifyOptions } from "passport-local";
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("/login", (req, res) => {
passport.authenticate('normal', (err: {type: string, message: string} | null, user?: Express.User | false, options?: IVerifyOptions) => {
if (user) {
req.login(user, (error) => {
if (error) {
res.status(500).send(error)
} else {
res.send({status: 200, admin: req.user.admin || undefined, redirect: req.user.defaultPage})
}
})
} else {
if (err) {
switch (err.type) {
case "unf":
res.status(404).send({status: 404, message: "Zła nazwa użytkownika lub hasło."})
break;
case "timeout":
res.status(403).send({status: 403, message: err.message})
break;
case "locked":
res.status(403).send({status: 403, message: err.message})
break;
default:
res.status(500).send({status: 500, message: err.message})
break;
}
} else {
res.status(403).send({status: 403, message: "Brak hasła lub loginu."})
}
}
})(req, res)
})
authRouter.post("/chpass", islogged, async (req,res) => {
@@ -51,10 +79,20 @@ 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.status(401).send({status: 401, message: "Your account has been locked."})
})
}
res.send({"admin": req.user.admin, "features": cap.flags, "room": req.user.room, "menu": {"defaultItems": usettings.settings.menu.defaultItems}, "vapid": vapidKeys.keys.publicKey})
res.send({"admin": req.user.admin, "features": cap.flags, "room": req.user.room, "menu": {"defaultItems": usettings.value.menu.defaultItems}, "vapid": vapidKeys.keys.publicKey})
})
authRouter.put("/redirect", islogged, async (req, res) => {
if (["", "/", "/login", "/login/", "login"].find(v => v == req.body.redirect)) return res.status(400).send({status: 400, message: "Path in blacklist"})
const update = await User.findByIdAndUpdate(req.user._id, {defaultPage: req.body.redirect})
if (update) {
res.send({status: 200}).end()
} else {
res.status(500).send({status: 500}).end()
}
})
export { authRouter };

View File

@@ -1,22 +1,30 @@
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 { Schema } from 'mongoose'
import capability, { Features } from "@/capability";
import capability, { Features } from "@/helpers/capability";
import mongoose from "mongoose";
import { apiRouter } from "./api";
const router = Router();
router.use('/app', appRouter)
router.use('/admin', adminRouter)
router.use('/', apiRouter)
router.use('/auth', authRouter)
router.get("/healthcheck", async (req, res) => {
res.status(200).send({
uptime: process.uptime(),
date: new Date(),
db: mongoose.connection.readyState
})
})
router.post("/notif", islogged, capability.mw(Features.Notif), async (req, res) => {
var obj = {user: req.user._id, ...req.body}
await Notification.findOneAndUpdate(obj, obj, {upsert: true})
res.send({"status": 200})
})
router.use("/", apiRouter)
export default router;

18
src/schemas/Inbox.ts Normal file
View File

@@ -0,0 +1,18 @@
import { SimpleMessage } from "@/notif"
import mongoose, { Types, Schema } from "mongoose"
export interface IInbox {
message: SimpleMessage,
sentDate: Date,
rcpt: Types.ObjectId[],
ack: Types.ObjectId[]
}
const inboxSchema = new Schema<IInbox>({
message: {type: Object, required: true},
sentDate: {type: Date, required: true, default: Date.now()},
rcpt: [{type: Schema.Types.ObjectId, ref: "logins", required: true}],
ack: [{type: Schema.Types.ObjectId, ref: "logins", required: true, default: []}],
})
export default mongoose.model("inbox", inboxSchema)

View File

@@ -1,11 +1,12 @@
import mongoose, { Schema } from "mongoose"
import mongoose, { Schema, Types } from "mongoose"
interface INews {
content: string;
title: string;
date: Date;
visible?: boolean;
pinned?: boolean
pinned?: boolean;
author: Types.ObjectId
}
const newsSchema = new Schema<INews>({
@@ -13,7 +14,8 @@ const newsSchema = new Schema<INews>({
title: {type: String, required: true},
date: {type: Date, requred: true, default: Date.now},
visible: {type: Boolean, default: false},
pinned: {type: Boolean, default: false}
pinned: {type: Boolean, default: false},
author: {type: "ObjectId", ref: "logins", required: true}
})
export default mongoose.model("news", newsSchema)

View File

@@ -1,27 +1,32 @@
import { Perms } from "@/utility";
import mongoose, { Types, Schema } from "mongoose"
// TODO: Unify `fname` and `surename` into single field
export interface IUser {
uname: string;
pass: string;
room?: string;
admin?: number;
admin?: Perms[];
locked?: boolean;
fname?: string;
surname?: string;
groups: Types.ObjectId[];
regDate: Date;
defaultPage: 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: String,
admin: Number,
room: {type: String, default: ""},
admin: [{type: String}],
locked: {type: Boolean, default: false},
fname: String,
surname: String,
groups: [{type: mongoose.Types.ObjectId, ref: "Group"}]
fname: {type: String, default: ""},
surname: {type: String, default: ""},
groups: [{type: mongoose.Types.ObjectId, ref: "Group"}],
regDate: {type: Date, default: Date.now},
defaultPage: {type: String, default: ""},
})
userSchema.index({uname: "text", room: "text", fname: "text", surname: "text"}, {weights: {fname: 3, surname: 4, room: 2, uname: 1}, default_language: "none"})
export default mongoose.model("logins", userSchema)

View File

@@ -1,38 +0,0 @@
import { readFileSync, writeFileSync } from "node:fs";
interface IUSettings {
keyrooms: string[];
rooms: string[];
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();

View File

@@ -8,21 +8,21 @@ var islogged = (req: Request, res: Response, next: NextFunction) => {
}
var isadmin = (req: Request, res: Response, next: NextFunction) => {
if (req.user.admin != null) {
if (req.user.admin) {
return next()
}
res.sendStatus(401)
}
enum Perms {
News = 1,
Menu = 2,
Notif = 4,
Groups = 8,
Accs = 16,
Superadmin = 32,
Key = 64,
Clean = 128,
News = "news",
Menu = "menu",
Notif = "notif",
Groups = "groups",
Accs = "accs",
Superadmin = "super",
Key = "keys",
Clean = "grades",
}
var adminPerm = (perm: Perms) => {
@@ -34,16 +34,26 @@ var adminPerm = (perm: Perms) => {
}
}
var adminCond = (adminInt = 0, perm: Perms) => {
return (adminInt & perm) == perm
var adminCond = (perms: Perms[], perm: Perms) => {
return perms.includes(perm)
}
var project = (obj: any, projection: any) => {
let obj2: any = {}
export function project<T extends object>(obj: T | any, projection?: (keyof T)[] | { [key in keyof T]: any}): Partial<T> {
let obj2: Partial<T> = {}
if (projection) {
if (projection instanceof Array) {
for (let key of projection) {
if (key in obj) obj2[key] = obj[key]
}
} else {
for (let key in projection) {
if (key in obj) obj2[key] = obj[key]
}
}
return obj2
} else {
return obj
}
}
export {islogged, isadmin, adminPerm, Perms, adminCond, project};
export {islogged, isadmin, adminPerm, Perms, adminCond};

View File

@@ -20,12 +20,23 @@ class VapidKeysSettings {
}
reload() {
try {
this._keys = JSON.parse(readFileSync("./config/keys.json", {encoding: "utf-8"}))
if (!(this._keys.privateKey && this._keys.publicKey)) {
} catch (error) {
if (error instanceof Error) {
if ('code' in error) {
if (error.code === "ENOENT") {
this.keys = generateVAPIDKeys();
}
}
}
} finally {
if (!(this.keys.privateKey && this.keys.publicKey)) {
this.keys = generateVAPIDKeys()
}
console.log("Reloaded VAPID keys");
}
}
}
export default new VapidKeysSettings();