48 lines
1.6 KiB
TypeScript
48 lines
1.6 KiB
TypeScript
|
|
import { Router } from 'express';
|
||
|
|
import bcrypt from 'bcryptjs';
|
||
|
|
import { users } from '../db';
|
||
|
|
import { requireAuth } from '../middleware/auth';
|
||
|
|
|
||
|
|
const router = Router();
|
||
|
|
|
||
|
|
router.post('/register', async (req, res) => {
|
||
|
|
const { username, password } = req.body as { username?: string; password?: string };
|
||
|
|
if (!username || !password) { res.status(400).json({ error: 'Username and password required' }); return; }
|
||
|
|
try {
|
||
|
|
const hash = await bcrypt.hash(password, 10);
|
||
|
|
const user = users.create({ username, password: hash });
|
||
|
|
req.session.userId = user.id;
|
||
|
|
req.session.username = user.username;
|
||
|
|
res.json({ id: user.id, username: user.username });
|
||
|
|
} catch {
|
||
|
|
res.status(409).json({ error: 'Username already taken' });
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
router.post('/login', async (req, res) => {
|
||
|
|
const { username, password } = req.body as { username?: string; password?: string };
|
||
|
|
const user = username ? users.findByUsername(username) : undefined;
|
||
|
|
if (!user || !password || !(await bcrypt.compare(password, user.password))) {
|
||
|
|
res.status(401).json({ error: 'Invalid credentials' });
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
req.session.userId = user.id;
|
||
|
|
req.session.username = user.username;
|
||
|
|
res.json({ id: user.id, username: user.username });
|
||
|
|
});
|
||
|
|
|
||
|
|
router.post('/logout', (req, res) => {
|
||
|
|
req.session.destroy(() => res.json({ ok: true }));
|
||
|
|
});
|
||
|
|
|
||
|
|
router.delete('/me', requireAuth, (req, res) => {
|
||
|
|
users.delete(req.session.userId!);
|
||
|
|
req.session.destroy(() => res.json({ ok: true }));
|
||
|
|
});
|
||
|
|
|
||
|
|
router.get('/me', requireAuth, (req, res) => {
|
||
|
|
res.json({ id: req.session.userId, username: req.session.username });
|
||
|
|
});
|
||
|
|
|
||
|
|
export default router;
|