auth logic (WIP), socket work (WIP)

This commit is contained in:
2024-05-04 00:28:15 +02:00
parent a766fd8882
commit 0a51c72cc8
5 changed files with 121 additions and 532 deletions

27
src/models/user.ts Normal file
View File

@ -0,0 +1,27 @@
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
const prisma = new PrismaClient();
export async function createUser(username: string, password: string): Promise<void> {
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(password, salt);
await prisma.user.create({
data: {
username,
password: hash
}
});
}
export async function validateUser(username: string, password: string): Promise<boolean> {
const user = await prisma.user.findUnique({
where: {
username,
},
});
if (!user) return false;
return bcrypt.compareSync(password, user.password);
}

View File

@ -1,31 +1,84 @@
import { PrismaClient, User } from '@prisma/client';
import express from 'express';
import http from 'http';
import { Server } from 'socket.io';
import dotenv from 'dotenv';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import http from 'http';
import { createUser, validateUser } from './models/user';
import cors from 'cors'; // Import cors
dotenv.config();
const prisma = new PrismaClient();
const app = express();
const server = http.createServer(app);
const io = new Server(server, { cors: { origin: '*' } });
app.get('/', (req: express.Request, res: express.Response) => {
res.send('Hello World!');
app.use(cors()); // Enable cors
app.use(express.json());
// Simple user registration endpoint
app.post('/register', async (req, res) => {
const { username, password } = req.body;
try {
await createUser(username, password);
res.status(201).send('User registered');
} catch (error) {
res.status(500).send('Error registering user');
}
});
// Simple login endpoint
app.post('/login', async (req, res) => {
const { username, password } = req.body;
if (await validateUser(username, password)) {
res.send('Login successful');
} else {
res.status(401).send('Invalid credentials');
}
});
const playerList: any = [];
// Socket.IO authentication and room management
io.on('connection', (socket) => {
console.log('new client connected');
socket.on('disconnect', () => {
console.log('client disconnected');
const { username, password } = socket.handshake.query;
if (!username || !password) {
socket.disconnect(true);
return;
}
if (!validateUser(<string> username, <string> password)) {
socket.disconnect(true);
return;
}
// add player to playerList but only if they are not already in the list
if (!playerList.find((player: any) => player.username === username)) {
playerList.push({ username, coords: { x: 0, y: 0 } });
}
console.log('User connected:', username);
socket.join('room');
socket.emit('message', 'Welcome to the room!');
socket.emit('playerList', playerList);
socket.on('joinRoom', (room) => {
socket.join(room);
socket.to(room).emit('message', `${username} has joined the room.`);
socket.to(room).emit('playerList', playerList);
});
socket.on('leaveRoom', (room) => {
socket.leave(room);
socket.to(room).emit('message', `${username} has left the room.`);
});
socket.on('player_moved', (coords) => {
socket.to('room').emit('player_moved', { username, coords });
});
})
io.on('disconnect', () => {
console.log('Socket disconnected');
});
const PORT = process.env.SERVER_PORT || 3000;
server.listen(PORT, () => {
console.log(`listening on *:${PORT}`);
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));