|
| 1 | +const {Router} = require('express') |
| 2 | +const bcrypt = require('bcryptjs') |
| 3 | +require('dotenv').config() |
| 4 | +const jwt = require('jsonwebtoken') |
| 5 | +const {check, validationResult} = require('express-validator') |
| 6 | +const User = require('../models/User') |
| 7 | +const router = Router() |
| 8 | + |
| 9 | +// /api/auth/register |
| 10 | +router.post( |
| 11 | + '/register', |
| 12 | + [ |
| 13 | + check('email', 'Некорректный email').isEmail(), |
| 14 | + check('password', 'Минимальная длина пароля 6 символов') |
| 15 | + .isLength({ min: 6 }) |
| 16 | + ], |
| 17 | + async (req, res) => { |
| 18 | + try { |
| 19 | + const errors = validationResult(req) |
| 20 | + |
| 21 | + if (!errors.isEmpty()) { |
| 22 | + return res.status(400).json({ |
| 23 | + errors: errors.array(), |
| 24 | + message: 'Некорректный данные при регистрации' |
| 25 | + }) |
| 26 | + } |
| 27 | + |
| 28 | + const {email, password} = req.body |
| 29 | + |
| 30 | + const candidate = await User.findOne({ email }) |
| 31 | + |
| 32 | + if (candidate) { |
| 33 | + return res.status(400).json({ message: 'Такой пользователь уже существует' }) |
| 34 | + } |
| 35 | + |
| 36 | + const hashedPassword = await bcrypt.hash(password, 12) |
| 37 | + const user = new User({ email, password: hashedPassword }) |
| 38 | + |
| 39 | + await user.save() |
| 40 | + |
| 41 | + res.status(201).json({ message: 'Пользователь создан' }) |
| 42 | + |
| 43 | + } catch (e) { |
| 44 | + res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' }) |
| 45 | + } |
| 46 | +}) |
| 47 | + |
| 48 | +// /api/auth/login |
| 49 | +router.post( |
| 50 | + '/login', |
| 51 | + [ |
| 52 | + check('email', 'Введите корректный email').normalizeEmail().isEmail(), |
| 53 | + check('password', 'Введите пароль').exists() |
| 54 | + ], |
| 55 | + async (req, res) => { |
| 56 | + try { |
| 57 | + const errors = validationResult(req) |
| 58 | + |
| 59 | + if (!errors.isEmpty()) { |
| 60 | + return res.status(400).json({ |
| 61 | + errors: errors.array(), |
| 62 | + message: 'Некорректный данные при входе в систему' |
| 63 | + }) |
| 64 | + } |
| 65 | + |
| 66 | + const {email, password} = req.body |
| 67 | + |
| 68 | + const user = await User.findOne({ email }) |
| 69 | + |
| 70 | + if (!user) { |
| 71 | + return res.status(400).json({ message: 'Пользователь не найден' }) |
| 72 | + } |
| 73 | + |
| 74 | + const isMatch = await bcrypt.compare(password, user.password) |
| 75 | + |
| 76 | + if (!isMatch) { |
| 77 | + return res.status(400).json({ message: 'Неверный пароль, попробуйте снова' }) |
| 78 | + } |
| 79 | + |
| 80 | + const token = jwt.sign( |
| 81 | + { userId: user.id }, |
| 82 | + process.env.jwtSecret, |
| 83 | + { expiresIn: '1h' } |
| 84 | + ) |
| 85 | + |
| 86 | + res.json({ token, userId: user.id }) |
| 87 | + |
| 88 | + } catch (e) { |
| 89 | + res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' }) |
| 90 | + } |
| 91 | +}) |
| 92 | + |
| 93 | + |
| 94 | +module.exports = router |
0 commit comments