|
| 1 | +const jwt = require('jsonwebtoken'); |
| 2 | +const bcrypt = require('bcryptjs'); |
| 3 | +const User = require('../models/user'); |
| 4 | +const NotFoundError = require('../errors/NotFoundError'); |
| 5 | +const ConflictError = require('../errors/ConflictError'); |
| 6 | +const BadRequestError = require('../errors/BadRequestError'); |
| 7 | +const config = require('../config'); |
| 8 | + |
| 9 | +module.exports.login = (req, res, next) => { |
| 10 | + const { email, password } = req.body; |
| 11 | + User.findUserByCredentials(email, password) |
| 12 | + .then((user) => { |
| 13 | + const token = jwt.sign( |
| 14 | + { _id: user._id }, |
| 15 | + process.env.NODE_ENV === 'production' ? process.env.JWT_SECRET : config.jwt.devKey, |
| 16 | + { expiresIn: '7d' }, |
| 17 | + ); |
| 18 | + res.status(200).send({ token }); |
| 19 | + }) |
| 20 | + .catch(next); |
| 21 | +}; |
| 22 | + |
| 23 | +module.exports.createUser = (req, res, next) => { |
| 24 | + const { password } = req.body; |
| 25 | + bcrypt.hash(password, 10) |
| 26 | + .then((hash) => User.create({ |
| 27 | + ...req.body, |
| 28 | + password: hash, |
| 29 | + })) |
| 30 | + .then((createdUser) => { |
| 31 | + User.findById(createdUser._id) |
| 32 | + .then((user) => res.status(201).send({ data: user })) |
| 33 | + .catch(next); |
| 34 | + }) |
| 35 | + .catch((err) => { |
| 36 | + if (err.name === 'ValidationError') { |
| 37 | + next(new BadRequestError(err.message)); |
| 38 | + } else if (err.code === 11000) { |
| 39 | + next(new ConflictError('User with this email address already exists.')); |
| 40 | + } else { |
| 41 | + next(err); |
| 42 | + } |
| 43 | + }); |
| 44 | +}; |
| 45 | + |
| 46 | +module.exports.getUserInfo = (req, res, next) => { |
| 47 | + User.findById(req.user._id) |
| 48 | + .orFail(() => { |
| 49 | + throw new NotFoundError('User ID not found'); |
| 50 | + }) |
| 51 | + .then((user) => { |
| 52 | + res.status(200).send({ data: user }); |
| 53 | + }) |
| 54 | + .catch(next); |
| 55 | +}; |
0 commit comments