backend_chat/server.js
Rangga Arya Putra a9707152ef backend
2024-09-11 09:10:59 +07:00

140 lines
4.0 KiB
JavaScript

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const session = require('express-session');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "http://localhost:5173",
methods: ["GET", "POST"],
credentials: true
}
});
app.use(cors({
origin: "http://localhost:5173",
methods: ["GET", "POST"],
credentials: true
}));
app.use(express.json());
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: { secure: false }
}));
let users = {};
let admins = {};
let messages = [];
app.post('/register', (req, res) => {
const { id, name } = req.body;
if (!id || !name) {
return res.status(400).json({ error: 'ID and Name are required' });
}
users[id] = { id, name };
res.status(200).json(users);
});
app.get('/users', (req, res) => {
res.status(200).json(users);
});
app.post('/registerAdmin', (req, res) => {
const { name, password } = req.body;
if (!name || !password) {
return res.status(400).json({ error: 'Name and Password are required' });
}
if (admins[name]) {
return res.status(400).json({ error: 'Admin already exists' });
}
admins[name] = { password };
res.status(200).json({ message: 'Admin successfully registered' });
});
app.post('/loginAdmin', (req, res) => {
const { name, password } = req.body;
if (!name || !password) {
return res.status(400).json({ error: 'Name and Password are required' });
}
if (!admins[name] || admins[name].password !== password) {
return res.status(400).json({ error: 'Invalid credentials' });
}
req.session.user = { name };
res.status(200).json({ message: 'Login successful' });
});
app.post('/logoutAdmin', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.status(500).json({ error: 'Logout failed' });
}
res.status(200).json({ message: 'Logout successful' });
});
});
const checkAuth = (req, res, next) => {
if (!req.session.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
next();
};
app.post('/sendMessage', checkAuth, (req, res) => {
const { content, recipient } = req.body;
if (!content || !recipient) {
return res.status(400).json({ error: 'Content and Recipient are required' });
}
const message = { content, sender: req.session.user.name, recipient };
messages.push(message);
io.emit('receiveMessage', message);
res.status(200).json(message);
});
app.post('/endConversation', checkAuth, (req, res) => {
const { recipient } = req.body;
if (!recipient) {
return res.status(400).json({ error: 'Recipient is required' });
}
messages = messages.filter(msg => msg.recipient !== recipient);
io.emit('receiveMessage', { type: 'conversationEnded', recipient });
res.status(200).json({ message: 'Conversation ended' });
});
app.post('/deleteUser', checkAuth, (req, res) => {
const { id } = req.body;
if (!id) {
return res.status(400).json({ error: 'User ID is required' });
}
delete users[id];
messages = messages.filter(msg => msg.recipient !== id);
io.emit('updateUsers', Object.values(users));
io.emit('receiveMessage', { type: 'userDeleted', id });
res.status(200).json({ message: 'User successfully deleted' });
});
io.on('connection', (socket) => {
console.log('User connected');
socket.on('sendMessage', (message) => {
io.emit('receiveMessage', message);
});
socket.on('endConversation', (data) => {
const { recipient } = data;
messages = messages.filter(msg => msg.recipient !== recipient);
io.emit('receiveMessage', { type: 'conversationEnded', recipient });
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
server.listen(3001, () => {
console.log('Server running on port 3001');
});