ach ich weiß nicht

This commit is contained in:
philipredstone
2025-04-17 13:06:50 +02:00
parent 56c0867a20
commit e60ec9248d
61 changed files with 2538 additions and 2323 deletions

View File

@ -0,0 +1,243 @@
import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import User, { IUser } from '../models/user.model';
import Network from '../models/network.model';
import Person from '../models/person.model';
import Relationship from '../models/relationship.model';
import { UserRequest } from '../../frontend/types/express';
import { validationResult } from 'express-validator';
import mongoose from 'mongoose';
// JWT secret from environment variables
const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_key_change_this';
// Token expiration (1 day)
const TOKEN_EXPIRY = '1d';
// Generate JWT token
const generateToken = (user: IUser): string => {
return jwt.sign({ id: user._id }, JWT_SECRET, {
expiresIn: TOKEN_EXPIRY,
});
};
// Set cookie with JWT token
const setTokenCookie = (res: Response, token: string): void => {
// Cookie options
const options = {
expires: new Date(Date.now() + 24 * 60 * 60 * 1000), // 1 day
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
};
res.cookie('token', token, options);
};
// Register a new user
export const register = async (req: Request, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
if (!process.env.ENABLE_REGISTRATION) {
res.status(400).json({ message: 'Registration is disabled' });
return;
}
const { email, password, username } = req.body;
// Check if user already exists
let user = await User.findOne({ email });
if (user) {
res.status(400).json({ message: 'User already exists' });
return;
}
// Create new user
user = new User({
email,
password,
username,
});
// Save user to database
await user.save();
// Create a sample demo network
// Fix: Ensure user._id is treated as ObjectId
await createSampleDemoNetwork(user._id);
// Generate JWT token
const token = generateToken(user);
// Set token cookie
setTokenCookie(res, token);
// Send response
res.status(201).json({
success: true,
user: {
id: user._id,
email: user.email,
username: user.username,
},
});
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Login user
export const login = async (req: Request, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
const { email, password } = req.body;
// Check if user exists
const user = await User.findOne({ email });
if (!user) {
res.status(400).json({ message: 'Invalid credentials' });
return;
}
// Check if password is correct
const isMatch = await user.comparePassword(password);
if (!isMatch) {
res.status(400).json({ message: 'Invalid credentials' });
return;
}
// Generate JWT token
const token = generateToken(user);
// Set token cookie
setTokenCookie(res, token);
// Send response
res.json({
success: true,
user: {
id: user._id,
email: user.email,
username: user.username,
},
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Logout user
export const logout = (req: Request, res: Response): void => {
res.cookie('token', 'none', {
expires: new Date(Date.now() + 10 * 1000), // 10 seconds
httpOnly: true,
});
res.json({ success: true, message: 'Logged out successfully' });
};
// Get current user
export const getCurrentUser = async (req: UserRequest, res: Response): Promise<void> => {
try {
const user = req.user;
if (!user) {
res.status(401).json({ message: 'Not authorized' });
return;
}
res.json({
success: true,
user: {
id: user._id,
email: user.email,
username: user.username,
},
});
} catch (error) {
console.error('Get current user error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Create a sample demo network for new users
// Fix: Update parameter type to accept both string and ObjectId
const createSampleDemoNetwork = async (userId: mongoose.Types.ObjectId | string): Promise<void> => {
try {
// Ensure userId is an ObjectId
const userObjectId = typeof userId === 'string' ? new mongoose.Types.ObjectId(userId) : userId;
// Create a demo network
const network = new Network({
name: 'My Sample Network',
description: 'A demo network to help you get started',
owner: userObjectId,
isPublic: false,
});
await network.save();
// Create sample people with better spacing
const people = [
{ firstName: 'John', lastName: 'Smith', position: { x: 200, y: 200 } },
{ firstName: 'Emma', lastName: 'Johnson', position: { x: 600, y: 200 } },
{ firstName: 'Michael', lastName: 'Williams', position: { x: 200, y: 600 } },
{ firstName: 'Sarah', lastName: 'Brown', position: { x: 600, y: 600 } },
{ firstName: 'David', lastName: 'Jones', position: { x: 800, y: 400 } },
{ firstName: 'Lisa', lastName: 'Garcia', position: { x: 400, y: 400 } },
];
// Fix: Update the type to accept string or ObjectId
const savedPeople: { [key: string]: mongoose.Types.ObjectId | string } = {};
// Create each person
for (const person of people) {
const newPerson = new Person({
firstName: person.firstName,
lastName: person.lastName,
network: network._id,
position: person.position,
});
await newPerson.save();
savedPeople[`${person.firstName}${person.lastName}`] = newPerson._id;
}
// Create relationships between people
const relationships = [
{ source: 'JohnSmith', target: 'EmmaJohnson', type: 'freund' },
{ source: 'EmmaJohnson', target: 'MichaelWilliams', type: 'familie' },
{ source: 'MichaelWilliams', target: 'SarahBrown', type: 'arbeitskolleg' },
{ source: 'SarahBrown', target: 'DavidJones', type: 'freund' },
{ source: 'DavidJones', target: 'LisaGarcia', type: 'partner' },
{ source: 'JohnSmith', target: 'DavidJones', type: 'arbeitskolleg' },
];
// Create each relationship
for (const rel of relationships) {
const newRelationship = new Relationship({
source: savedPeople[rel.source],
target: savedPeople[rel.target],
type: rel.type,
network: network._id,
});
await newRelationship.save();
}
} catch (error) {
console.error('Error creating sample network:', error);
// Don't throw the error, just log it so that registration can continue
}
};

View File

@ -0,0 +1,166 @@
import { Response } from 'express';
import Network from '../models/network.model';
import { UserRequest } from '../../frontend/types/express';
import { validationResult } from 'express-validator';
// Get all networks for current user and all public networks
export const getUserNetworks = async (req: UserRequest, res: Response): Promise<void> => {
try {
if (!req.user) {
res.status(401).json({ message: 'Not authorized' });
return;
}
// Find networks that either:
// 1. Belong to the current user, OR
// 2. Are public networks (created by any user)
const networks = await Network.find({
$or: [{ owner: req.user._id }, { isPublic: true }],
}).populate('owner', 'username _id'); // Populate owner field with username
res.json({ success: true, data: networks });
} catch (error) {
console.error('Get networks error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Create a new network
export const createNetwork = async (req: UserRequest, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
if (!req.user) {
res.status(401).json({ message: 'Not authorized' });
return;
}
const { name, description, isPublic } = req.body;
const network = new Network({
name,
description,
owner: req.user._id,
isPublic: isPublic || false,
});
await network.save();
res.status(201).json({ success: true, data: network });
} catch (error) {
console.error('Create network error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Get a specific network
export const getNetwork = async (req: UserRequest, res: Response): Promise<void> => {
try {
const networkId = req.params.id;
if (!req.user) {
res.status(401).json({ message: 'Not authorized' });
return;
}
const network = await Network.findById(networkId).populate('owner', 'username _id');
if (!network) {
res.status(404).json({ message: 'Network not found' });
return;
}
// Check if user is owner or network is public
if (network.owner._id.toString() !== req.user._id.toString() && !network.isPublic) {
res.status(403).json({ message: 'You do not have permission to access this network' });
return;
}
res.json({ success: true, data: network });
} catch (error) {
console.error('Get network error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Update a network
export const updateNetwork = async (req: UserRequest, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
const networkId = req.params.id;
if (!req.user) {
res.status(401).json({ message: 'Not authorized' });
return;
}
const network = await Network.findById(networkId);
if (!network) {
res.status(404).json({ message: 'Network not found' });
return;
}
// Check if user is owner
if (network.owner.toString() !== req.user._id.toString()) {
res.status(403).json({ message: 'You do not have permission to update this network' });
return;
}
const { name, description, isPublic } = req.body;
network.name = name || network.name;
network.description = description !== undefined ? description : network.description;
network.isPublic = isPublic !== undefined ? isPublic : network.isPublic;
await network.save();
res.json({ success: true, data: network });
} catch (error) {
console.error('Update network error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Delete a network
export const deleteNetwork = async (req: UserRequest, res: Response): Promise<void> => {
try {
const networkId = req.params.id;
if (!req.user) {
res.status(401).json({ message: 'Not authorized' });
return;
}
const network = await Network.findById(networkId);
if (!network) {
res.status(404).json({ message: 'Network not found' });
return;
}
// Check if user is owner
if (network.owner.toString() !== req.user._id.toString()) {
res.status(403).json({ message: 'You do not have permission to delete this network' });
return;
}
await network.deleteOne(); // Changed from remove() to deleteOne()
res.json({ success: true, message: 'Network deleted successfully' });
} catch (error) {
console.error('Delete network error:', error);
res.status(500).json({ message: 'Server error' });
}
};

View File

@ -0,0 +1,175 @@
import { Response } from 'express';
import Person from '../models/person.model';
import Relationship from '../models/relationship.model';
import { UserRequest } from '../../frontend/types/express';
import { validationResult } from 'express-validator';
// Get all people in a network
export const getPeople = async (req: UserRequest, res: Response): Promise<void> => {
try {
const networkId = req.params.networkId;
if (!req.user || !req.network) {
res.status(401).json({ message: 'Not authorized' });
return;
}
const people = await Person.find({ network: networkId });
res.json({ success: true, data: people });
} catch (error) {
console.error('Get people error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Add a person to the network
export const addPerson = async (req: UserRequest, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
const networkId = req.params.networkId;
if (!req.user || !req.network) {
res.status(401).json({ message: 'Not authorized' });
return;
}
// Check if user is the owner (only owners can add people)
if (req.network.owner.toString() !== req.user._id.toString()) {
res.status(403).json({ message: 'Only the network owner can add people' });
return;
}
const { firstName, lastName, birthday, position } = req.body;
// Check if person already exists in this network
const existingPerson = await Person.findOne({
firstName,
lastName,
network: networkId,
});
if (existingPerson) {
res.status(400).json({ message: 'This person already exists in the network' });
return;
}
const person = new Person({
firstName,
lastName,
birthday: birthday || undefined,
network: networkId,
position: position || { x: 100 + Math.random() * 800, y: 100 + Math.random() * 600 },
});
await person.save();
res.status(201).json({ success: true, data: person });
} catch (error) {
console.error('Add person error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Update a person
export const updatePerson = async (req: UserRequest, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
const networkId = req.params.networkId;
const personId = req.params.id;
if (!req.user || !req.network) {
res.status(401).json({ message: 'Not authorized' });
return;
}
// Check if user is the owner (only owners can update people)
if (req.network.owner.toString() !== req.user._id.toString()) {
res.status(403).json({ message: 'Only the network owner can update people' });
return;
}
const person = await Person.findOne({
_id: personId,
network: networkId,
});
if (!person) {
res.status(404).json({ message: 'Person not found' });
return;
}
const { firstName, lastName, birthday, position } = req.body;
// Update person
if (firstName) person.firstName = firstName;
if (lastName) person.lastName = lastName;
if (birthday !== undefined) person.birthday = birthday || undefined;
if (position) person.position = position;
await person.save();
res.json({ success: true, data: person });
} catch (error) {
console.error('Update person error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Remove a person from the network
export const removePerson = async (req: UserRequest, res: Response): Promise<void> => {
try {
const networkId = req.params.networkId;
const personId = req.params.id;
if (!req.user || !req.network) {
res.status(401).json({ message: 'Not authorized' });
return;
}
// Check if user is the owner (only owners can remove people)
if (req.network.owner.toString() !== req.user._id.toString()) {
res.status(403).json({ message: 'Only the network owner can remove people' });
return;
}
const person = await Person.findOne({
_id: personId,
network: networkId,
});
if (!person) {
res.status(404).json({ message: 'Person not found' });
return;
}
// Remove all relationships involving this person
await Relationship.deleteMany({
network: networkId,
$or: [{ source: personId }, { target: personId }],
});
// Remove the person
await person.deleteOne(); // Changed from remove() to deleteOne()
res.json({
success: true,
message: 'Person and associated relationships removed successfully',
});
} catch (error) {
console.error('Remove person error:', error);
res.status(500).json({ message: 'Server error' });
}
};

View File

@ -0,0 +1,180 @@
import { Response } from 'express';
import Relationship from '../models/relationship.model';
import Person from '../models/person.model';
import { UserRequest } from '../../frontend/types/express';
import { validationResult } from 'express-validator';
// Get all relationships in a network
export const getRelationships = async (req: UserRequest, res: Response): Promise<void> => {
try {
const networkId = req.params.networkId;
if (!req.user || !req.network) {
res.status(401).json({ message: 'Not authorized' });
return;
}
const relationships = await Relationship.find({ network: networkId });
res.json({ success: true, data: relationships });
} catch (error) {
console.error('Get relationships error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Add a relationship to the network
export const addRelationship = async (req: UserRequest, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
const networkId = req.params.networkId;
if (!req.user || !req.network) {
res.status(401).json({ message: 'Not authorized' });
return;
}
// Check if user is the owner (only owners can add relationships)
if (req.network.owner.toString() !== req.user._id.toString()) {
res.status(403).json({ message: 'Only the network owner can add relationships' });
return;
}
const { source, target, type, customType } = req.body;
// Check if source and target exist and belong to the network
const sourcePerson = await Person.findOne({
_id: source,
network: networkId,
});
const targetPerson = await Person.findOne({
_id: target,
network: networkId,
});
if (!sourcePerson || !targetPerson) {
res.status(400).json({ message: 'Source or target person not found in this network' });
return;
}
// Check if relationship already exists
const existingRelationship = await Relationship.findOne({
$or: [
{ source, target, network: networkId },
{ source: target, target: source, network: networkId },
],
});
if (existingRelationship) {
res.status(400).json({ message: 'A relationship already exists between these people' });
return;
}
const relationship = new Relationship({
source,
target,
type,
customType: type === 'custom' ? customType : undefined,
network: networkId,
});
await relationship.save();
res.status(201).json({ success: true, data: relationship });
} catch (error) {
console.error('Add relationship error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Update a relationship
export const updateRelationship = async (req: UserRequest, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ errors: errors.array() });
return;
}
const networkId = req.params.networkId;
const relationshipId = req.params.id;
if (!req.user || !req.network) {
res.status(401).json({ message: 'Not authorized' });
return;
}
// Check if user is the owner (only owners can update relationships)
if (req.network.owner.toString() !== req.user._id.toString()) {
res.status(403).json({ message: 'Only the network owner can update relationships' });
return;
}
const relationship = await Relationship.findOne({
_id: relationshipId,
network: networkId,
});
if (!relationship) {
res.status(404).json({ message: 'Relationship not found' });
return;
}
const { type, customType } = req.body;
// Update relationship
if (type) relationship.type = type;
if (type === 'custom' && customType) relationship.customType = customType;
await relationship.save();
res.json({ success: true, data: relationship });
} catch (error) {
console.error('Update relationship error:', error);
res.status(500).json({ message: 'Server error' });
}
};
// Remove a relationship
export const removeRelationship = async (req: UserRequest, res: Response): Promise<void> => {
try {
const networkId = req.params.networkId;
const relationshipId = req.params.id;
if (!req.user || !req.network) {
res.status(401).json({ message: 'Not authorized' });
return;
}
// Check if user is the owner (only owners can remove relationships)
if (req.network.owner.toString() !== req.user._id.toString()) {
res.status(403).json({ message: 'Only the network owner can remove relationships' });
return;
}
const relationship = await Relationship.findOne({
_id: relationshipId,
network: networkId,
});
if (!relationship) {
res.status(404).json({ message: 'Relationship not found' });
return;
}
await relationship.deleteOne(); // Changed from remove() to deleteOne()
res.json({ success: true, message: 'Relationship removed successfully' });
} catch (error) {
console.error('Remove relationship error:', error);
res.status(500).json({ message: 'Server error' });
}
};