All files / nodejs-homework-API/controllers user.js

23.08% Statements 15/65
0% Branches 0/10
0% Functions 0/6
23.08% Lines 15/65

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 1551x 1x 1x 1x 1x 1x 1x 1x   1x                                                                   1x                                                       1x                                                         1x                           1x                                     1x                         1x                
const UserModel = require("../model/user");
const fs = require("fs").promises;
const path = require("path");
const Jimp = require("jimp");
const jwt = require("jsonwebtoken");
const createFolderIsExist = require("../helpers/create-directory");
require("dotenv").config();
const SECRET_KEY = process.env.JWT_SECRET;
 
const saveAvatarForStatic = async (req, res, next) => {
  try {
    const id = req.user.id;
    const DIR_IMAGES = process.env.DIR_IMAGES;
    const pathToFile = req.file.path;
    const newNameAvatar = req.file.originalname;
 
    const img = await Jimp.read(pathToFile);
    await img
      .autocrop()
      .cover(
        250,
        250,
        Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE
      )
      .writeAsync(pathToFile);
 
    await createFolderIsExist(path.join(DIR_IMAGES, id));
    await fs.rename(pathToFile, path.join(DIR_IMAGES, id, newNameAvatar));
    const newUrlAvatar = path.normalize(path.join(id, newNameAvatar));
    const newUrl = `http://localhost:3000/${id}/${newNameAvatar}`;
    await UserModel.updateAvatar(id, newUrlAvatar);
    return res.status(200).json({
      status: "success",
      code: 200,
      data: {
        newUrl,
      },
    });
  } catch (e) {
    next(e);
  }
};
 
const createNewUser = async (req, res, next) => {
  try {
    const { email } = req.body;
    const isExist = await UserModel.findByEmail(email);
    if (isExist) {
      return res.status(409).json({
        status: "error",
        code: 409,
        data: "Conflict",
        message: "Email has used already!",
      });
    }
    const newUser = await UserModel.createUser(req.body);
    return res.status(201).json({
      status: "success",
      code: 201,
      data: {
        id: newUser.id,
        email: newUser.email,
        name: newUser.name,
        avatar: newUser.avatar,
      },
    });
  } catch (e) {
    next(e);
  }
};
 
const logIn = async (req, res, next) => {
  try {
    const { email, password } = req.body;
    const user = await UserModel.findByEmail(email);
    const isValidPassword = await user.validPassword(password);
    if (!user || !isValidPassword) {
      return res.status(401).json({
        status: "error",
        code: 401,
        data: "UNAUTHORIZED",
        message: "Invalid credentials",
      });
    }
    const id = user._id;
    const payload = { id };
    const token = jwt.sign(payload, SECRET_KEY, { expiresIn: "2h" });
    await UserModel.updateToken(id, token);
    return res.status(200).json({
      status: "success",
      code: 200,
      data: {
        token,
      },
    });
  } catch (e) {
    next(e);
  }
};
 
const logout = async (req, res, next) => {
  const id = req.user.id;
  const user = await UserModel.findById(id);
  if (!user) {
    return res.status(401).json({
      status: "error",
      code: 401,
      data: "UNAUTHORIZED",
      message: "Invalid credentials",
    });
  }
  await UserModel.updateToken(id, null);
  return res.status(204).json({});
};
const getCurrent = async (req, res, next) => {
  const user = req.user;
  if (!user) {
    return res.status(401).json({
      status: "error",
      code: 401,
      data: "UNAUTHORIZED",
      message: "Invalid credentials",
    });
  }
 
  return res.status(200).json({
    status: "success",
    code: 200,
    data: {
      user,
    },
  });
};
const updateSubscription = async (req, res, next) => {
  try {
    const id = req.user.id;
    console.log(req.body);
    const update = await UserModel.updateSubscrip(id, req.body);
    return res.status(200).json({
      data: update,
    });
  } catch (e) {
    next(e);
  }
};
 
module.exports = {
  saveAvatarForStatic,
  createNewUser,
  logIn,
  logout,
  getCurrent,
  updateSubscription,
};