feat: creates backend for the project
This commit is contained in:
51
backend/src/routes/auth.ts
Normal file
51
backend/src/routes/auth.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Router } from 'express';
|
||||
import { asyncHandler } from '../utils';
|
||||
import { requireAuth } from '../middleware/auth';
|
||||
import * as authService from '../services/auth';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/login',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { login, password } = req.body;
|
||||
if (!login || !password) {
|
||||
res.status(400).json({ error: 'BAD_REQUEST', message: 'login and password are required' });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await authService.login({ login, password });
|
||||
if (!result) {
|
||||
res.status(401).json({ error: 'UNAUTHORIZED', message: 'Invalid credentials' });
|
||||
return;
|
||||
}
|
||||
|
||||
res.cookie('sid', result.sessionId, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
});
|
||||
res.json({ ok: true });
|
||||
}),
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/logout',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
await authService.logout(req.sessionId!);
|
||||
res.clearCookie('sid');
|
||||
res.json({ ok: true });
|
||||
}),
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/me',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const result = await authService.me(req.sessionId!);
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
export default router;
|
||||
Reference in New Issue
Block a user