Files
geo/backend/dist/routes/auth.js
2026-02-04 00:11:19 +05:00

132 lines
4.9 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const client_1 = require("@prisma/client");
const bcrypt_1 = __importDefault(require("bcrypt"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const router = (0, express_1.Router)();
const prisma = new client_1.PrismaClient();
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change-in-production';
const COOKIE_OPTIONS = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
};
function signToken(userId, email) {
return jsonwebtoken_1.default.sign({ userId, email }, JWT_SECRET, { expiresIn: '7d' });
}
function setTokenCookie(res, token) {
res.cookie('token', token, COOKIE_OPTIONS);
}
// POST /api/auth/register
router.post('/register', async (req, res) => {
try {
const { email, password, name } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Укажите email и пароль' });
}
const normalizedEmail = String(email).trim().toLowerCase();
if (normalizedEmail.length < 3) {
return res.status(400).json({ error: 'Некорректный email' });
}
if (String(password).length < 4) {
return res.status(400).json({ error: 'Пароль не менее 4 символов' });
}
const existing = await prisma.user.findUnique({
where: { email: normalizedEmail },
});
if (existing) {
return res.status(400).json({ error: 'Пользователь с таким email уже зарегистрирован' });
}
const passwordHash = await bcrypt_1.default.hash(password, 10);
const user = await prisma.user.create({
data: {
email: normalizedEmail,
passwordHash,
name: name ? String(name).trim() || null : null,
},
});
const token = signToken(user.id, user.email);
setTokenCookie(res, token);
res.status(201).json({
user: { id: user.id, email: user.email, name: user.name },
token,
});
}
catch (error) {
console.error('Register error:', error);
res.status(500).json({ error: 'Ошибка регистрации' });
}
});
// POST /api/auth/login
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Укажите email и пароль' });
}
const normalizedEmail = String(email).trim().toLowerCase();
const user = await prisma.user.findUnique({
where: { email: normalizedEmail },
});
if (!user) {
return res.status(401).json({ error: 'Неверный email или пароль' });
}
const valid = await bcrypt_1.default.compare(password, user.passwordHash);
if (!valid) {
return res.status(401).json({ error: 'Неверный email или пароль' });
}
const token = signToken(user.id, user.email);
setTokenCookie(res, token);
res.json({
user: { id: user.id, email: user.email, name: user.name },
token,
});
}
catch (error) {
console.error('Login error:', error);
const message = process.env.NODE_ENV === 'development' && error?.message
? error.message
: 'Ошибка входа';
res.status(500).json({ error: message });
}
});
// POST /api/auth/logout
router.post('/logout', (_req, res) => {
res.clearCookie('token', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
});
res.json({ ok: true });
});
// GET /api/auth/me (requires auth)
router.get('/me', async (req, res) => {
const token = req.cookies?.token ||
(req.headers.authorization?.startsWith('Bearer ')
? req.headers.authorization.slice(7)
: null);
if (!token) {
return res.status(401).json({ error: 'Требуется авторизация' });
}
try {
const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET);
const user = await prisma.user.findUnique({
where: { id: decoded.userId },
select: { id: true, email: true, name: true },
});
if (!user) {
return res.status(401).json({ error: 'Пользователь не найден' });
}
res.json({ user });
}
catch {
return res.status(401).json({ error: 'Недействительный токен' });
}
});
exports.default = router;
//# sourceMappingURL=auth.js.map