All files / src/controllers user.controller.js

98.26% Statements 113/115
95.45% Branches 21/22
100% Functions 11/11
98.26% Lines 113/115

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 3384x 4x 4x 4x 4x 4x 4x       4x 1x 1x 1x     1x                               4x 2x 2x 2x 2x 1x   1x           1x                   4x 7x 7x     7x 7x 1x     6x     6x     5x 5x     5x   5x             2x                   4x 3x 3x     3x 3x 1x           2x 2x 1x       1x     1x                   1x                     4x 1x       1x 1x                       4x 2x 2x 2x 2x         1x           1x               4x 3x 3x 3x 3x 1x   2x         2x 1x     1x   1x 1x   1x   1x             2x               4x 2x 2x 2x   2x 1x     1x   1x   1x           1x               4x 2x 2x   2x   2x 2x 1x   1x   1x 1x   1x   1x           1x               4x 2x 2x 2x 2x 1x   1x 1x   1x             1x                   4x 2x   2x 2x 2x 1x     1x           1x               4x                          
const { disabled } = require('express/lib/application');
const JWT = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const User = require('../models/user.model');
const WorkSpace = require('../models/workSpace.model');
const { JWTgenerator } = require('../helpers/jwt');
const { transporter, passwordChanged, forgoted } = require('../utils/mailer');
 
// GET - READ
 
const listUser = async (req, res) => {
  try {
    const users = await User.find();
    Iif (!users) {
      throw new Error('User not found');
    }
    res.status(200).json({
      ok: true,
      message: 'Users found',
      data: users,
    });
  } catch (err) {
    res.status(404).json({
      ok: false,
      message: 'Users not found',
      data: err.message,
    });
  }
};
 
// GET ID - READ id
 
const showUser = async (req, res) => {
  try {
    const { uid } = req;
    const user = await User.findById(uid).select('-password');
    if (!user) {
      throw new Error('User not found');
    }
    res.status(200).json({
      ok: true,
      message: 'User found',
      data: user,
    });
  } catch (err) {
    res.status(404).json({
      ok: false,
      message: 'User not found',
      data: err.message,
    });
  }
};
 
// POST - CREATE - REGISTER
 
const registerUser = async (req, res) => {
  try {
    const { workSpaceId, password } = req.body;
 
    // Requiriendo el Id del workSpace para luego poder agregar el usuario creado mediante un push
    const workSpace = await WorkSpace.findById(workSpaceId);
    if (!workSpace) {
      throw new Error('Invalid workspace');
    }
    //Encrypta la contraseña
    const encryptPassword = await bcrypt.hash(password, 8);
 
    // Crea el usuario
    const user = await User.create({ ...req.body, password: encryptPassword });
 
    // Agrega el usuario al array de users del workspace y lo guarda
    workSpace.users.push(user);
    await workSpace.save({ validateBeforeSave: false });
 
    // Generar el JWT
    const token = await JWTgenerator(user._id, user.fullName, user.email);
 
    res.status(200).json({
      ok: true,
      message: 'User created',
      token,
      data: user,
    });
  } catch (err) {
    res.status(404).json({
      ok: false,
      message: 'User coult not be create',
      data: err.message,
    });
  }
};
 
// POST LOGIN
 
const loginUser = async (req, res) => {
  try {
    const { email, password } = req.body;
 
    // Validacion si el usuario existe en la base de datos
    const user = await User.findOne({ email });
    if (!user) {
      return res
        .status(400)
        .json({ ok: false, message: 'the email or password is not correct' });
    }
 
    // Validar que el password sea correcto
    const validatePassword = await bcrypt.compare(password, user.password);
    if (!validatePassword) {
      throw new Error('the email or password is not correct');
    }
 
    // Generar el JWT
    const token = await JWTgenerator(user._id, user.fullName, user.email);
 
    // Respuesta exitosa
    res.status(200).json({
      ok: true,
      message: 'Login successful',
      name: user.fullName,
      id: user._id,
      image: user.image,
      description: user.description,
      token,
    });
  } catch (err) {
    res.status(500).json({
      ok: false,
      message:
        'There was a problem trying to login, please contact the administrator',
      data: err.message,
    });
  }
};
 
// GET - REVALIDAR EL TOKEN
 
const tokenRevalidate = async (req, res) => {
  const { uid, fullName, email } = req;
 
  // Generar el JWT
 
  const token = await JWTgenerator(uid, fullName, email);
  res.status(200).json({
    ok: true,
    message: 'token revalidated',
    token,
    uid,
    fullName,
    email,
  });
};
 
// PUT - EDIT - UPDATE
 
const updateUser = async (req, res) => {
  const { uid } = req;
  try {
    delete req.body.email;
    const user = await User.findByIdAndUpdate(uid, req.body, {
      new: true,
      runValidators: true,
      context: 'query',
    });
    res.status(200).json({
      ok: true,
      message: 'User updated',
      data: user,
    });
  } catch (err) {
    res.status(500).json({
      ok: false,
      message: 'User could not be update',
      data: err.message,
    });
  }
};
 
const changePassword = async (req, res) => {
  const { uid } = req;
  try {
    const findUser = await User.findById(uid);
    if (!findUser) {
      throw new Error('User not found');
    }
    const validatePassword = await bcrypt.compare(
      req.body.oldPassword,
      findUser.password
    );
 
    if (!validatePassword) {
      throw new Error('Password is incorrect');
    }
 
    const encryptPassword = await bcrypt.hash(req.body.repeatPassword, 8);
 
    findUser.password = encryptPassword;
    await findUser.save({ validateBeforeSave: false });
 
    await transporter.sendMail(passwordChanged(findUser));
 
    res.status(200).json({
      ok: true,
      message: 'User updated',
      data: findUser,
      password: encryptPassword,
    });
  } catch (err) {
    res.status(500).json({
      ok: false,
      message: 'User could not be update',
      data: err.message,
    });
  }
};
 
const forgotPassword = async (req, res) => {
  try {
    const { email } = req.body;
    const user = await User.findOne({ email });
 
    if (!user) {
      throw new Error('User not found');
    }
 
    const token = await JWTgenerator(user._id, user.fullName, user.email);
 
    await transporter.sendMail(forgoted(user, token));
 
    res.status(200).json({
      ok: true,
      message: 'Email sent',
      token,
    });
  } catch (err) {
    res.status(500).json({
      ok: false,
      message: 'Email could not be sent',
      data: err.message,
    });
  }
};
 
const resetPassword = async (req, res) => {
  try {
    const { token, newPassword } = req.body;
 
    const decoded = await JWT.verify(token, process.env.SECRET_JWT_SEED_SLACK);
 
    const user = await User.findById(decoded.uid);
    if (!user) {
      throw new Error('User not found');
    }
    const encryptPassword = await bcrypt.hash(newPassword, 8);
 
    user.password = encryptPassword;
    await user.save({ validateBeforeSave: false });
 
    await transporter.sendMail(passwordChanged(user));
 
    res.status(200).json({
      ok: true,
      message: 'Password updated',
      data: user,
    });
  } catch (err) {
    res.status(500).json({
      ok: false,
      message: 'Password could not be updated',
      data: err.message,
    });
  }
};
 
const changePremium = async (req, res) => {
  try {
    const { uid } = req;
    const findUser = await User.findById(uid);
    if (!findUser) {
      throw new Error('User not found');
    }
    findUser.premium = true;
    await findUser.save({ validateBeforeSave: false });
 
    res.status(200).json({
      ok: true,
      message: 'User updated',
      data: findUser,
      premium: true,
    });
  } catch (err) {
    res.status(500).json({
      ok: false,
      message: 'User could not be update',
      data: err.message,
    });
  }
};
 
// DESTROY DELETE
 
const destroyUser = async (req, res) => {
  const { userId } = req.params;
 
  try {
    const user = await User.findByIdAndDelete(userId);
    if (!user) {
      throw new Error('User not found');
    }
 
    res.status(200).json({
      ok: true,
      message: 'User deleted',
      data: user,
    });
  } catch (err) {
    res.status(404).json({
      ok: false,
      message: 'User could not be detele',
      data: err.message,
    });
  }
};
 
module.exports = {
  listUser,
  showUser,
  registerUser,
  loginUser,
  tokenRevalidate,
  updateUser,
  destroyUser,
  changePassword,
  forgotPassword,
  resetPassword,
  changePremium,
};