34 lines
1.2 KiB
JavaScript
34 lines
1.2 KiB
JavaScript
|
const express = require('express');
|
||
|
const router = express.Router();
|
||
|
const jwt = require('jsonwebtoken');
|
||
|
const bcrypt = require('bcrypt');
|
||
|
const User = require('../models/User');
|
||
|
const passport = require('passport');
|
||
|
|
||
|
router.post('/register', async (req, res) => {
|
||
|
const { username, password } = req.body;
|
||
|
if (!username || !password) return res.status(400).json({ error: 'Missing fields' });
|
||
|
const pfp = "https://source.boringavatars.com/marble/" + username
|
||
|
console.log(pfp)
|
||
|
const user = new User({ username, password, profilePhoto: pfp });
|
||
|
await user.save();
|
||
|
res.sendStatus(201);
|
||
|
console.log("register success")
|
||
|
});
|
||
|
|
||
|
router.post('/login', async (req, res) => {
|
||
|
const { username, password } = req.body;
|
||
|
if (!username || !password) return res.status(400).json({ error: 'Missing fields' });
|
||
|
const user = await User.findOne({ username });
|
||
|
if (!user) return res.sendStatus(401);
|
||
|
const isPasswordCorrect = await bcrypt.compare(password, user.password);
|
||
|
if (!isPasswordCorrect) return res.sendStatus(401);
|
||
|
const token = jwt.sign({ userId: user._id }, 'SECRET_KEY');
|
||
|
const userId = user._id
|
||
|
// req.app.io.emit('user connected', { userId: userId });
|
||
|
res.send({ token, userId});
|
||
|
console.log("login success")
|
||
|
});
|
||
|
|
||
|
module.exports = router;
|