Add watcher routes to backend and frontend; implement routing and UI components for watcher management

This commit is contained in:
Torsten Schulz (local)
2025-10-17 23:50:25 +02:00
parent c7a0316ca0
commit ac3720fb61
12 changed files with 750 additions and 10 deletions

View File

@@ -0,0 +1,28 @@
-- SQL Script: Watcher-Tabelle erstellen
-- Speichert Email-Adressen, die die Arbeitszeiten eines Users sehen dürfen
-- Ausführen mit: mysql -u root -p stechuhr < create-watcher-table.sql
USE stechuhr;
-- Erstelle Watcher-Tabelle falls nicht vorhanden
CREATE TABLE IF NOT EXISTS watcher (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL COMMENT 'User dessen Arbeitszeiten gesehen werden dürfen',
watcher_email VARCHAR(255) NOT NULL COMMENT 'Email-Adresse der berechtigten Person',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
-- Foreign Keys
CONSTRAINT fk_watcher_user FOREIGN KEY (user_id)
REFERENCES user(id) ON DELETE CASCADE,
-- Indices für Performance
INDEX idx_watcher_user (user_id),
INDEX idx_watcher_email (watcher_email),
-- Unique constraint: Ein Watcher pro User/Email-Kombination
UNIQUE KEY idx_watcher_user_email (user_id, watcher_email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SELECT 'Watcher-Tabelle erfolgreich erstellt oder bereits vorhanden.' AS status;

View File

@@ -83,6 +83,7 @@ class Database {
const Timefix = require('../models/Timefix'); const Timefix = require('../models/Timefix');
const Timewish = require('../models/Timewish'); const Timewish = require('../models/Timewish');
const Invitation = require('../models/Invitation'); const Invitation = require('../models/Invitation');
const Watcher = require('../models/Watcher');
// Models mit Sequelize-Instanz initialisieren // Models mit Sequelize-Instanz initialisieren
User.initialize(this.sequelize); User.initialize(this.sequelize);
@@ -100,6 +101,7 @@ class Database {
Timefix.initialize(this.sequelize); Timefix.initialize(this.sequelize);
Timewish.initialize(this.sequelize); Timewish.initialize(this.sequelize);
Invitation.initialize(this.sequelize); Invitation.initialize(this.sequelize);
Watcher.initialize(this.sequelize);
// Assoziationen definieren // Assoziationen definieren
this.defineAssociations(); this.defineAssociations();
@@ -111,7 +113,7 @@ class Database {
* Model-Assoziationen definieren * Model-Assoziationen definieren
*/ */
defineAssociations() { defineAssociations() {
const { User, Worklog, AuthInfo, AuthToken, AuthIdentity, State, WeeklyWorktime, Holiday, HolidayState, Vacation, Sick, SickType, Timefix, Timewish, Invitation } = this.sequelize.models; const { User, Worklog, AuthInfo, AuthToken, AuthIdentity, State, WeeklyWorktime, Holiday, HolidayState, Vacation, Sick, SickType, Timefix, Timewish, Invitation, Watcher } = this.sequelize.models;
// User Assoziationen // User Assoziationen
User.hasMany(Worklog, { foreignKey: 'user_id', as: 'worklogs' }); User.hasMany(Worklog, { foreignKey: 'user_id', as: 'worklogs' });
@@ -181,6 +183,10 @@ class Database {
// Invitation Assoziationen // Invitation Assoziationen
Invitation.belongsTo(User, { foreignKey: 'inviter_user_id', as: 'inviter' }); Invitation.belongsTo(User, { foreignKey: 'inviter_user_id', as: 'inviter' });
User.hasMany(Invitation, { foreignKey: 'inviter_user_id', as: 'invitations' }); User.hasMany(Invitation, { foreignKey: 'inviter_user_id', as: 'invitations' });
// Watcher Assoziationen
Watcher.belongsTo(User, { foreignKey: 'user_id', as: 'user' });
User.hasMany(Watcher, { foreignKey: 'user_id', as: 'watchers' });
} }
/** /**

View File

@@ -0,0 +1,73 @@
const WatcherService = require('../services/WatcherService');
/**
* Controller für Watcher (Berechtigungen)
* Verarbeitet HTTP-Requests und delegiert an WatcherService
*/
class WatcherController {
/**
* Holt alle Watcher des aktuellen Users
*/
async getWatchers(req, res) {
try {
const userId = req.user?.id || 1;
const watchers = await WatcherService.getWatchers(userId);
res.json(watchers);
} catch (error) {
console.error('Fehler beim Abrufen der Beobachter:', error);
res.status(500).json({
message: 'Fehler beim Abrufen der Beobachter',
error: error.message
});
}
}
/**
* Fügt einen Watcher hinzu
*/
async addWatcher(req, res) {
try {
const userId = req.user?.id || 1;
const { email } = req.body;
if (!email) {
return res.status(400).json({
message: 'Email-Adresse ist erforderlich'
});
}
const watcher = await WatcherService.addWatcher(userId, email);
res.status(201).json(watcher);
} catch (error) {
console.error('Fehler beim Hinzufügen des Beobachters:', error);
res.status(error.message.includes('bereits eingetragen') ? 409 : 500).json({
message: error.message
});
}
}
/**
* Entfernt einen Watcher
*/
async removeWatcher(req, res) {
try {
const userId = req.user?.id || 1;
const watcherId = parseInt(req.params.id);
if (isNaN(watcherId)) {
return res.status(400).json({ message: 'Ungültige ID' });
}
await WatcherService.removeWatcher(userId, watcherId);
res.json({ message: 'Beobachter entfernt' });
} catch (error) {
console.error('Fehler beim Entfernen des Beobachters:', error);
res.status(error.message.includes('nicht gefunden') ? 404 : 500).json({
message: error.message
});
}
}
}
module.exports = new WatcherController();

View File

@@ -110,6 +110,10 @@ app.use('/api/roles', authenticateToken, rolesRouter);
const inviteRouter = require('./routes/invite'); const inviteRouter = require('./routes/invite');
app.use('/api/invite', authenticateToken, inviteRouter); app.use('/api/invite', authenticateToken, inviteRouter);
// Watcher routes (geschützt) - MIT ID-Hashing
const watcherRouter = require('./routes/watcher');
app.use('/api/watcher', authenticateToken, watcherRouter);
// Error handling middleware // Error handling middleware
app.use((err, req, res, next) => { app.use((err, req, res, next) => {
console.error(err.stack); console.error(err.stack);

View File

@@ -0,0 +1,79 @@
const { Model, DataTypes } = require('sequelize');
/**
* Watcher Model
* Repräsentiert Personen, die die Arbeitszeiten eines Users sehen dürfen
*/
class Watcher extends Model {
static initialize(sequelize) {
Watcher.init(
{
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
user_id: {
type: DataTypes.BIGINT,
allowNull: false,
references: {
model: 'user',
key: 'id'
},
comment: 'Der User dessen Arbeitszeiten gesehen werden dürfen'
},
watcher_email: {
type: DataTypes.STRING(255),
allowNull: false,
comment: 'Email-Adresse der Person, die sehen darf'
},
created_at: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
}
},
{
sequelize,
tableName: 'watcher',
timestamps: false,
indexes: [
{
name: 'idx_watcher_user',
fields: ['user_id']
},
{
name: 'idx_watcher_email',
fields: ['watcher_email']
},
{
name: 'idx_watcher_user_email',
fields: ['user_id', 'watcher_email'],
unique: true
}
]
}
);
return Watcher;
}
/**
* Definiert Assoziationen mit anderen Models
*/
static associate(models) {
Watcher.belongsTo(models.User, {
foreignKey: 'user_id',
as: 'user'
});
}
}
module.exports = Watcher;

View File

@@ -16,6 +16,7 @@ const SickType = require('./SickType');
const Timefix = require('./Timefix'); const Timefix = require('./Timefix');
const Timewish = require('./Timewish'); const Timewish = require('./Timewish');
const Invitation = require('./Invitation'); const Invitation = require('./Invitation');
const Watcher = require('./Watcher');
module.exports = { module.exports = {
User, User,
@@ -30,6 +31,7 @@ module.exports = {
SickType, SickType,
Timefix, Timefix,
Timewish, Timewish,
Invitation Invitation,
Watcher
}; };

View File

@@ -0,0 +1,20 @@
const express = require('express');
const router = express.Router();
const WatcherController = require('../controllers/WatcherController');
const unhashRequestIds = require('../middleware/unhashRequest');
/**
* Routen für Watcher (Berechtigungen)
*/
// GET /api/watcher - Alle Watcher abrufen
router.get('/', WatcherController.getWatchers.bind(WatcherController));
// POST /api/watcher - Neuen Watcher hinzufügen
router.post('/', WatcherController.addWatcher.bind(WatcherController));
// DELETE /api/watcher/:id - Watcher entfernen
router.delete('/:id', unhashRequestIds, WatcherController.removeWatcher.bind(WatcherController));
module.exports = router;

View File

@@ -0,0 +1,139 @@
const database = require('../config/database');
/**
* Service-Klasse für Watcher (Berechtigungen)
* Verwaltet, wer die Arbeitszeiten eines Users sehen darf
*/
class WatcherService {
/**
* Holt alle Watcher eines Users
* @param {number} userId - User-ID
* @returns {Promise<Array>} Array von Watchern
*/
async getWatchers(userId) {
const { Watcher } = database.getModels();
const watchers = await Watcher.findAll({
where: {
user_id: userId,
is_active: true
},
order: [['created_at', 'DESC']],
raw: true
});
return watchers.map(w => ({
id: w.id,
email: w.watcher_email,
createdAt: w.created_at ? new Date(w.created_at).toISOString() : null
}));
}
/**
* Fügt einen Watcher hinzu
* @param {number} userId - User-ID
* @param {string} watcherEmail - Email-Adresse des Watchers
* @returns {Promise<Object>} Erstellter Watcher
*/
async addWatcher(userId, watcherEmail) {
const { Watcher } = database.getModels();
// Validiere Email
if (!watcherEmail || !this._isValidEmail(watcherEmail)) {
throw new Error('Ungültige Email-Adresse');
}
// Prüfe ob bereits existiert
const existing = await Watcher.findOne({
where: {
user_id: userId,
watcher_email: watcherEmail
}
});
if (existing) {
if (existing.is_active) {
throw new Error('Diese Email-Adresse ist bereits als Beobachter eingetragen');
} else {
// Reaktiviere inaktiven Watcher
existing.is_active = true;
await existing.save();
return {
id: existing.id,
email: existing.watcher_email,
createdAt: existing.created_at
};
}
}
// Erstelle neuen Watcher
const watcher = await Watcher.create({
user_id: userId,
watcher_email: watcherEmail,
is_active: true,
created_at: new Date()
});
return {
id: watcher.id,
email: watcher.watcher_email,
createdAt: watcher.created_at
};
}
/**
* Entfernt einen Watcher (soft delete)
* @param {number} userId - User-ID
* @param {number} watcherId - Watcher-ID
* @returns {Promise<void>}
*/
async removeWatcher(userId, watcherId) {
const { Watcher } = database.getModels();
const watcher = await Watcher.findByPk(watcherId);
if (!watcher) {
throw new Error('Beobachter nicht gefunden');
}
// Prüfe Berechtigung
if (watcher.user_id !== userId) {
throw new Error('Keine Berechtigung für diesen Eintrag');
}
// Soft delete: Setze is_active auf false
watcher.is_active = false;
await watcher.save();
}
/**
* Prüft ob eine Email die Arbeitszeiten eines Users sehen darf
* @param {number} userId - User-ID
* @param {string} watcherEmail - Email-Adresse des Watchers
* @returns {Promise<boolean>} True wenn berechtigt
*/
async canWatch(userId, watcherEmail) {
const { Watcher } = database.getModels();
const watcher = await Watcher.findOne({
where: {
user_id: userId,
watcher_email: watcherEmail,
is_active: true
}
});
return !!watcher;
}
/**
* Validiert Email-Format
*/
_isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
}
module.exports = new WatcherService();

View File

@@ -78,6 +78,7 @@ const pageTitle = computed(() => {
'settings-password': 'Passwort ändern', 'settings-password': 'Passwort ändern',
'settings-timewish': 'Zeitwünsche', 'settings-timewish': 'Zeitwünsche',
'settings-invite': 'Einladen', 'settings-invite': 'Einladen',
'settings-permissions': 'Berechtigungen',
'entries': 'Einträge', 'entries': 'Einträge',
'stats': 'Statistiken' 'stats': 'Statistiken'
} }

View File

@@ -69,14 +69,6 @@ const SECTIONS_USER = [
{ label: 'Kalender', to: '/calendar' } { label: 'Kalender', to: '/calendar' }
] ]
}, },
{
title: 'Andere Nutzer',
hasDropdown: true,
items: [
{ label: 'Liste mit Nutzernamen', to: '/users' },
{ label: 'Berechtigungen verteilen', to: '/users/permissions' }
]
},
{ {
title: 'Export', title: 'Export',
hasDropdown: false, hasDropdown: false,
@@ -89,6 +81,7 @@ const SECTIONS_USER = [
{ label: 'Persönliches', to: '/settings/profile' }, { label: 'Persönliches', to: '/settings/profile' },
{ label: 'Paßwort ändern', to: '/settings/password' }, { label: 'Paßwort ändern', to: '/settings/password' },
{ label: 'Zeitwünsche', to: '/settings/timewish' }, { label: 'Zeitwünsche', to: '/settings/timewish' },
{ label: 'Zugriffe verwalten', to: '/settings/permissions' },
{ label: 'Einladen', to: '/settings/invite' } { label: 'Einladen', to: '/settings/invite' }
] ]
} }

View File

@@ -21,6 +21,7 @@ import PasswordChange from '../views/PasswordChange.vue'
import Timewish from '../views/Timewish.vue' import Timewish from '../views/Timewish.vue'
import Roles from '../views/Roles.vue' import Roles from '../views/Roles.vue'
import Invite from '../views/Invite.vue' import Invite from '../views/Invite.vue'
import Permissions from '../views/Permissions.vue'
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@@ -133,6 +134,12 @@ const router = createRouter({
component: Invite, component: Invite,
meta: { requiresAuth: true } meta: { requiresAuth: true }
}, },
{
path: '/settings/permissions',
name: 'settings-permissions',
component: Permissions,
meta: { requiresAuth: true }
},
{ {
path: '/entries', path: '/entries',
name: 'entries', name: 'entries',

View File

@@ -0,0 +1,388 @@
<template>
<div class="permissions-page">
<div class="card">
<!-- Informationstext -->
<div class="info-box">
<h3>Arbeitszeiten teilen</h3>
<p>
Hier können Sie Email-Adressen eintragen, die berechtigt sind, Ihre aktuellen Arbeitszeiten
und Ihr voraussichtliches Arbeitsende zu sehen. Dies ist nützlich, wenn Familie oder Freunde
wissen möchten, wann Sie mit der Arbeit fertig sind.
</p>
</div>
<!-- Formular zum Hinzufügen eines Beobachters -->
<form @submit.prevent="addWatcher" class="watcher-form">
<div class="form-row">
<div class="form-group">
<label for="email">Email-Adresse hinzufügen</label>
<input
type="email"
id="email"
v-model="form.email"
placeholder="name@beispiel.de"
required
>
</div>
<div class="form-group button-group">
<button type="submit" class="btn btn-primary" :disabled="loading">
{{ loading ? 'Wird hinzugefügt...' : 'Hinzufügen' }}
</button>
</div>
</div>
</form>
<hr>
<!-- Tabelle mit berechtigten Personen -->
<h3>Berechtigte Personen</h3>
<table class="watchers-table">
<thead>
<tr>
<th>Email-Adresse</th>
<th>Hinzugefügt am</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-if="watchers.length === 0">
<td colspan="3" class="no-data">
Keine berechtigten Personen eingetragen
</td>
</tr>
<tr v-for="watcher in watchers" :key="watcher.id">
<td>{{ watcher.email }}</td>
<td>{{ formatDateTime(watcher.createdAt) }}</td>
<td>
<button
@click="removeWatcher(watcher.id, watcher.email)"
class="btn btn-delete-small"
:disabled="loading"
>
×
</button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Modal-Komponente -->
<Modal
v-if="showModal"
:show="showModal"
:title="modalConfig.title"
:message="modalConfig.message"
:type="modalConfig.type"
:confirmText="modalConfig.confirmText"
:cancelText="modalConfig.cancelText"
@confirm="onConfirm"
@cancel="onCancel"
/>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../stores/authStore'
import { useModal } from '../composables/useModal'
import Modal from '../components/Modal.vue'
const authStore = useAuthStore()
const watchers = ref([])
const loading = ref(false)
const { showModal, modalConfig, alert, confirm, onConfirm, onCancel } = useModal()
const form = ref({
email: ''
})
// Lade alle Watcher
async function loadWatchers() {
try {
const response = await fetch('http://localhost:3010/api/watcher', {
headers: {
'Authorization': `Bearer ${authStore.token}`
}
})
if (!response.ok) {
throw new Error('Fehler beim Laden der Berechtigungen')
}
watchers.value = await response.json()
} catch (error) {
console.error('Fehler beim Laden der Berechtigungen:', error)
await alert(`Fehler: ${error.message}`, 'Fehler')
}
}
// Füge Watcher hinzu
async function addWatcher() {
if (!form.value.email) {
await alert('Bitte geben Sie eine Email-Adresse ein', 'Fehlende Angaben')
return
}
try {
loading.value = true
const response = await fetch('http://localhost:3010/api/watcher', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authStore.token}`
},
body: JSON.stringify({
email: form.value.email
})
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.message || 'Fehler beim Hinzufügen der Berechtigung')
}
await alert('Berechtigung erfolgreich hinzugefügt', 'Erfolg')
// Formular zurücksetzen
form.value.email = ''
// Liste neu laden
await loadWatchers()
} catch (error) {
console.error('Fehler beim Hinzufügen der Berechtigung:', error)
await alert(`Fehler: ${error.message}`, 'Fehler')
} finally {
loading.value = false
}
}
// Entferne Watcher
async function removeWatcher(id, email) {
const confirmed = await confirm(
`Möchten Sie die Berechtigung für ${email} wirklich entfernen?`,
'Berechtigung entfernen'
)
if (!confirmed) {
return
}
try {
loading.value = true
const response = await fetch(`http://localhost:3010/api/watcher/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${authStore.token}`
}
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.message || 'Fehler beim Entfernen der Berechtigung')
}
await loadWatchers()
} catch (error) {
console.error('Fehler beim Entfernen der Berechtigung:', error)
await alert(`Fehler: ${error.message}`, 'Fehler')
} finally {
loading.value = false
}
}
// Formatiere Datum und Zeit
function formatDateTime(dateStr) {
if (!dateStr) return ''
// Prüfe ob dateStr bereits ein Date-Objekt ist
const date = dateStr instanceof Date ? dateStr : new Date(dateStr)
// Prüfe auf ungültiges Datum
if (isNaN(date.getTime())) {
console.error('Ungültiges Datum:', dateStr)
return '—'
}
return date.toLocaleString('de-DE', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
}
// Initiales Laden
onMounted(() => {
loadWatchers()
})
</script>
<style scoped>
.permissions-page {
max-width: 900px;
margin: 0 auto;
padding: 20px;
}
.card {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.info-box {
background: #e8f5e9;
border: 1px solid #c8e6c9;
border-radius: 4px;
padding: 16px;
margin-bottom: 24px;
}
.info-box h3 {
margin: 0 0 8px 0;
font-size: 16px;
color: #2e7d32;
}
.info-box p {
margin: 0;
font-size: 13px;
color: #1b5e20;
line-height: 1.6;
}
.watcher-form {
margin-bottom: 16px;
}
.form-row {
display: flex;
gap: 16px;
align-items: flex-end;
}
.form-group {
flex: 1;
display: flex;
flex-direction: column;
gap: 6px;
}
.form-group.button-group {
flex: 0 0 auto;
}
.form-group label {
font-weight: 600;
font-size: 14px;
color: #333;
}
.form-group input {
padding: 10px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
font-family: inherit;
}
.form-group input:focus {
outline: none;
border-color: #4CAF50;
box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
}
hr {
border: none;
border-top: 1px solid #eee;
margin: 20px 0;
}
h3 {
margin: 0 0 12px 0;
font-size: 16px;
color: #333;
}
.watchers-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.watchers-table th {
text-align: left;
padding: 10px 8px;
background: #f5f5f5;
border-bottom: 2px solid #ddd;
font-weight: 600;
font-size: 12px;
color: #666;
}
.watchers-table th:last-child {
width: 40px;
}
.watchers-table td {
padding: 10px 8px;
border-bottom: 1px solid #eee;
}
.watchers-table tbody tr:hover {
background: #f9f9f9;
}
.no-data {
text-align: center;
color: #999;
font-style: italic;
padding: 20px !important;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
font-family: inherit;
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-primary {
background: linear-gradient(135deg, #4CAF50, #45a049);
color: white;
box-shadow: 0 2px 4px rgba(76, 175, 80, 0.3);
}
.btn-primary:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(76, 175, 80, 0.4);
}
.btn-delete-small {
background: #f44336;
color: white;
padding: 4px 8px;
font-size: 16px;
line-height: 1;
border-radius: 3px;
}
.btn-delete-small:hover:not(:disabled) {
background: #da190b;
}
</style>