Add invite routes to backend and frontend; implement routing and UI components for invitation management
This commit is contained in:
28
backend/create-invitation-table.sql
Normal file
28
backend/create-invitation-table.sql
Normal file
@@ -0,0 +1,28 @@
|
||||
-- SQL Script: Invitation-Tabelle erstellen
|
||||
-- Speichert gesendete Einladungen mit Spam-Schutz
|
||||
-- Ausführen mit: mysql -u root -p stechuhr < create-invitation-table.sql
|
||||
|
||||
USE stechuhr;
|
||||
|
||||
-- Erstelle Invitation-Tabelle falls nicht vorhanden
|
||||
CREATE TABLE IF NOT EXISTS invitation (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
inviter_user_id BIGINT NOT NULL,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
token VARCHAR(255) NOT NULL UNIQUE,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at DATETIME NOT NULL,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
||||
|
||||
-- Foreign Keys
|
||||
CONSTRAINT fk_invitation_user FOREIGN KEY (inviter_user_id)
|
||||
REFERENCES user(id) ON DELETE CASCADE,
|
||||
|
||||
-- Indices für Performance
|
||||
INDEX idx_invitation_token (token),
|
||||
INDEX idx_invitation_email_created (email, created_at),
|
||||
INDEX idx_invitation_status (status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
SELECT 'Invitation-Tabelle erfolgreich erstellt oder bereits vorhanden.' AS status;
|
||||
|
||||
@@ -82,6 +82,7 @@ class Database {
|
||||
const SickType = require('../models/SickType');
|
||||
const Timefix = require('../models/Timefix');
|
||||
const Timewish = require('../models/Timewish');
|
||||
const Invitation = require('../models/Invitation');
|
||||
|
||||
// Models mit Sequelize-Instanz initialisieren
|
||||
User.initialize(this.sequelize);
|
||||
@@ -98,6 +99,7 @@ class Database {
|
||||
SickType.initialize(this.sequelize);
|
||||
Timefix.initialize(this.sequelize);
|
||||
Timewish.initialize(this.sequelize);
|
||||
Invitation.initialize(this.sequelize);
|
||||
|
||||
// Assoziationen definieren
|
||||
this.defineAssociations();
|
||||
@@ -109,7 +111,7 @@ class Database {
|
||||
* Model-Assoziationen definieren
|
||||
*/
|
||||
defineAssociations() {
|
||||
const { User, Worklog, AuthInfo, AuthToken, AuthIdentity, State, WeeklyWorktime, Holiday, HolidayState, Vacation, Sick, SickType, Timefix, Timewish } = this.sequelize.models;
|
||||
const { User, Worklog, AuthInfo, AuthToken, AuthIdentity, State, WeeklyWorktime, Holiday, HolidayState, Vacation, Sick, SickType, Timefix, Timewish, Invitation } = this.sequelize.models;
|
||||
|
||||
// User Assoziationen
|
||||
User.hasMany(Worklog, { foreignKey: 'user_id', as: 'worklogs' });
|
||||
@@ -175,6 +177,10 @@ class Database {
|
||||
// Timewish Assoziationen
|
||||
Timewish.belongsTo(User, { foreignKey: 'user_id', as: 'user' });
|
||||
User.hasMany(Timewish, { foreignKey: 'user_id', as: 'timewishes' });
|
||||
|
||||
// Invitation Assoziationen
|
||||
Invitation.belongsTo(User, { foreignKey: 'inviter_user_id', as: 'inviter' });
|
||||
User.hasMany(Invitation, { foreignKey: 'inviter_user_id', as: 'invitations' });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
63
backend/src/controllers/InviteController.js
Normal file
63
backend/src/controllers/InviteController.js
Normal file
@@ -0,0 +1,63 @@
|
||||
const InviteService = require('../services/InviteService');
|
||||
|
||||
/**
|
||||
* Controller für Einladungen
|
||||
* Verarbeitet HTTP-Requests und delegiert an InviteService
|
||||
*/
|
||||
class InviteController {
|
||||
/**
|
||||
* Sendet eine Einladung
|
||||
*/
|
||||
async sendInvite(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 invitation = await InviteService.sendInvite(userId, email);
|
||||
res.status(201).json(invitation);
|
||||
} catch (error) {
|
||||
console.error('Fehler beim Senden der Einladung:', error);
|
||||
|
||||
// Spezifische Fehlermeldungen
|
||||
if (error.message.includes('bereits eingeladen')) {
|
||||
return res.status(429).json({ message: error.message }); // Too Many Requests
|
||||
}
|
||||
|
||||
if (error.message.includes('bereits registriert')) {
|
||||
return res.status(409).json({ message: error.message }); // Conflict
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
message: error.message || 'Fehler beim Senden der Einladung'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Holt alle Einladungen des aktuellen Users
|
||||
*/
|
||||
async getMyInvitations(req, res) {
|
||||
try {
|
||||
const userId = req.user?.id || 1;
|
||||
const activeOnly = req.query.activeOnly === 'true';
|
||||
|
||||
const invitations = await InviteService.getUserInvitations(userId, activeOnly);
|
||||
res.json(invitations);
|
||||
} catch (error) {
|
||||
console.error('Fehler beim Abrufen der Einladungen:', error);
|
||||
res.status(500).json({
|
||||
message: 'Fehler beim Abrufen der Einladungen',
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new InviteController();
|
||||
|
||||
@@ -106,6 +106,10 @@ app.use('/api/timewish', authenticateToken, timewishRouter);
|
||||
const rolesRouter = require('./routes/roles');
|
||||
app.use('/api/roles', authenticateToken, rolesRouter);
|
||||
|
||||
// Invite routes (geschützt) - MIT ID-Hashing
|
||||
const inviteRouter = require('./routes/invite');
|
||||
app.use('/api/invite', authenticateToken, inviteRouter);
|
||||
|
||||
// Error handling middleware
|
||||
app.use((err, req, res, next) => {
|
||||
console.error(err.stack);
|
||||
|
||||
83
backend/src/models/Invitation.js
Normal file
83
backend/src/models/Invitation.js
Normal file
@@ -0,0 +1,83 @@
|
||||
const { Model, DataTypes } = require('sequelize');
|
||||
|
||||
/**
|
||||
* Invitation Model
|
||||
* Repräsentiert die invitation-Tabelle (falls vorhanden)
|
||||
* Wenn nicht vorhanden, erstellen wir eine einfache In-Memory-Lösung
|
||||
*/
|
||||
class Invitation extends Model {
|
||||
static initialize(sequelize) {
|
||||
Invitation.init(
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.BIGINT,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false
|
||||
},
|
||||
inviter_user_id: {
|
||||
type: DataTypes.BIGINT,
|
||||
allowNull: false,
|
||||
references: {
|
||||
model: 'user',
|
||||
key: 'id'
|
||||
}
|
||||
},
|
||||
email: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: false
|
||||
},
|
||||
token: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: false,
|
||||
unique: true
|
||||
},
|
||||
created_at: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: DataTypes.NOW
|
||||
},
|
||||
expires_at: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: false
|
||||
},
|
||||
status: {
|
||||
type: DataTypes.STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending' // pending, accepted, expired
|
||||
}
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
tableName: 'invitation',
|
||||
timestamps: false,
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_invitation_token',
|
||||
fields: ['token'],
|
||||
unique: true
|
||||
},
|
||||
{
|
||||
name: 'idx_invitation_email_created',
|
||||
fields: ['email', 'created_at']
|
||||
}
|
||||
]
|
||||
}
|
||||
);
|
||||
|
||||
return Invitation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Definiert Assoziationen mit anderen Models
|
||||
*/
|
||||
static associate(models) {
|
||||
Invitation.belongsTo(models.User, {
|
||||
foreignKey: 'inviter_user_id',
|
||||
as: 'inviter'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Invitation;
|
||||
|
||||
@@ -15,6 +15,7 @@ const Sick = require('./Sick');
|
||||
const SickType = require('./SickType');
|
||||
const Timefix = require('./Timefix');
|
||||
const Timewish = require('./Timewish');
|
||||
const Invitation = require('./Invitation');
|
||||
|
||||
module.exports = {
|
||||
User,
|
||||
@@ -28,6 +29,7 @@ module.exports = {
|
||||
Sick,
|
||||
SickType,
|
||||
Timefix,
|
||||
Timewish
|
||||
Timewish,
|
||||
Invitation
|
||||
};
|
||||
|
||||
|
||||
16
backend/src/routes/invite.js
Normal file
16
backend/src/routes/invite.js
Normal file
@@ -0,0 +1,16 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const InviteController = require('../controllers/InviteController');
|
||||
|
||||
/**
|
||||
* Routen für Einladungen
|
||||
*/
|
||||
|
||||
// GET /api/invite - Eigene Einladungen abrufen
|
||||
router.get('/', InviteController.getMyInvitations.bind(InviteController));
|
||||
|
||||
// POST /api/invite - Neue Einladung senden
|
||||
router.post('/', InviteController.sendInvite.bind(InviteController));
|
||||
|
||||
module.exports = router;
|
||||
|
||||
195
backend/src/services/InviteService.js
Normal file
195
backend/src/services/InviteService.js
Normal file
@@ -0,0 +1,195 @@
|
||||
const database = require('../config/database');
|
||||
const { Op } = require('sequelize');
|
||||
const nodemailer = require('nodemailer');
|
||||
|
||||
/**
|
||||
* Service-Klasse für Einladungen
|
||||
* Verwaltet Einladungs-Emails mit Spam-Schutz
|
||||
*/
|
||||
class InviteService {
|
||||
constructor() {
|
||||
this.emailTransporter = null;
|
||||
this.initializeEmailTransporter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialisiert den Email-Transporter
|
||||
*/
|
||||
initializeEmailTransporter() {
|
||||
if (!process.env.EMAIL_HOST) {
|
||||
console.warn('⚠️ Email-Konfiguration fehlt - Einladungen können nicht versendet werden');
|
||||
return;
|
||||
}
|
||||
|
||||
this.emailTransporter = nodemailer.createTransport({
|
||||
host: process.env.EMAIL_HOST,
|
||||
port: parseInt(process.env.EMAIL_PORT) || 587,
|
||||
secure: process.env.EMAIL_SECURE === 'true',
|
||||
auth: {
|
||||
user: process.env.EMAIL_USER,
|
||||
pass: process.env.EMAIL_PASSWORD
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sendet eine Einladungs-Email
|
||||
* @param {number} inviterUserId - ID des einladenden Users
|
||||
* @param {string} inviteeEmail - Email-Adresse des Eingeladenen
|
||||
* @returns {Promise<Object>} Einladungs-Info
|
||||
*/
|
||||
async sendInvite(inviterUserId, inviteeEmail) {
|
||||
const { User, Invitation } = database.getModels();
|
||||
|
||||
// Validiere Email
|
||||
if (!inviteeEmail || !this._isValidEmail(inviteeEmail)) {
|
||||
throw new Error('Ungültige Email-Adresse');
|
||||
}
|
||||
|
||||
// Hole einladenden User
|
||||
const inviter = await User.findByPk(inviterUserId);
|
||||
if (!inviter) {
|
||||
throw new Error('Benutzer nicht gefunden');
|
||||
}
|
||||
|
||||
// Spam-Schutz: Prüfe ob diese Email heute schon eingeladen wurde
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
const existingInvite = await Invitation.findOne({
|
||||
where: {
|
||||
email: inviteeEmail,
|
||||
created_at: {
|
||||
[Op.gte]: today
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (existingInvite) {
|
||||
throw new Error('Diese Email-Adresse wurde heute bereits eingeladen. Bitte versuchen Sie es morgen erneut.');
|
||||
}
|
||||
|
||||
// Prüfe ob Email bereits registriert ist
|
||||
const { AuthInfo } = database.getModels();
|
||||
const existingUser = await AuthInfo.findOne({
|
||||
where: { email: inviteeEmail }
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
throw new Error('Diese Email-Adresse ist bereits registriert');
|
||||
}
|
||||
|
||||
// Erstelle Einladungs-Token
|
||||
const token = this._generateToken();
|
||||
const expiresAt = new Date();
|
||||
expiresAt.setDate(expiresAt.getDate() + 7); // 7 Tage gültig
|
||||
|
||||
// Speichere Einladung
|
||||
const invitation = await Invitation.create({
|
||||
inviter_user_id: inviterUserId,
|
||||
email: inviteeEmail,
|
||||
token,
|
||||
expires_at: expiresAt,
|
||||
created_at: new Date(),
|
||||
status: 'pending'
|
||||
});
|
||||
|
||||
// Sende Email (falls konfiguriert)
|
||||
if (this.emailTransporter) {
|
||||
await this._sendInviteEmail(inviteeEmail, inviter.full_name, token);
|
||||
} else {
|
||||
console.warn('⚠️ Email-Transporter nicht konfiguriert - Einladung wurde gespeichert, aber keine Email versendet');
|
||||
}
|
||||
|
||||
return {
|
||||
id: invitation.id,
|
||||
email: inviteeEmail,
|
||||
token,
|
||||
expiresAt,
|
||||
status: 'sent'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Holt alle Einladungen eines Users (optional: nur aktive)
|
||||
* @param {number} userId - User-ID
|
||||
* @param {boolean} activeOnly - Nur aktive (nicht abgelaufene) Einladungen
|
||||
* @returns {Promise<Array>} Array von Einladungen
|
||||
*/
|
||||
async getUserInvitations(userId, activeOnly = false) {
|
||||
const { Invitation } = database.getModels();
|
||||
|
||||
const where = {
|
||||
inviter_user_id: userId
|
||||
};
|
||||
|
||||
if (activeOnly) {
|
||||
where.expires_at = { [Op.gt]: new Date() };
|
||||
where.status = 'pending';
|
||||
}
|
||||
|
||||
const invitations = await Invitation.findAll({
|
||||
where,
|
||||
order: [['created_at', 'DESC']],
|
||||
raw: true
|
||||
});
|
||||
|
||||
return invitations.map(inv => ({
|
||||
id: inv.id,
|
||||
email: inv.email,
|
||||
createdAt: inv.created_at,
|
||||
expiresAt: inv.expires_at,
|
||||
status: inv.status,
|
||||
isExpired: new Date() > new Date(inv.expires_at)
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Validiert Email-Format
|
||||
*/
|
||||
_isValidEmail(email) {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generiert einen zufälligen Token
|
||||
*/
|
||||
_generateToken() {
|
||||
return require('crypto').randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sendet die Einladungs-Email
|
||||
*/
|
||||
async _sendInviteEmail(toEmail, inviterName, token) {
|
||||
const appUrl = process.env.APP_URL || 'http://localhost:5010';
|
||||
const registerUrl = `${appUrl}/register?token=${token}`;
|
||||
|
||||
const mailOptions = {
|
||||
from: process.env.EMAIL_FROM || process.env.EMAIL_USER,
|
||||
to: toEmail,
|
||||
subject: 'Einladung zur Stechuhr - Zeiterfassungssystem',
|
||||
html: `
|
||||
<h2>Einladung zur Stechuhr</h2>
|
||||
<p>Hallo,</p>
|
||||
<p><strong>${inviterName}</strong> hat Sie eingeladen, die Stechuhr-Zeiterfassung zu nutzen.</p>
|
||||
<p>Klicken Sie auf den folgenden Link, um Ihren Account zu erstellen:</p>
|
||||
<p><a href="${registerUrl}" style="display: inline-block; padding: 12px 24px; background: #4CAF50; color: white; text-decoration: none; border-radius: 4px;">Account erstellen</a></p>
|
||||
<p>Oder kopieren Sie diesen Link in Ihren Browser:</p>
|
||||
<p style="word-break: break-all; color: #666;">${registerUrl}</p>
|
||||
<p><small>Diese Einladung ist 7 Tage gültig.</small></p>
|
||||
<hr>
|
||||
<p style="color: #999; font-size: 12px;">
|
||||
Wenn Sie diese Einladung nicht erwartet haben, können Sie diese Email ignorieren.
|
||||
</p>
|
||||
`
|
||||
};
|
||||
|
||||
await this.emailTransporter.sendMail(mailOptions);
|
||||
console.log(`✉️ Einladungs-Email an ${toEmail} versendet`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new InviteService();
|
||||
|
||||
Reference in New Issue
Block a user