Compare commits

..

No commits in common. "main" and "v1.0.1" have entirely different histories.
main ... v1.0.1

89 changed files with 204 additions and 1401 deletions

View file

@ -10,7 +10,6 @@ SERVER_PORT = portnumber
JWT_SECRET = ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890
JWT_EXPIRATION = [0-9]*(y|d|h|m|s)
REFRESH_EXPIRATION = [0-9]*(y|d|h|m|s)
PWA_REFRESH_EXPIRATION = [0-9]*(y|d|h|m|s)
MAIL_USERNAME = mail_username
MAIL_PASSWORD = mail_password
@ -18,5 +17,5 @@ MAIL_HOST = mail_hoststring
MAIL_PORT = mail_portnumber
MAIL_SECURE (true|false) // true for port 465, fals for other ports
CLUB_NAME = clubname #default FF Admin
CLUB_NAME = clubname
CLUB_WEBSITE = https://my-club-website-url

View file

@ -6,7 +6,7 @@ Administration für Feuerwehren und Vereine (Backend).
Dieses Projekt, `ff-admin-server`, ist das Backend zur Verwaltung von Mitgliederdaten. Die zugehörige Webapp ist im Repository [ff-admin-ui](https://forgejo.jk-effects.cloud/Ehrenamt/ff-admin) zu finden.
Eine Demo zusammen mit der `ff-admin` finden Sie unter [https://admin-demo.ff-admin.de](https://admin-demo.ff-admin.de).
Eine Demo zusammen mit der `ff-admin` finden Sie unter [ff-admin-demo.jk-effects.cloud](ff-admin-demo.jk-effects.cloud).
## Installation
@ -25,22 +25,21 @@ services:
container_name: ff_member_administration_server
restart: unless-stopped
environment:
- DB_TYPE=<mysql|sqlite> # default ist auf mysql gesetzt
- DB_TYPE=mysql
- DB_HOST=ffm-db
- DB_PORT=<number> # default ist auf 3306 gesetzt
- DB_PORT=<number> # fallback ist auf 3306 gesetzt
- DB_NAME=ffadmin
- DB_USERNAME=administration_backend
- DB_PASSWORD=<dbuserpasswd>
- JWT_SECRET=<tobemodified>
- JWT_EXPIRATION=<number[m|d] - bsp.:15m> # default ist auf 15m gesetzt
- REFRESH_EXPIRATION=<number[m|d] - bsp.:1d> # default ist auf 1d gesetzt
- PWA_REFRESH_EXPIRATION=<number[m|d] - bsp.:5d> # default ist auf 5d gesetzt
- JWT_EXPIRATION=<number[m|d] - bsp.:15m>
- REFRESH_EXPIRATION=<number[m|d] - bsp.:1d>
- MAIL_USERNAME=<mailadress|username>
- MAIL_PASSWORD=<password>
- MAIL_HOST=<url>
- MAIL_PORT=<port> # default ist auf 578 gesetzt
- MAIL_SECURE=<boolean> # default ist auf false gesetzt
- CLUB_NAME=<tobemodified> # default ist auf FF Admin gesetzt
- MAIL_PORT=<port>
- MAIL_SECURE=<boolean>
- CLUB_NAME=<tobemodified>
- CLUB_WEBSITE=<tobemodified>
volumes:
- <volume|local path>:/app/files

52
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "ff-admin-server",
"version": "1.2.0",
"version": "1.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ff-admin-server",
"version": "1.2.0",
"version": "1.0.1",
"license": "GPL-3.0-only",
"dependencies": {
"cors": "^2.8.5",
@ -24,7 +24,6 @@
"puppeteer": "^23.11.1",
"qrcode": "^1.5.4",
"reflect-metadata": "^0.2.2",
"rss-parser": "^3.13.0",
"socket.io": "^4.7.5",
"speakeasy": "^2.0.0",
"typeorm": "^0.3.20",
@ -1497,15 +1496,6 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/entities": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz",
"integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==",
"license": "BSD-2-Clause",
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/env-paths": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",
@ -3162,16 +3152,6 @@
"node": ">= 0.10"
}
},
"node_modules/rss-parser": {
"version": "3.13.0",
"resolved": "https://registry.npmjs.org/rss-parser/-/rss-parser-3.13.0.tgz",
"integrity": "sha512-7jWUBV5yGN3rqMMj7CZufl/291QAhvrrGpDNE4k/02ZchL0npisiYYqULF71jCEKoIiHvK/Q2e6IkDwPziT7+w==",
"license": "MIT",
"dependencies": {
"entities": "^2.0.3",
"xml2js": "^0.5.0"
}
},
"node_modules/runes2": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/runes2/-/runes2-1.1.4.tgz",
@ -3202,12 +3182,6 @@
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"node_modules/sax": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.4.1.tgz",
"integrity": "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg==",
"license": "ISC"
},
"node_modules/semver": {
"version": "7.6.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
@ -4279,28 +4253,6 @@
}
}
},
"node_modules/xml2js": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz",
"integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==",
"license": "MIT",
"dependencies": {
"sax": ">=0.6.0",
"xmlbuilder": "~11.0.0"
},
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/xmlbuilder": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
"integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
"license": "MIT",
"engines": {
"node": ">=4.0"
}
},
"node_modules/y18n": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",

View file

@ -1,6 +1,6 @@
{
"name": "ff-admin-server",
"version": "1.2.0",
"version": "1.0.1",
"description": "Feuerwehr/Verein Mitgliederverwaltung Server",
"main": "dist/index.js",
"scripts": {
@ -39,7 +39,6 @@
"puppeteer": "^23.11.1",
"qrcode": "^1.5.4",
"reflect-metadata": "^0.2.2",
"rss-parser": "^3.13.0",
"socket.io": "^4.7.5",
"speakeasy": "^2.0.0",
"typeorm": "^0.3.20",

View file

@ -33,10 +33,7 @@ export default abstract class MemberCommandHandler {
return result.identifiers[0].id;
})
.catch((err) => {
throw new InternalException(
`Failed creating member${err.code.includes("ER_DUP_ENTRY") ? " due to duplicate entry for column" : ""}`,
err
);
throw new InternalException("Failed creating member", err);
});
}
@ -46,6 +43,7 @@ export default abstract class MemberCommandHandler {
* @returns {Promise<void>}
*/
static async update(updateMember: UpdateMemberCommand): Promise<void> {
console.log(updateMember);
return await dataSource
.createQueryBuilder()
.update(member)
@ -61,10 +59,7 @@ export default abstract class MemberCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed updating member${err.code.includes("ER_DUP_ENTRY") ? " due to duplicate entry for column" : ""}`,
err
);
throw new InternalException("Failed updating member", err);
});
}
@ -89,7 +84,7 @@ export default abstract class MemberCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(`Failed updating member`, err);
throw new InternalException("Failed updating member", err);
});
}

View file

@ -31,7 +31,7 @@ export default abstract class MembershipCommandHandler {
.createQueryBuilder()
.update(membership)
.set({
end: new Date(new Date(createMembership.start).setDate(new Date(createMembership.start).getDate() - 1)),
end: new Date(createMembership.start).setDate(new Date(createMembership.start).getDate() - 1),
terminationReason: "beendet durch neuen Eintrag.",
})
.where("end IS NULL")

View file

@ -6,5 +6,4 @@ export interface SynchronizeProtocolPresenceCommand {
export interface ProtocolPresenceCommand {
memberId: number;
absent: boolean;
excused: boolean;
}

View file

@ -74,7 +74,6 @@ export default abstract class ProtocolPresenceCommandHandler {
.update(protocolPresence)
.set({
absent: member.absent,
excused: member.excused,
})
.where("memberId = :memberId", { memberId: member.memberId })
.andWhere("protocolId = :protocolId", { protocolId })

View file

@ -1,6 +1,5 @@
export interface CreateRefreshCommand {
userId: number;
isFromPwa?: boolean;
}
export interface DeleteRefreshCommand {

View file

@ -1,9 +1,11 @@
import { dataSource } from "../data-source";
import { refresh } from "../entity/refresh";
import { PWA_REFRESH_EXPIRATION, REFRESH_EXPIRATION } from "../env.defaults";
import { REFRESH_EXPIRATION } from "../env.defaults";
import InternalException from "../exceptions/internalException";
import { JWTHelper } from "../helpers/jwtHelper";
import { StringHelper } from "../helpers/stringHelper";
import UserService from "../service/user/userService";
import { JWTRefresh } from "../type/jwtTypes";
import { CreateRefreshCommand, DeleteRefreshCommand } from "./refreshCommand";
import ms from "ms";
@ -14,6 +16,10 @@ export default abstract class RefreshCommandHandler {
* @returns {Promise<string>}
*/
static async create(createRefresh: CreateRefreshCommand): Promise<string> {
// let createRefreshToken: JWTRefresh = {
// userId: createRefresh.userId,
// };
// const refreshToken = await JWTHelper.create(createRefreshToken);
const refreshToken = StringHelper.random(32);
return await dataSource
@ -23,9 +29,7 @@ export default abstract class RefreshCommandHandler {
.values({
token: refreshToken,
user: await UserService.getById(createRefresh.userId),
expiry: createRefresh.isFromPwa
? new Date(Date.now() + ms(PWA_REFRESH_EXPIRATION))
: new Date(Date.now() + ms(REFRESH_EXPIRATION)),
expiry: new Date(Date.now() + ms(REFRESH_EXPIRATION)),
})
.execute()
.then((result) => {

View file

@ -60,10 +60,7 @@ export default abstract class AwardCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed deleting award ${err.code.includes("ER_ROW_IS_REFERENCED") ? " due to referenced data" : ""}`,
err
);
throw new InternalException("Failed deleting award", err);
});
}
}

View file

@ -66,10 +66,7 @@ export default abstract class CalendarTypeCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed deleting calendarType${err.code.includes("ER_ROW_IS_REFERENCED") ? " due to referenced data" : ""}`,
err
);
throw new InternalException("Failed deleting calendarType", err);
});
}
}

View file

@ -66,12 +66,7 @@ export default abstract class CommunicationTypeCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed deleting communicationType${
err.code.includes("ER_ROW_IS_REFERENCED") ? " due to referenced data" : ""
}`,
err
);
throw new InternalException("Failed deleting communicationType", err);
});
}
}

View file

@ -64,12 +64,7 @@ export default abstract class ExecutivePositionCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed deleting executivePosition${
err.code.includes("ER_ROW_IS_REFERENCED") ? " due to referenced data" : ""
}`,
err
);
throw new InternalException("Failed deleting executivePosition", err);
});
}
}

View file

@ -64,12 +64,7 @@ export default abstract class MembershipStatusCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed deleting membershipStatus${
err.code.includes("ER_ROW_IS_REFERENCED") ? " due to referenced data" : ""
}`,
err
);
throw new InternalException("Failed deleting membershipStatus", err);
});
}
}

View file

@ -4,3 +4,7 @@ export interface SetNewsletterConfigCommand {
comTypeId: number;
config: NewsletterConfigType;
}
export interface DeleteNewsletterConfigCommand {
comTypeId: number;
}

View file

@ -1,7 +1,7 @@
import { dataSource } from "../../../data-source";
import { newsletterConfig } from "../../../entity/settings/newsletterConfig";
import InternalException from "../../../exceptions/internalException";
import { SetNewsletterConfigCommand } from "./newsletterConfigCommand";
import { DeleteNewsletterConfigCommand, SetNewsletterConfigCommand } from "./newsletterConfigCommand";
export default abstract class NewsletterConfigCommandHandler {
/**
@ -27,4 +27,21 @@ export default abstract class NewsletterConfigCommandHandler {
throw new InternalException("Failed setting newsletterConfig", err);
});
}
/**
* @description delete newsletterConfig
* @param {DeleteNewsletterConfigCommand} deleteNewsletterConfig
* @returns {Promise<void>}
*/
static async delete(deleteNewsletterConfig: DeleteNewsletterConfigCommand): Promise<void> {
return await dataSource
.createQueryBuilder()
.delete()
.from(newsletterConfig)
.where("comTypeId = :comTypeId", { comTypeId: deleteNewsletterConfig.comTypeId })
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException("Failed setting newsletterConfig", err);
});
}
}

View file

@ -66,10 +66,7 @@ export default abstract class QualificationCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed deleting qualification${err.code.includes("ER_ROW_IS_REFERENCED") ? " due to referenced data" : ""}`,
err
);
throw new InternalException("Failed deleting qualification", err);
});
}
}

View file

@ -63,10 +63,7 @@ export default abstract class QueryStoreCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed deleting queryStore${err.code.includes("ER_ROW_IS_REFERENCED") ? " due to referenced data" : ""}`,
err
);
throw new InternalException("Failed deleting queryStore", err);
});
}
}

View file

@ -64,10 +64,7 @@ export default abstract class TemplateCommandHandler {
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed deleting template${err.code.includes("ER_ROW_IS_REFERENCED") ? " due to referenced data" : ""}`,
err
);
throw new InternalException("Failed deleting template", err);
});
}
}

View file

@ -1,19 +0,0 @@
export interface CreateWebapiCommand {
title: string;
token: string;
expiry?: Date;
}
export interface UpdateWebapiCommand {
id: number;
title: string;
expiry?: Date;
}
export interface UpdateLastUsageWebapiCommand {
id: number;
}
export interface DeleteWebapiCommand {
id: number;
}

View file

@ -1,100 +0,0 @@
import { dataSource } from "../../../data-source";
import { webapi } from "../../../entity/user/webapi";
import InternalException from "../../../exceptions/internalException";
import {
CreateWebapiCommand,
DeleteWebapiCommand,
UpdateLastUsageWebapiCommand,
UpdateWebapiCommand,
} from "./webapiCommand";
export default abstract class WebapiCommandHandler {
/**
* @description create api
* @param {CreateWebapiCommand} createWebapi
* @returns {Promise<number>}
*/
static async create(createWebapi: CreateWebapiCommand): Promise<number> {
return await dataSource
.createQueryBuilder()
.insert()
.into(webapi)
.values({
token: createWebapi.token,
title: createWebapi.title,
expiry: createWebapi.expiry,
})
.execute()
.then((result) => {
return result.identifiers[0].token;
})
.catch((err) => {
throw new InternalException(
`Failed creating api${err.code.includes("ER_DUP_ENTRY") ? " due to duplicate entry for column" : ""}`,
err
);
});
}
/**
* @description update api
* @param {UpdateWebapiCommand} updateWebapi
* @returns {Promise<void>}
*/
static async update(updateWebapi: UpdateWebapiCommand): Promise<void> {
return await dataSource
.createQueryBuilder()
.update(webapi)
.set({
title: updateWebapi.title,
expiry: updateWebapi.expiry,
})
.where("id = :id", { id: updateWebapi.id })
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(
`Failed updating api${err.code.includes("ER_DUP_ENTRY") ? " due to duplicate entry for column" : ""}`,
err
);
});
}
/**
* @description update api usage
* @param {UpdateLastUsageWebapiCommand} updateWebapi
* @returns {Promise<void>}
*/
static async updateUsage(updateWebapi: UpdateLastUsageWebapiCommand): Promise<void> {
return await dataSource
.createQueryBuilder()
.update(webapi)
.set({
lastUsage: new Date(),
})
.where("id = :id", { id: updateWebapi.id })
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException(`Failed updating api last usage`, err);
});
}
/**
* @description delete api
* @param {DeleteWebapiCommand} deleteWebapi
* @returns {Promise<void>}
*/
static async delete(deleteWebapi: DeleteWebapiCommand): Promise<void> {
return await dataSource
.createQueryBuilder()
.delete()
.from(webapi)
.where("id = :id", { id: deleteWebapi.id })
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException("Failed deleting api", err);
});
}
}

View file

@ -1,16 +0,0 @@
import { PermissionString } from "../../../type/permissionTypes";
export interface CreateWebapiPermissionCommand {
permission: PermissionString;
webapiId: number;
}
export interface DeleteWebapiPermissionCommand {
permission: PermissionString;
webapiId: number;
}
export interface UpdateWebapiPermissionsCommand {
webapiId: number;
permissions: Array<PermissionString>;
}

View file

@ -1,119 +0,0 @@
import { DeleteResult, EntityManager, InsertResult } from "typeorm";
import { dataSource } from "../../../data-source";
import { webapiPermission } from "../../../entity/user/webapi_permission";
import InternalException from "../../../exceptions/internalException";
import WebapiService from "../../../service/user/webapiService";
import {
CreateWebapiPermissionCommand,
DeleteWebapiPermissionCommand,
UpdateWebapiPermissionsCommand,
} from "./webapiPermissionCommand";
import PermissionHelper from "../../../helpers/permissionHelper";
import WebapiPermissionService from "../../../service/user/webapiPermissionService";
import { PermissionString } from "../../../type/permissionTypes";
export default abstract class WebapiPermissionCommandHandler {
/**
* @description update api permissions
* @param {UpdateWebapiPermissionsCommand} updateWebapiPermissions
* @returns {Promise<void>}
*/
static async updatePermissions(updateWebapiPermissions: UpdateWebapiPermissionsCommand): Promise<void> {
let currentPermissions = (await WebapiPermissionService.getByApi(updateWebapiPermissions.webapiId)).map(
(r) => r.permission
);
return await dataSource.manager
.transaction(async (manager) => {
let newPermissions = PermissionHelper.getWhatToAdd(currentPermissions, updateWebapiPermissions.permissions);
let removePermissions = PermissionHelper.getWhatToRemove(
currentPermissions,
updateWebapiPermissions.permissions
);
if (newPermissions.length != 0) {
await this.updatePermissionsAdd(manager, updateWebapiPermissions.webapiId, newPermissions);
}
if (removePermissions.length != 0) {
await this.updatePermissionsRemove(manager, updateWebapiPermissions.webapiId, removePermissions);
}
})
.then(() => {})
.catch((err) => {
throw new InternalException("Failed saving api permissions", err);
});
}
private static async updatePermissionsAdd(
manager: EntityManager,
webapiId: number,
permissions: Array<PermissionString>
): Promise<InsertResult> {
return await manager
.createQueryBuilder()
.insert()
.into(webapiPermission)
.values(
permissions.map((p) => ({
permission: p,
webapiId: webapiId,
}))
)
.orIgnore()
.execute();
}
private static async updatePermissionsRemove(
manager: EntityManager,
webapiId: number,
permissions: Array<PermissionString>
): Promise<DeleteResult> {
return await manager
.createQueryBuilder()
.delete()
.from(webapiPermission)
.where("webapiId = :id", { id: webapiId })
.andWhere("permission IN (:...permission)", { permission: permissions })
.execute();
}
/**
* @description grant permission to user
* @param {CreateWebapiPermissionCommand} createPermission
* @returns {Promise<number>}
*/
static async create(createPermission: CreateWebapiPermissionCommand): Promise<number> {
return await dataSource
.createQueryBuilder()
.insert()
.into(webapiPermission)
.values({
permission: createPermission.permission,
webapiId: createPermission.webapiId,
})
.execute()
.then((result) => {
return result.identifiers[0].id;
})
.catch((err) => {
throw new InternalException("Failed saving api permission", err);
});
}
/**
* @description remove permission from api
* @param {DeleteWebapiPermissionCommand} deletePermission
* @returns {Promise<any>}
*/
static async delete(deletePermission: DeleteWebapiPermissionCommand): Promise<any> {
return await dataSource
.createQueryBuilder()
.delete()
.from(webapiPermission)
.where("webapiId = :id", { id: deletePermission.webapiId })
.andWhere("permission = :permission", { permission: deletePermission.permission })
.execute()
.then(() => {})
.catch((err) => {
throw new InternalException("failed api permission removal", err);
});
}
}

View file

@ -61,13 +61,8 @@ export async function getAllMembers(req: Request, res: Response): Promise<any> {
let offset = parseInt((req.query.offset as string) ?? "0");
let count = parseInt((req.query.count as string) ?? "25");
let search = (req.query.search as string) ?? "";
let noLimit = req.query.noLimit === "true";
let ids = ((req.query.ids ?? "") as string)
.split(",")
.filter((i) => i)
.map((i) => parseInt(i));
let [members, total] = await MemberService.getAll({ offset, count, search, noLimit, ids });
let [members, total] = await MemberService.getAll(offset, count, search);
res.json({
members: MemberFactory.mapToBase(members),
@ -90,19 +85,6 @@ export async function getMemberById(req: Request, res: Response): Promise<any> {
res.json(MemberFactory.mapToSingle(member));
}
/**
* @description get member statistics by id
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function getMemberStatisticsById(req: Request, res: Response): Promise<any> {
const memberId = parseInt(req.params.id);
let member = await MemberService.getStatisticsById(memberId);
res.json(MemberFactory.mapToMemberStatistic(member));
}
/**
* @description get memberships by member
* @param req {Request} Express req object
@ -116,19 +98,6 @@ export async function getMembershipsByMember(req: Request, res: Response): Promi
res.json(MembershipFactory.mapToBase(memberships));
}
/**
* @description get member statistics by id
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function getMembershipStatisticsById(req: Request, res: Response): Promise<any> {
const memberId = parseInt(req.params.memberId);
let member = await MembershipService.getStatisticsById(memberId);
res.json(MembershipFactory.mapToBaseStatistics(member));
}
/**
* @description get membership by member and record
* @param req {Request} Express req object

View file

@ -6,10 +6,7 @@ import NewsletterDatesFactory from "../../../factory/admin/club/newsletter/newsl
import NewsletterRecipientsService from "../../../service/club/newsletter/newsletterRecipientsService";
import NewsletterRecipientsFactory from "../../../factory/admin/club/newsletter/newsletterRecipients";
import { FileSystemHelper } from "../../../helpers/fileSystemHelper";
import {
CreateNewsletterCommand,
SynchronizeNewsletterCommand,
} from "../../../command/club/newsletter/newsletterCommand";
import { CreateNewsletterCommand, SynchronizeNewsletterCommand } from "../../../command/club/newsletter/newsletterCommand";
import NewsletterCommandHandler from "../../../command/club/newsletter/newsletterCommandHandler";
import { SynchronizeNewsletterDatesCommand } from "../../../command/club/newsletter/newsletterDatesCommand";
import NewsletterDatesCommandHandler from "../../../command/club/newsletter/newsletterDatesCommandHandler";
@ -191,14 +188,15 @@ export async function createNewsletter(req: Request, res: Response): Promise<any
export async function getNewsletterPrintoutProgressById(req: Request, res: Response): Promise<any> {
let newsletterId = parseInt(req.params.newsletterId);
res.writeHead(200, {
"Content-Type": "text/plain",
"Transfer-Encoding": "chunked",
});
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.flushHeaders();
const progressHandler = (data: NewsletterEventType) => {
if (data.newsletterId == newsletterId && data.kind == "pdf") {
res.write(JSON.stringify(data) + "//");
res.write(JSON.stringify(data));
}
};
@ -289,14 +287,15 @@ export async function sendNewsletterById(req: Request, res: Response): Promise<a
export async function getNewsletterSendingProgressById(req: Request, res: Response): Promise<any> {
let newsletterId = parseInt(req.params.newsletterId);
res.writeHead(200, {
"Content-Type": "text/plain",
"Transfer-Encoding": "chunked",
});
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.flushHeaders();
const progressHandler = (data: NewsletterEventType) => {
if (data.newsletterId == newsletterId && data.kind == "mail") {
res.write(JSON.stringify(data) + "//");
res.write(JSON.stringify(data));
}
};

View file

@ -260,9 +260,7 @@ export async function createProtocolPrintoutById(req: Request, res: Response): P
agenda,
decisions,
presence: presence.filter((p) => !p.absent).map((p) => p.member),
absent: presence.filter((p) => p.absent).map((p) => ({ ...p.member, excused: p.excused })),
excused_absent: presence.filter((p) => p.absent && p.excused).map((p) => p.member),
unexcused_absent: presence.filter((p) => p.absent && !p.excused).map((p) => p.member),
absent: presence.filter((p) => p.absent).map((p) => p.member),
votings,
},
});
@ -391,7 +389,6 @@ export async function synchronizeProtocolPrecenseById(req: Request, res: Respons
members: presence.map((p) => ({
memberId: p.memberId,
absent: p.absent,
excused: p.excused,
})),
protocolId,
};

View file

@ -2,7 +2,7 @@ import { Request, Response } from "express";
import NewsletterConfigService from "../../../service/settings/newsletterConfigService";
import NewsletterConfigFactory from "../../../factory/admin/settings/newsletterConfig";
import NewsletterConfigCommandHandler from "../../../command/settings/newsletterConfig/newsletterConfigCommandHandler";
import { SetNewsletterConfigCommand } from "../../../command/settings/newsletterConfig/newsletterConfigCommand";
import { DeleteNewsletterConfigCommand, SetNewsletterConfigCommand } from "../../../command/settings/newsletterConfig/newsletterConfigCommand";
/**
* @description get all newsletterConfigs
@ -47,3 +47,20 @@ export async function setNewsletterConfig(req: Request, res: Response): Promise<
res.send(id);
}
/**
* @description delete award
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function deleteNewsletterConfig(req: Request, res: Response): Promise<any> {
const comTypeId = parseInt(req.params.comTypeId);
let deleteNewsletterConfig: DeleteNewsletterConfigCommand = {
comTypeId: comTypeId,
};
await NewsletterConfigCommandHandler.delete(deleteNewsletterConfig);
res.sendStatus(204);
}

View file

@ -1,155 +0,0 @@
import { Request, Response } from "express";
import WebapiService from "../../../service/user/webapiService";
import ApiFactory from "../../../factory/admin/user/webapi";
import WebapiPermissionService from "../../../service/user/webapiPermissionService";
import PermissionHelper from "../../../helpers/permissionHelper";
import {
CreateWebapiCommand,
DeleteWebapiCommand,
UpdateWebapiCommand,
} from "../../../command/user/webapi/webapiCommand";
import WebapiCommandHandler from "../../../command/user/webapi/webapiCommandHandler";
import { UpdateWebapiPermissionsCommand } from "../../../command/user/webapi/webapiPermissionCommand";
import WebapiPermissionCommandHandler from "../../../command/user/webapi/webapiPermissionCommandHandler";
import { JWTHelper } from "../../../helpers/jwtHelper";
import { CLUB_NAME } from "../../../env.defaults";
import { StringHelper } from "../../../helpers/stringHelper";
/**
* @description get All apis
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function getAllWebapis(req: Request, res: Response): Promise<any> {
let apis = await WebapiService.getAll();
res.json(ApiFactory.mapToBase(apis));
}
/**
* @description get api by id
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function getWebapiById(req: Request, res: Response): Promise<any> {
const id = parseInt(req.params.id);
let api = await WebapiService.getById(id);
res.json(ApiFactory.mapToSingle(api));
}
/**
* @description get api token by id
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function getWebapiTokenById(req: Request, res: Response): Promise<any> {
const id = parseInt(req.params.id);
let { token } = await WebapiService.getTokenById(id);
res.send(token);
}
/**
* @description get permissions by api
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function getWebapiPermissions(req: Request, res: Response): Promise<any> {
const id = parseInt(req.params.id);
let permissions = await WebapiPermissionService.getByApi(id);
res.json(PermissionHelper.convertToObject(permissions.map((p) => p.permission)));
}
/**
* @description create new api
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function createWebapi(req: Request, res: Response): Promise<any> {
let title = req.body.title;
let expiry = req.body.expiry || null;
let token = await JWTHelper.create(
{
iss: CLUB_NAME,
sub: "api_token_retrieve",
aud: StringHelper.random(32),
},
{ useExpiration: false }
);
let createApi: CreateWebapiCommand = {
token: token,
title: title,
expiry: expiry,
};
await WebapiCommandHandler.create(createApi);
res.sendStatus(204);
}
/**
* @description update api data
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function updateWebapi(req: Request, res: Response): Promise<any> {
const id = parseInt(req.params.id);
let title = req.body.title;
let expiry = req.body.expiry || null;
let updateApi: UpdateWebapiCommand = {
id: id,
title: title,
expiry: expiry,
};
await WebapiCommandHandler.update(updateApi);
res.sendStatus(204);
}
/**
* @description update api assigned permission strings
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function updateWebapiPermissions(req: Request, res: Response): Promise<any> {
const id = parseInt(req.params.id);
let permissions = req.body.permissions;
let permissionStrings = PermissionHelper.convertToStringArray(permissions);
let updateApiPermissions: UpdateWebapiPermissionsCommand = {
webapiId: id,
permissions: permissionStrings,
};
await WebapiPermissionCommandHandler.updatePermissions(updateApiPermissions);
res.sendStatus(204);
}
/**
* @description delete api by id
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function deleteWebapi(req: Request, res: Response): Promise<any> {
const id = parseInt(req.params.id);
let deleteApi: DeleteWebapiCommand = {
id: id,
};
await WebapiCommandHandler.delete(deleteApi);
res.sendStatus(204);
}

View file

@ -8,6 +8,9 @@ import UserService from "../service/user/userService";
import speakeasy from "speakeasy";
import UnauthorizedRequestException from "../exceptions/unauthorizedRequestException";
import RefreshService from "../service/refreshService";
import UserPermissionService from "../service/user/userPermissionService";
import PermissionHelper from "../helpers/permissionHelper";
import RolePermissionService from "../service/user/rolePermissionService";
/**
* @description Check authentication status by token
@ -36,7 +39,6 @@ export async function login(req: Request, res: Response): Promise<any> {
let refreshCommand: CreateRefreshCommand = {
userId: id,
isFromPwa: req.isPWA,
};
let refreshToken = await RefreshCommandHandler.create(refreshCommand);
@ -81,7 +83,6 @@ export async function refresh(req: Request, res: Response): Promise<any> {
let refreshCommand: CreateRefreshCommand = {
userId: tokenUserId,
isFromPwa: req.isPWA,
};
let refreshToken = await RefreshCommandHandler.create(refreshCommand);

View file

@ -1,37 +0,0 @@
import { Request, Response } from "express";
import { JWTHelper } from "../helpers/jwtHelper";
import { JWTToken } from "../type/jwtTypes";
import InternalException from "../exceptions/internalException";
import RefreshCommandHandler from "../command/refreshCommandHandler";
import { CreateRefreshCommand, DeleteRefreshCommand } from "../command/refreshCommand";
import UserService from "../service/user/userService";
import speakeasy from "speakeasy";
import UnauthorizedRequestException from "../exceptions/unauthorizedRequestException";
import RefreshService from "../service/refreshService";
import WebapiService from "../service/user/webapiService";
import ForbiddenRequestException from "../exceptions/forbiddenRequestException";
import WebapiCommandHandler from "../command/user/webapi/webapiCommandHandler";
/**
* @description Check authentication status by token
* @param req {Request} Express req object
* @param res {Response} Express res object
* @returns {Promise<*>}
*/
export async function getWebApiAccess(req: Request, res: Response): Promise<any> {
const bearer = req.headers.authorization?.split(" ")?.[1] ?? undefined;
let { id, expiry } = await WebapiService.getByToken(bearer);
if (expiry != null && new Date() > new Date(expiry)) {
throw new ForbiddenRequestException("api token expired");
}
await WebapiCommandHandler.updateUsage({ id });
let accessToken = await JWTHelper.buildWebapiToken(bearer, expiry);
res.json({
accessToken,
});
}

View file

@ -67,10 +67,6 @@ import { ProtocolAbsent1736072179716 } from "./migrations/1736072179716-protocol
import { Memberlist1736079005086 } from "./migrations/1736079005086-memberlist";
import { ExtendViewValues1736084198860 } from "./migrations/1736084198860-extendViewValues";
import { FinishInternalIdTransfer1736505324488 } from "./migrations/1736505324488-finishInternalIdTransfer";
import { ProtocolPresenceExcuse1737287798828 } from "./migrations/1737287798828-protocolPresenceExcuse";
import { webapi } from "./entity/user/webapi";
import { webapiPermission } from "./entity/user/webapi_permission";
import { AddWebapiTokens1737453096674 } from "./migrations/1737453096674-addwebapiTokens";
const dataSource = new DataSource({
type: DB_TYPE as any,
@ -120,8 +116,6 @@ const dataSource = new DataSource({
memberExecutivePositionsView,
memberQualificationsView,
membershipView,
webapi,
webapiPermission,
],
migrations: [
Initial1724317398939,
@ -150,8 +144,6 @@ const dataSource = new DataSource({
Memberlist1736079005086,
ExtendViewValues1736084198860,
FinishInternalIdTransfer1736505324488,
ProtocolPresenceExcuse1737287798828,
AddWebapiTokens1737453096674,
],
migrationsRun: true,
migrationsTransactionMode: "each",

View file

@ -40,17 +40,17 @@ export class communication {
@Column()
typeId: number;
@ManyToOne(() => member, (member) => member.awards, {
nullable: false,
onDelete: "CASCADE",
onUpdate: "RESTRICT",
})
member: member;
@ManyToOne(() => communicationType, (communicationType) => communicationType.communications, {
nullable: false,
onDelete: "RESTRICT",
onUpdate: "RESTRICT",
})
type: communicationType;
@ManyToOne(() => member, (member) => member.awards, {
nullable: false,
onDelete: "CASCADE",
onUpdate: "RESTRICT",
})
member: member;
}

View file

@ -13,9 +13,6 @@ export class protocolPresence {
@Column({ type: "boolean", default: false })
absent: boolean;
@Column({ type: "boolean", default: true })
excused: boolean;
@ManyToOne(() => member, {
nullable: false,
onDelete: "CASCADE",

View file

@ -9,7 +9,7 @@ export class protocolPrintout {
@Column({ type: "varchar", length: 255 })
title: string;
@Column({ type: "int", default: "1" })
@Column({ type: "int" })
iteration: number;
@Column({ type: "varchar", length: 255 })

View file

@ -1,26 +0,0 @@
import { Column, CreateDateColumn, Entity, OneToMany, PrimaryColumn } from "typeorm";
import { webapiPermission } from "./webapi_permission";
@Entity()
export class webapi {
@PrimaryColumn({ generated: "increment", type: "int" })
id: number;
@Column({ type: "text", unique: true, select: false })
token: string;
@Column({ type: "varchar", length: 255, unique: true })
title: string;
@CreateDateColumn()
createdAt: Date;
@Column({ type: "datetime", nullable: true })
lastUsage?: Date;
@Column({ type: "date", nullable: true })
expiry?: Date;
@OneToMany(() => webapiPermission, (apiPermission) => apiPermission.webapi)
permissions: webapiPermission[];
}

View file

@ -1,19 +0,0 @@
import { Column, Entity, ManyToOne, OneToMany, PrimaryColumn } from "typeorm";
import { PermissionObject, PermissionString } from "../../type/permissionTypes";
import { webapi } from "./webapi";
@Entity()
export class webapiPermission {
@PrimaryColumn({ type: "int" })
webapiId: number;
@PrimaryColumn({ type: "varchar", length: 255 })
permission: PermissionString;
@ManyToOne(() => webapi, {
nullable: false,
onDelete: "CASCADE",
onUpdate: "RESTRICT",
})
webapi: webapi;
}

View file

@ -13,7 +13,6 @@ export const SERVER_PORT = Number(process.env.SERVER_PORT ?? 5000);
export const JWT_SECRET = process.env.JWT_SECRET ?? "my_jwt_secret_string_ilughfnadiuhgq§$IUZGFVRweiouarbt1oub3h5q4a";
export const JWT_EXPIRATION = process.env.JWT_EXPIRATION ?? "15m";
export const REFRESH_EXPIRATION = process.env.REFRESH_EXPIRATION ?? "1d";
export const PWA_REFRESH_EXPIRATION = process.env.PWA_REFRESH_EXPIRATION ?? "5d";
export const MAIL_USERNAME = process.env.MAIL_USERNAME ?? "";
export const MAIL_PASSWORD = process.env.MAIL_PASSWORD ?? "";
@ -21,7 +20,7 @@ export const MAIL_HOST = process.env.MAIL_HOST ?? "";
export const MAIL_PORT = Number(process.env.MAIL_PORT ?? "587");
export const MAIL_SECURE = process.env.MAIL_SECURE ?? "false";
export const CLUB_NAME = process.env.CLUB_NAME ?? "FF Admin";
export const CLUB_NAME = process.env.CLUB_NAME ?? "";
export const CLUB_WEBSITE = process.env.CLUB_WEBSITE ?? "";
export function configCheck() {
@ -36,7 +35,6 @@ export function configCheck() {
if (JWT_SECRET == "" || typeof JWT_SECRET != "string") throw new Error("set valid value to JWT_SECRET");
checkMS(JWT_EXPIRATION, "JWT_EXPIRATION");
checkMS(REFRESH_EXPIRATION, "REFRESH_EXPIRATION");
checkMS(PWA_REFRESH_EXPIRATION, "PWA_REFRESH_EXPIRATION");
if (MAIL_USERNAME == "" || typeof MAIL_USERNAME != "string") throw new Error("set valid value to MAIL_USERNAME");
if (MAIL_PASSWORD == "" || typeof MAIL_PASSWORD != "string") throw new Error("set valid value to MAIL_PASSWORD");
@ -44,6 +42,7 @@ export function configCheck() {
if (typeof MAIL_PORT != "number") throw new Error("set valid numeric value to MAIL_PORT");
if (MAIL_SECURE != "true" && MAIL_SECURE != "false") throw new Error("set 'true' or 'false' to MAIL_SECURE");
console.log(CLUB_WEBSITE);
if (
CLUB_WEBSITE != "" &&
!/^(http(s):\/\/.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/.test(CLUB_WEBSITE)

View file

@ -1,6 +1,5 @@
import { member } from "../../../../entity/club/member/member";
import { MemberStatisticsViewModel, MemberViewModel } from "../../../../viewmodel/admin/club/member/member.models";
import { memberView } from "../../../../views/memberView";
import { MemberViewModel } from "../../../../viewmodel/admin/club/member/member.models";
import CommunicationFactory from "./communication";
import MembershipFactory from "./membership";
@ -41,23 +40,4 @@ export default abstract class MemberFactory {
public static mapToBase(records: Array<member>): Array<MemberViewModel> {
return records.map((r) => this.mapToSingle(r));
}
/**
* @description map view record to MemberMembershipStatisticsViewModel
* @param {memberView} record
* @returns {MemberStatisticsViewModel}
*/
public static mapToMemberStatistic(record: memberView): MemberStatisticsViewModel {
return {
id: record.id,
salutation: record.salutation,
firstname: record.firstname,
lastname: record.lastname,
nameaffix: record.nameaffix,
birthdate: record.birthdate,
todayAge: record.todayAge,
ageThisYear: record.ageThisYear,
exactAge: record.exactAge,
};
}
}

View file

@ -1,9 +1,5 @@
import { membership } from "../../../../entity/club/member/membership";
import {
MembershipStatisticsViewModel,
MembershipViewModel,
} from "../../../../viewmodel/admin/club/member/membership.models";
import { membershipView } from "../../../../views/membershipsView";
import { MembershipViewModel } from "../../../../viewmodel/admin/club/member/membership.models";
export default abstract class MembershipFactory {
/**
@ -30,33 +26,4 @@ export default abstract class MembershipFactory {
public static mapToBase(records: Array<membership>): Array<MembershipViewModel> {
return records.map((r) => this.mapToSingle(r));
}
/**
* @description map view record to MembershipStatisticsViewModel
* @param {membershipView} record
* @returns {MembershipStatisticsViewModel}
*/
public static mapToSingleStatistic(record: membershipView): MembershipStatisticsViewModel {
return {
durationInDays: record.durationInDays,
durationInYears: record.durationInYears,
status: record.status,
statusId: record.statusId,
memberId: record.memberId,
memberSalutation: record.memberSalutation,
memberFirstname: record.memberFirstname,
memberLastname: record.memberLastname,
memberNameaffix: record.memberNameaffix,
memberBirthdate: record.memberBirthdate,
};
}
/**
* @description map records to MembershipStatisticsViewModel
* @param {Array<membershipView>} records
* @returns {Array<MembershipStatisticsViewModel>}
*/
public static mapToBaseStatistics(records: Array<membershipView>): Array<MembershipStatisticsViewModel> {
return records.map((r) => this.mapToSingleStatistic(r));
}
}

View file

@ -12,7 +12,6 @@ export default abstract class ProtocolPresenceFactory {
return {
memberId: record.member.id,
absent: record.absent,
excused: record.excused,
protocolId: record.protocolId,
};
}

View file

@ -1,30 +0,0 @@
import { webapi } from "../../../entity/user/webapi";
import PermissionHelper from "../../../helpers/permissionHelper";
import { ApiViewModel } from "../../../viewmodel/admin/user/webapi.models";
export default abstract class ApiFactory {
/**
* @description map record to api
* @param {webapi} record
* @returns {apiViewModel}
*/
public static mapToSingle(record: webapi): ApiViewModel {
return {
id: record.id,
permissions: PermissionHelper.convertToObject(record.permissions.map((e) => e.permission)),
title: record.title,
expiry: record.expiry,
lastUsage: record.lastUsage,
createdAt: record.createdAt,
};
}
/**
* @description map records to api
* @param {Array<webapi>} records
* @returns {Array<apiViewModel>}
*/
public static mapToBase(records: Array<webapi>): Array<ApiViewModel> {
return records.map((r) => this.mapToSingle(r));
}
}

View file

@ -6,9 +6,6 @@ import RolePermissionService from "../service/user/rolePermissionService";
import UserPermissionService from "../service/user/userPermissionService";
import UserService from "../service/user/userService";
import PermissionHelper from "./permissionHelper";
import WebapiService from "../service/user/webapiService";
import WebapiPermissionService from "../service/user/webapiPermissionService";
import ms from "ms";
export abstract class JWTHelper {
static validate(token: string): Promise<string | jwt.JwtPayload> {
@ -20,16 +17,13 @@ export abstract class JWTHelper {
});
}
static create(
data: JWTData,
{ expOverwrite, useExpiration }: { expOverwrite?: number; useExpiration?: boolean } = { useExpiration: true }
): Promise<string> {
static create(data: JWTData): Promise<string> {
return new Promise<string>((resolve, reject) => {
jwt.sign(
data,
JWT_SECRET,
{
...(useExpiration ?? true ? { expiresIn: expOverwrite ?? JWT_EXPIRATION } : {}),
expiresIn: JWT_EXPIRATION,
},
(err, token) => {
if (err) reject(err.message);
@ -78,35 +72,4 @@ export abstract class JWTHelper {
throw new InternalException("Failed accessToken creation", err);
});
}
static async buildWebapiToken(token: string, expiration?: Date): Promise<string> {
let { id, title } = await WebapiService.getByToken(token);
let webapiPermissions = await WebapiPermissionService.getByApi(id);
let webapiPermissionStrings = webapiPermissions.map((e) => e.permission);
let permissionObject = PermissionHelper.convertToObject(webapiPermissionStrings);
let jwtData: JWTToken = {
userId: id,
mail: "",
username: title,
firstname: "",
lastname: "",
isOwner: false,
permissions: permissionObject,
sub: "webapi_access_token",
};
let overwriteExpiration =
ms(JWT_EXPIRATION) < new Date().getTime() - new Date(expiration).getTime()
? null
: Date.now() - new Date(expiration).getTime();
return await JWTHelper.create(jwtData, { expOverwrite: overwriteExpiration, useExpiration: true })
.then((result) => {
return result;
})
.catch((err) => {
throw new InternalException("Failed webapi accessToken creation", err);
});
}
}

View file

@ -33,21 +33,12 @@ export abstract class NewsletterHelper {
private static formatJobEmit(
event: "progress" | "complete",
kind: "pdf" | "mail",
factor: "success" | "failed" | "info",
newsletterId: number,
total: number,
iteration: number,
msg: string
) {
this.jobStatus.emit<NewsletterEventType>(event, {
kind,
newsletterId,
factor,
total,
iteration,
msg,
date: new Date(),
});
this.jobStatus.emit<NewsletterEventType>(event, { kind, newsletterId, total, iteration, msg, date: new Date() });
}
public static buildData(
@ -141,7 +132,9 @@ export abstract class NewsletterHelper {
}
}
let members = await MemberService.getAll({ noLimit: true });
console.log(queryMemberIds);
let members = await MemberService.getAll(0, 1000);
return members[0].filter((m) => queryMemberIds.includes(m.id));
}
@ -178,9 +171,18 @@ export abstract class NewsletterHelper {
allowedForMail.includes(m.sendNewsletter?.type?.id)
);
this.formatJobEmit("progress", "mail", "info", newsletterId, mailRecipients.length, 0, "starting sending");
this.formatJobEmit("progress", "mail", newsletterId, mailRecipients.length, 0, "starting sending");
for (const [index, rec] of mailRecipients.entries()) {
this.formatJobEmit(
"progress",
"mail",
newsletterId,
mailRecipients.length,
index,
`start sending to ${rec.sendNewsletter.email}`
);
let data = this.buildData(newsletter, dates, rec);
const { body } = await TemplateHelper.renderFileForModule({
@ -195,10 +197,9 @@ export abstract class NewsletterHelper {
this.formatJobEmit(
"progress",
"mail",
"success",
newsletterId,
mailRecipients.length,
index + 1,
index,
`successfully sent to ${rec.sendNewsletter.email}`
);
})
@ -206,19 +207,18 @@ export abstract class NewsletterHelper {
this.formatJobEmit(
"progress",
"mail",
"failed",
newsletterId,
mailRecipients.length,
index + 1,
index,
`failed to send to ${rec.sendNewsletter.email}`
);
console.log("mail send", err);
});
}
this.formatJobEmit(
"complete",
"mail",
"info",
newsletterId,
mailRecipients.length,
mailRecipients.length,
@ -249,12 +249,21 @@ export abstract class NewsletterHelper {
(m) => !notAllowedForPdf.includes(m.sendNewsletter?.type?.id) || m.sendNewsletter == null
);
this.formatJobEmit("progress", "pdf", "info", newsletterId, pdfRecipients.length + 1, 0, "starting sending");
this.formatJobEmit("progress", "pdf", newsletterId, pdfRecipients.length, 0, "starting sending");
for (const [index, rec] of [
...pdfRecipients,
{ id: 0, firstname: "Alle Mitglieder", lastname: CLUB_NAME } as member,
].entries()) {
this.formatJobEmit(
"progress",
"pdf",
newsletterId,
pdfRecipients.length,
index,
`start print for ${rec.lastname}, ${rec.firstname}`
);
let data = this.buildData(newsletter, dates, rec, printWithAdress.includes(rec.sendNewsletter?.type?.id));
await PdfExport.renderFile({
@ -268,10 +277,9 @@ export abstract class NewsletterHelper {
this.formatJobEmit(
"progress",
"pdf",
"success",
newsletterId,
pdfRecipients.length + 1,
index + 1,
pdfRecipients.length,
index,
`successfully printed for ${rec.lastname}, ${rec.firstname}`
);
})
@ -279,15 +287,24 @@ export abstract class NewsletterHelper {
this.formatJobEmit(
"progress",
"pdf",
"failed",
newsletterId,
pdfRecipients.length + 1,
index + 1,
pdfRecipients.length,
index,
`failed print for ${rec.lastname}, ${rec.firstname}`
);
console.log("pdf print", err);
});
}
this.formatJobEmit(
"progress",
"pdf",
newsletterId,
pdfRecipients.length,
pdfRecipients.length,
"starting pdf combine"
);
await PdfExport.sqashToSingleFile(
`newsletter/${newsletter.id}_${newsletter.title.replace(" ", "")}`,
"allPdfsTogether",
@ -297,10 +314,9 @@ export abstract class NewsletterHelper {
this.formatJobEmit(
"progress",
"pdf",
"success",
newsletterId,
pdfRecipients.length + 1,
pdfRecipients.length + 1,
pdfRecipients.length,
pdfRecipients.length,
"sucessfully combined pdf"
);
})
@ -308,21 +324,20 @@ export abstract class NewsletterHelper {
this.formatJobEmit(
"progress",
"pdf",
"failed",
newsletterId,
pdfRecipients.length + 1,
pdfRecipients.length + 1,
pdfRecipients.length,
pdfRecipients.length,
"failed combining pdf"
);
console.log("pdf squash", err);
});
this.formatJobEmit(
"complete",
"pdf",
"info",
newsletterId,
pdfRecipients.length + 1,
pdfRecipients.length + 1,
pdfRecipients.length,
pdfRecipients.length,
`completed printing process`
);
}

View file

@ -89,19 +89,6 @@ export default class PermissionHelper {
};
}
static isAdminMiddleware(): (req: Request, res: Response, next: Function) => void {
return (req: Request, res: Response, next: Function) => {
const permissions = req.permissions;
const isOwner = req.isOwner;
if (isOwner || permissions.admin) {
next();
} else {
throw new ForbiddenRequestException(`missing admin permission`);
}
};
}
static convertToObject(permissions: Array<PermissionString>): PermissionObject {
if (permissions.includes("*")) {
return {

View file

@ -12,8 +12,6 @@ declare global {
username: string;
isOwner: boolean;
permissions: PermissionObject;
isPWA: boolean;
isWebApiRequest: boolean;
}
}
}

View file

@ -29,15 +29,10 @@ export default async function authenticate(req: Request, res: Response, next: Fu
throw new InternalException("process failed");
}
if (decoded?.sub == "api_token_retrieve") {
throw new BadRequestException("This token is only authorized to get temporary access tokens via GET /api/webapi");
}
req.userId = decoded.userId;
req.username = decoded.username;
req.isOwner = decoded.isOwner;
req.permissions = decoded.permissions;
req.isWebApiRequest = decoded?.sub == "webapi_access_token";
next();
}

View file

@ -1,37 +0,0 @@
import { Request, Response } from "express";
import jwt from "jsonwebtoken";
import BadRequestException from "../exceptions/badRequestException";
import UnauthorizedRequestException from "../exceptions/unauthorizedRequestException";
import InternalException from "../exceptions/internalException";
import { JWTHelper } from "../helpers/jwtHelper";
export default async function authenticateAPI(req: Request, res: Response, next: Function) {
const bearer = req.headers.authorization?.split(" ")?.[1] ?? undefined;
if (!bearer) {
throw new BadRequestException("Provide valid Authorization Header");
}
let decoded: string | jwt.JwtPayload;
await JWTHelper.validate(bearer)
.then((result) => {
decoded = result;
})
.catch((err) => {
if (err == "jwt expired") {
throw new UnauthorizedRequestException("Token expired", err);
} else {
throw new BadRequestException("Failed Authorization Header decoding", err);
}
});
if (typeof decoded == "string" || !decoded) {
throw new InternalException("process failed");
}
if (decoded?.sub != "api_token_retrieve") {
throw new BadRequestException("This route can only be accessed via a api token");
}
next();
}

View file

@ -1,11 +0,0 @@
import { Request, Response } from "express";
export default async function detectPWA(req: Request, res: Response, next: Function) {
const userAgent = req.headers["user-agent"] || "";
if ((userAgent.includes("Mobile") && userAgent.includes("Standalone")) || req.headers["x-pwa-client"] === "true") {
req.isPWA = true;
} else {
req.isPWA = false;
}
next();
}

View file

@ -1,10 +0,0 @@
import { Request, Response } from "express";
import ForbiddenRequestException from "../exceptions/forbiddenRequestException";
export default async function preventWebapiAccess(req: Request, res: Response, next: Function) {
if (req.isWebApiRequest) {
throw new ForbiddenRequestException("This route cannot be accessed via webapi");
} else {
next();
}
}

View file

@ -19,6 +19,7 @@ export class InternalId1735822722235 implements MigrationInterface {
);
// let memberships = await queryRunner.manager.getRepository(membership).find();
// console.log(memberships);
// let internalIds = memberships.reduce<{ [key: number]: Array<string> }>((acc, cur) => {
// let memberId = cur.memberId;
// let setIds = acc[memberId] ?? [];
@ -29,6 +30,7 @@ export class InternalId1735822722235 implements MigrationInterface {
// return acc;
// }, {});
// console.log(internalIds);
// for (const [id, value] of Object.entries(internalIds)) {
// const ids = value.filter((v) => v != null).join(", ");
// if (ids) {

View file

@ -1,21 +0,0 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class ProtocolPresenceExcuse1737287798828 implements MigrationInterface {
name = "ProtocolPresenceExcuse1737287798828";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
"protocol_presence",
new TableColumn({
name: "excused",
type: "tinyint",
default: "1",
isNullable: false,
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumn("protocol_presence", "excused");
}
}

View file

@ -1,55 +0,0 @@
import { MigrationInterface, QueryRunner, Table, TableForeignKey } from "typeorm";
import { DB_TYPE } from "../env.defaults";
export class AddWebapiTokens1737453096674 implements MigrationInterface {
name = "AddWebApiTokens1737453096674";
public async up(queryRunner: QueryRunner): Promise<void> {
const variableType_int = DB_TYPE == "mysql" ? "int" : "integer";
await queryRunner.createTable(
new Table({
name: "webapi",
columns: [
{ name: "id", type: variableType_int, isPrimary: true, isGenerated: true, generationStrategy: "increment" },
{ name: "token", type: "text", isUnique: true, isNullable: false },
{ name: "title", type: "varchar", isUnique: true, length: "255", isNullable: false },
{ name: "createdAt", type: "datetime", default: "CURRENT_TIMESTAMP(6)", isNullable: false },
{ name: "lastUsage", type: "datetime", isNullable: true, default: null },
{ name: "expiry", type: "date", isNullable: true, default: null },
],
}),
true
);
await queryRunner.createTable(
new Table({
name: "webapi_permission",
columns: [
{ name: "webapiId", type: variableType_int, isPrimary: true, isNullable: false },
{ name: "permission", type: "varchar", length: "255", isPrimary: true, isNullable: false },
],
}),
true
);
await queryRunner.createForeignKey(
"webapi_permission",
new TableForeignKey({
columnNames: ["webapiId"],
referencedColumnNames: ["id"],
referencedTableName: "webapi",
onDelete: "CASCADE",
onUpdate: "RESTRICT",
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
const table = await queryRunner.getTable("webapi_permission");
const foreignKey = table.foreignKeys.find((fk) => fk.columnNames.indexOf("webapiId") !== -1);
await queryRunner.dropForeignKey("webapi_permission", foreignKey);
await queryRunner.dropTable("webapi_permission");
await queryRunner.dropTable("webapi");
}
}

View file

@ -1,38 +1,36 @@
import express, { Request, Response } from "express";
import {
addAwardToMember,
addCommunicationToMember,
addExecutivePositionToMember,
addMembershipToMember,
addQualificationToMember,
createMember,
createMemberPrintoutList,
deleteAwardOfMember,
deleteCommunicationOfMember,
deleteExecutivePositionOfMember,
deleteMemberById,
deleteMembershipOfMember,
deleteQualificationOfMember,
getAllMembers,
getAwardByMemberAndRecord,
getAwardsByMember,
getCommunicationByMemberAndRecord,
getCommunicationsByMember,
getExecutivePositionByMemberAndRecord,
getExecutivePositionsByMember,
getMemberById,
getMembershipByMemberAndRecord,
getMembershipsByMember,
getMembershipStatisticsById,
getMemberStatisticsById,
getQualificationByMemberAndRecord,
getQualificationsByMember,
updateAwardOfMember,
updateCommunicationOfMember,
updateExecutivePositionOfMember,
updateMemberById,
updateMembershipOfMember,
updateQualificationOfMember,
addAwardToMember,
addCommunicationToMember,
addExecutivePositionToMember,
addMembershipToMember,
addQualificationToMember,
createMember,
createMemberPrintoutList,
deleteAwardOfMember,
deleteCommunicationOfMember,
deleteExecutivePositionOfMember,
deleteMemberById,
deleteMembershipOfMember,
deleteQualificationOfMember,
getAllMembers,
getAwardByMemberAndRecord,
getAwardsByMember,
getCommunicationByMemberAndRecord,
getCommunicationsByMember,
getExecutivePositionByMemberAndRecord,
getExecutivePositionsByMember,
getMemberById,
getMembershipByMemberAndRecord,
getMembershipsByMember,
getQualificationByMemberAndRecord,
getQualificationsByMember,
updateAwardOfMember,
updateCommunicationOfMember,
updateExecutivePositionOfMember,
updateMemberById,
updateMembershipOfMember,
updateQualificationOfMember,
} from "../../../controller/admin/club/memberController";
import PermissionHelper from "../../../helpers/permissionHelper";
@ -46,22 +44,14 @@ router.get("/:id", async (req: Request, res: Response) => {
await getMemberById(req, res);
});
router.get("/:id/statistics", async (req: Request, res: Response) => {
await getMemberStatisticsById(req, res);
});
router.get("/print/namelist", async (req: Request, res: Response) => {
await createMemberPrintoutList(req, res);
await createMemberPrintoutList(req, res);
});
router.get("/:memberId/memberships", async (req: Request, res: Response) => {
await getMembershipsByMember(req, res);
});
router.get("/:memberId/memberships/statistics", async (req: Request, res: Response) => {
await getMembershipStatisticsById(req, res);
});
router.get("/:memberId/membership/:id", async (req: Request, res: Response) => {
await getMembershipByMemberAndRecord(req, res);
});

View file

@ -21,8 +21,6 @@ import newsletter from "./club/newsletter";
import role from "./user/role";
import user from "./user/user";
import invite from "./user/invite";
import api from "./user/webapi";
import preventWebapiAccess from "../../middleware/preventWebApiAccess";
var router = express.Router({ mergeParams: true });
@ -62,6 +60,5 @@ router.use("/newsletter", PermissionHelper.passCheckMiddleware("read", "club", "
router.use("/role", PermissionHelper.passCheckMiddleware("read", "user", "role"), role);
router.use("/user", PermissionHelper.passCheckMiddleware("read", "user", "user"), user);
router.use("/invite", PermissionHelper.passCheckMiddleware("read", "user", "user"), invite);
router.use("/webapi", preventWebapiAccess, PermissionHelper.passCheckMiddleware("read", "user", "webapi"), api);
export default router;

View file

@ -1,5 +1,6 @@
import express, { Request, Response } from "express";
import {
deleteNewsletterConfig,
getAllNewsletterConfigs,
getNewsletterConfigById,
setNewsletterConfig,
@ -24,4 +25,12 @@ router.put(
}
);
router.delete(
"/:comTypeId",
PermissionHelper.passCheckMiddleware("create", "settings", "newsletter_config"),
async (req: Request, res: Response) => {
await deleteNewsletterConfig(req, res);
}
);
export default router;

View file

@ -1,64 +0,0 @@
import express, { Request, Response } from "express";
import PermissionHelper from "../../../helpers/permissionHelper";
import {
createWebapi,
deleteWebapi,
getAllWebapis,
getWebapiById,
getWebapiPermissions,
getWebapiTokenById,
updateWebapi,
updateWebapiPermissions,
} from "../../../controller/admin/user/webapiController";
var router = express.Router({ mergeParams: true });
router.get("/", async (req: Request, res: Response) => {
await getAllWebapis(req, res);
});
router.get("/:id", async (req: Request, res: Response) => {
await getWebapiById(req, res);
});
router.get("/:id/token", async (req: Request, res: Response) => {
await getWebapiTokenById(req, res);
});
router.get("/:id/permissions", async (req: Request, res: Response) => {
await getWebapiPermissions(req, res);
});
router.post(
"/",
PermissionHelper.passCheckMiddleware("create", "user", "webapi"),
async (req: Request, res: Response) => {
await createWebapi(req, res);
}
);
router.patch(
"/:id",
PermissionHelper.passCheckMiddleware("update", "user", "webapi"),
async (req: Request, res: Response) => {
await updateWebapi(req, res);
}
);
router.patch(
"/:id/permissions",
PermissionHelper.passCheckMiddleware("admin", "user", "webapi"),
async (req: Request, res: Response) => {
await updateWebapiPermissions(req, res);
}
);
router.delete(
"/:id",
PermissionHelper.passCheckMiddleware("delete", "user", "webapi"),
async (req: Request, res: Response) => {
await deleteWebapi(req, res);
}
);
export default router;

View file

@ -13,11 +13,6 @@ import reset from "./reset";
import auth from "./auth";
import admin from "./admin/index";
import user from "./user";
import detectPWA from "../middleware/detectPWA";
import api from "./webapi";
import authenticateAPI from "../middleware/authenticateAPI";
import server from "./server";
import PermissionHelper from "../helpers/permissionHelper";
export default (app: Express) => {
app.set("query parser", "extended");
@ -30,16 +25,13 @@ export default (app: Express) => {
app.use(cors());
app.options("*", cors());
app.use(detectPWA);
app.use("/api/public", publicAvailable);
app.use("/api/setup", allowSetup, setup);
app.use("/api/reset", reset);
app.use("/api/invite", invite);
app.use("/api/auth", auth);
app.use("/api/webapi", authenticateAPI, api);
app.use(authenticate);
app.use("/api/admin", admin);
app.use("/api/user", user);
app.use("/api/server", PermissionHelper.isAdminMiddleware(), server);
app.use(errorHandler);
};

View file

@ -1,35 +0,0 @@
import express, { Request, Response } from "express";
import { FileSystemHelper } from "../helpers/fileSystemHelper";
import Parser from "rss-parser";
var router = express.Router({ mergeParams: true });
router.get("/version", async (req: Request, res: Response) => {
let serverPackage = FileSystemHelper.readTemplateFile("/package.json");
let serverJson = JSON.parse(serverPackage);
res.send({
name: serverJson.name,
description: serverJson.description,
version: serverJson.version,
author: serverJson.author,
license: serverJson.license,
});
});
router.get("/settings", async (req: Request, res: Response) => {
res.json({});
});
router.get("/serverrss", async (req: Request, res: Response) => {
const parser = new Parser();
let feed = await parser.parseURL("https://forgejo.jk-effects.cloud/Ehrenamt/ff-admin-server/releases.rss");
res.json(feed);
});
router.get("/clientrss", async (req: Request, res: Response) => {
const parser = new Parser();
let feed = await parser.parseURL("https://forgejo.jk-effects.cloud/Ehrenamt/ff-admin/releases.rss");
res.json(feed);
});
export default router;

View file

@ -1,10 +0,0 @@
import express, { Request, Response } from "express";
import { getWebApiAccess } from "../controller/webapiController";
var router = express.Router({ mergeParams: true });
router.get("/retrieve", async (req: Request, res: Response) => {
await getWebApiAccess(req, res);
});
export default router;

View file

@ -12,7 +12,6 @@ export default abstract class CalendarService {
.getRepository(calendar)
.createQueryBuilder("calendar")
.leftJoinAndSelect("calendar.type", "type")
.orderBy("starttime", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -16,7 +16,6 @@ export default abstract class CommunicationService {
.leftJoinAndSelect("communication.member", "member")
.leftJoinAndSelect("member.sendNewsletter", "sendNewsletter")
.where("communication.memberId = :memberId", { memberId: memberId })
.orderBy("communicationType.type", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -14,7 +14,6 @@ export default abstract class MemberAwardService {
.createQueryBuilder("memberAwards")
.leftJoinAndSelect("memberAwards.award", "award")
.where("memberAwards.memberId = :memberId", { memberId: memberId })
.orderBy("award.award", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -14,8 +14,6 @@ export default abstract class MemberExecutivePositionService {
.createQueryBuilder("memberExecutivePositions")
.leftJoinAndSelect("memberExecutivePositions.executivePosition", "executivePosition")
.where("memberExecutivePositions.memberId = :memberId", { memberId: memberId })
.orderBy("executivePosition.position", "ASC")
.addOrderBy("memberExecutivePositions.start", "DESC")
.getMany()
.then((res) => {
return res;

View file

@ -14,7 +14,6 @@ export default abstract class MemberQualificationService {
.createQueryBuilder("memberQualifications")
.leftJoinAndSelect("memberQualifications.qualification", "qualification")
.where("memberQualifications.memberId = :memberId", { memberId: memberId })
.orderBy("qualification.qualification", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -2,26 +2,13 @@ import { dataSource } from "../../../data-source";
import { member } from "../../../entity/club/member/member";
import { membership } from "../../../entity/club/member/membership";
import InternalException from "../../../exceptions/internalException";
import { memberView } from "../../../views/memberView";
export default abstract class MemberService {
/**
* @description get all members
* @returns {Promise<[Array<member>, number]>}
*/
static async getAll({
offset = 0,
count = 25,
search = "",
noLimit = false,
ids = [],
}: {
offset?: number;
count?: number;
search?: string;
noLimit?: boolean;
ids?: Array<number>;
}): Promise<[Array<member>, number]> {
static async getAll(offset: number = 0, count: number = 25, search: string = ""): Promise<[Array<member>, number]> {
let query = dataSource
.getRepository(member)
.createQueryBuilder("member")
@ -67,15 +54,9 @@ export default abstract class MemberService {
});
}
if (ids.length != 0) {
query = query.where({ id: ids });
}
if (!noLimit) {
query = query.offset(offset).limit(count);
}
return await query
.offset(offset)
.limit(count)
.orderBy("member.lastname")
.addOrderBy("member.firstname")
.addOrderBy("member.nameaffix")
@ -133,25 +114,6 @@ export default abstract class MemberService {
});
}
/**
* @description get member statistics by id
* @param {number} id
* @returns {Promise<memberView>}
*/
static async getStatisticsById(id: number): Promise<memberView> {
return await dataSource
.getRepository(memberView)
.createQueryBuilder("memberView")
.where("memberView.id = :id", { id: id })
.getOneOrFail()
.then((res) => {
return res;
})
.catch((err) => {
throw new InternalException("memberView not found by id", err);
});
}
/**
* @description get members where membership is setz
* @returns {Promise<member>}

View file

@ -1,7 +1,6 @@
import { dataSource } from "../../../data-source";
import { membership } from "../../../entity/club/member/membership";
import InternalException from "../../../exceptions/internalException";
import { membershipView } from "../../../views/membershipsView";
export default abstract class MembershipService {
/**
@ -46,23 +45,4 @@ export default abstract class MembershipService {
throw new InternalException("member membership not found by id", err);
});
}
/**
* @description get membership statistics by memberId
* @param {number} memberId
* @returns {Promise<Array<membershipView>>}
*/
static async getStatisticsById(memberId: number): Promise<Array<membershipView>> {
return await dataSource
.getRepository(membershipView)
.createQueryBuilder("membershipView")
.where("membershipView.memberId = :memberId", { memberId: memberId })
.getMany()
.then((res) => {
return res;
})
.catch((err) => {
throw new InternalException("membershipView not found by id", err);
});
}
}

View file

@ -12,7 +12,6 @@ export default abstract class AwardService {
return await dataSource
.getRepository(award)
.createQueryBuilder("award")
.orderBy("award", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -11,7 +11,6 @@ export default abstract class CalendarTypeService {
return await dataSource
.getRepository(calendarType)
.createQueryBuilder("calendarType")
.orderBy("type", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -11,7 +11,6 @@ export default abstract class CommunicationTypeService {
return await dataSource
.getRepository(communicationType)
.createQueryBuilder("communicationType")
.orderBy("type", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -12,7 +12,6 @@ export default abstract class ExecutivePositionService {
return await dataSource
.getRepository(executivePosition)
.createQueryBuilder("executivePosition")
.orderBy("position", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -12,7 +12,6 @@ export default abstract class MembershipStatusService {
return await dataSource
.getRepository(membershipStatus)
.createQueryBuilder("membershipStatus")
.orderBy("status", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -13,7 +13,6 @@ export default abstract class NewsletterConfigService {
.getRepository(newsletterConfig)
.createQueryBuilder("newsletterConfig")
.leftJoinAndSelect("newsletterConfig.comType", "comType")
.orderBy("comType.type", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -13,7 +13,6 @@ export default abstract class QualificationService {
return await dataSource
.getRepository(qualification)
.createQueryBuilder("qualification")
.orderBy("qualification", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -11,7 +11,6 @@ export default abstract class QueryStoreService {
return await dataSource
.getRepository(query)
.createQueryBuilder("queryStore")
.orderBy("title", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -12,7 +12,6 @@ export default abstract class TemplateService {
return await dataSource
.getRepository(template)
.createQueryBuilder("template")
.orderBy("template", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -14,7 +14,6 @@ export default abstract class TemplateUsageService {
.leftJoinAndSelect("templateUsage.header", "headerTemplate")
.leftJoinAndSelect("templateUsage.body", "bodyTemplate")
.leftJoinAndSelect("templateUsage.footer", "footerTemplate")
.orderBy("scope", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -12,7 +12,6 @@ export default abstract class RoleService {
.getRepository(role)
.createQueryBuilder("role")
.leftJoinAndSelect("role.permissions", "role_permissions")
.orderBy("role", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -15,8 +15,6 @@ export default abstract class UserService {
.leftJoinAndSelect("user.roles", "roles")
.leftJoinAndSelect("user.permissions", "permissions")
.leftJoinAndSelect("roles.permissions", "role_permissions")
.orderBy("firstname", "ASC")
.addOrderBy("lastname", "ASC")
.getMany()
.then((res) => {
return res;

View file

@ -1,24 +0,0 @@
import { dataSource } from "../../data-source";
import { webapiPermission } from "../../entity/user/webapi_permission";
import InternalException from "../../exceptions/internalException";
export default abstract class WebapiPermissionService {
/**
* @description get permission by api
* @param webapiId number
* @returns {Promise<Array<webapiPermission>>}
*/
static async getByApi(webapiId: number): Promise<Array<webapiPermission>> {
return await dataSource
.getRepository(webapiPermission)
.createQueryBuilder("webapi_permission")
.where("webapi_permission.webapiId = :webapiId", { webapiId: webapiId })
.getMany()
.then((res) => {
return res;
})
.catch((err) => {
throw new InternalException("webapi permissions not found by api", err);
});
}
}

View file

@ -1,83 +0,0 @@
import { dataSource } from "../../data-source";
import { webapi } from "../../entity/user/webapi";
import InternalException from "../../exceptions/internalException";
export default abstract class WebapiService {
/**
* @description get apis
* @returns {Promise<Array<webapi>>}
*/
static async getAll(): Promise<Array<webapi>> {
return await dataSource
.getRepository(webapi)
.createQueryBuilder("webapi")
.leftJoinAndSelect("webapi.permissions", "permissions")
.getMany()
.then((res) => {
return res;
})
.catch((err) => {
throw new InternalException("webapis not found", err);
});
}
/**
* @description get api by id
* @param id number
* @returns {Promise<webapi>}
*/
static async getById(id: number): Promise<webapi> {
return await dataSource
.getRepository(webapi)
.createQueryBuilder("webapi")
.leftJoinAndSelect("webapi.permissions", "permissions")
.where("webapi.id = :id", { id: id })
.getOneOrFail()
.then((res) => {
return res;
})
.catch((err) => {
throw new InternalException("webapi not found by id", err);
});
}
/**
* @description get api by token
* @param token string
* @returns {Promise<webapi>}
*/
static async getByToken(token: string): Promise<webapi> {
return await dataSource
.getRepository(webapi)
.createQueryBuilder("webapi")
.leftJoinAndSelect("webapi.permissions", "permissions")
.where("webapi.token = :token", { token: token })
.getOneOrFail()
.then((res) => {
return res;
})
.catch((err) => {
throw new InternalException("webapi not found by token", err);
});
}
/**
* @description get api by id
* @param id number
* @returns {Promise<webapi>}
*/
static async getTokenById(id: number): Promise<webapi> {
return await dataSource
.getRepository(webapi)
.createQueryBuilder("webapi")
.select("webapi.token")
.where("webapi.id = :id", { id: id })
.getOneOrFail()
.then((res) => {
return res;
})
.catch((err) => {
throw new InternalException("webapi token not found by id", err);
});
}
}

View file

@ -14,19 +14,9 @@
<br />
<br />
<h2>Anwesenheit ({{presence.length}})</h2>
<p>
{{#each presence}}{{this.firstname}} {{this.lastname}}{{#unless @last}}, {{/unless}}{{/each}}{{#unless
presence.length}}---{{/unless}}
</p>
<p>{{#each presence}} {{this.firstname}} {{this.lastname}}{{#unless @last}}, {{/unless}} {{/each}}</p>
<h2>Abwesenheit ({{absent.length}})</h2>
<p>
entschuldigt: {{#each excused_absent}}{{this.firstname}} {{this.lastname}}{{#unless @last}},
{{/unless}}{{/each}}{{#unless excused_absent.length}}---{{/unless}}
</p>
<p>
unentschuldigt: {{#each unexcused_absent}}{{this.firstname}} {{this.lastname}}{{#unless @last}},
{{/unless}}{{/each}}{{#unless unexcused_absent.length}}---{{/unless}}
</p>
<p>{{#each absent}} {{this.firstname}} {{this.lastname}}{{#unless @last}}, {{/unless}} {{/each}}</p>
<br />
<h2>Agenda</h2>
{{#each agenda}}

View file

@ -14,7 +14,6 @@ export type PermissionModule =
| "calendar_type"
| "user"
| "role"
| "webapi"
| "query"
| "query_store"
| "template"
@ -56,7 +55,6 @@ export const permissionModules: Array<PermissionModule> = [
"calendar_type",
"user",
"role",
"webapi",
"query",
"query_store",
"template",
@ -77,5 +75,5 @@ export const sectionsAndModules: SectionsAndModulesObject = {
"template_usage",
"newsletter_config",
],
user: ["user", "role", "webapi"],
user: ["user", "role"],
};

View file

@ -16,15 +16,3 @@ export interface MemberViewModel {
smsAlarming?: Array<CommunicationViewModel>;
preferredCommunication?: Array<CommunicationViewModel>;
}
export interface MemberStatisticsViewModel {
id: number;
salutation: Salutation;
firstname: string;
lastname: string;
nameaffix: string;
birthdate: Date;
todayAge: number;
ageThisYear: number;
exactAge: string;
}

View file

@ -1,5 +1,3 @@
import { Salutation } from "../../../../enums/salutation";
export interface MembershipViewModel {
id: number;
start: Date;
@ -8,16 +6,3 @@ export interface MembershipViewModel {
status: string;
statusId: number;
}
export interface MembershipStatisticsViewModel {
durationInDays: number;
durationInYears: string;
status: string;
statusId: number;
memberId: number;
memberSalutation: Salutation;
memberFirstname: string;
memberLastname: string;
memberNameaffix: string;
memberBirthdate: Date;
}

View file

@ -3,6 +3,5 @@ import { MemberViewModel } from "../member/member.models";
export interface ProtocolPresenceViewModel {
memberId: number;
absent: boolean;
excused: boolean;
protocolId: number;
}

View file

@ -1,10 +0,0 @@
import { PermissionObject } from "../../../type/permissionTypes";
export interface ApiViewModel {
id: number;
permissions: PermissionObject;
title: string;
createdAt: Date;
lastUsage?: Date;
expiry?: Date;
}

View file

@ -43,5 +43,5 @@ export class memberView {
ageThisYear: number;
@ViewColumn()
exactAge: string;
exactAge: Date;
}

View file

@ -30,7 +30,7 @@ export class membershipView {
durationInDays: number;
@ViewColumn()
durationInYears: string;
durationInYears: Date;
@ViewColumn()
status: string;