Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hw05 avatars #5518

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
27 changes: 27 additions & 0 deletions JWT/configJWT.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const passport = require("passport");
const { ExtractJwt, Strategy } = require("passport-jwt");
const User = require("../models/user");
require("dotenv").config();

const JWTStrategy = () => {
const secret = process.env.SECRET;
const params = {
secretOrKey: secret,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
};
passport.use(
new Strategy(params, async function (payload, done) {
try {
const user = await User.findOne({ _id: payload.id });
if (!user) {
return done(new Error("User not found."));
}
return done(null, user);
} catch (error) {
return done(error);
}
})
);
};

module.exports = JWTStrategy;
20 changes: 20 additions & 0 deletions JWT/middlewareJWT.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const passport = require("passport");

const authMiddleware = (req, res, next) => {
passport.authenticate(
"jwt",
{
session: false,
},
(err, user) => {
if (!user || err || user.token === null) {
return res.status(401).json({ message: "Not authorized" });
}

res.locals.user = user;
next();
}
)(req, res, next);
};

module.exports = authMiddleware;
35 changes: 35 additions & 0 deletions Multer/configMulter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const multer = require("multer");
const path = require("path");
const { v4: uuidV4 } = require("uuid");

const tempDir = path.join(process.cwd(), "tmp");

const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, tempDir);
},
filename: (req, file, cb) => {
cb(null, `${uuidV4()}${path.extname(file.originalname)}`);
},
});

const extensionWhiteList = [".jpg", ".jpeg", ".png", ".gif"];
const mimetypeWhiteList = ["image/png", "image/jpg", "image/jpeg", "image/gif"];

const uploadMiddleware = multer({
storage,
fileFilter: async (req, file, cb) => {
const extension = path.extname(file.originalname).toLowerCase();
const mimetype = file.mimetype.toLowerCase();
if (
!extensionWhiteList.includes(extension) ||
!mimetypeWhiteList.includes(mimetype)
) {
return cb(new Error("Invalid file type"), false);
}
return cb(null, true);
},
limits: { fileSize: 1024 * 1024 * 5 },
});

module.exports = { uploadMiddleware };
41 changes: 24 additions & 17 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')
const express = require("express");
const logger = require("morgan");
const cors = require("cors");
const allRouter = require("./routes/allRouter");
const app = express();
const JWTStrategy = require("./JWT/configJWT");
const path = require("path");

const contactsRouter = require('./routes/api/contacts')
const formatsLogger = app.get("env") === "development" ? "dev" : "short";

const app = express()
app.use(logger(formatsLogger));
app.use(cors());
app.use(express.json());
app.use(express.static(path.resolve(__dirname, "./public")));

const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short'
JWTStrategy();

app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())

app.use('/api/contacts', contactsRouter)
app.use("/api", allRouter);

app.use((req, res) => {
res.status(404).json({ message: 'Not found' })
})
res.status(404).json({ message: `Not found - ${req.path}` });
});

app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
})

module.exports = app
if (err.name === "ValidationError") {
return res.status(400).json({ message: err.message });
} else {
res.status(500).json({ message: err.message || "Something went wrong" });
}
});

module.exports = app;
44 changes: 44 additions & 0 deletions controllers/avatars.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const fs = require("fs").promises;
const path = require("path");
const { v4: uuidV4 } = require("uuid");
const User = require("../models/user");
const { isImageAndTransform } = require("../helpers");

const updateAvatar = async (req, res, next) => {
if (!req.file) {
return res.status(400).json({ message: "No file uploaded" });
}

const { path: temporaryPath } = req.file;
const extension = path.extname(temporaryPath);
const fileName = `${uuidV4()}${extension}`;
const filePath = path.join(process.cwd(), "public/avatars", fileName);

try {
const isValidAndTransform = await isImageAndTransform(
temporaryPath,
filePath
);
if (!isValidAndTransform) {
await fs.unlink(temporaryPath);
return res.status(400).json({ message: "File isn't a photo" });
}

const user = await User.findByIdAndUpdate(
res.locals.user.id,
{ avatarURL: `/avatars/${fileName}` },
{ new: true }
);
if (!user) {
return res.status(404).json({ message: "User not found" });
}

res.status(200).json({
avatarURL: user.avatarURL,
});
} catch (error) {
next(error);
}
};

module.exports = { updateAvatar };
91 changes: 91 additions & 0 deletions controllers/contacts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
const {
listContacts,
getContactById,
deleteContact,
createContact,
updateContact,
updateStatusContact,
} = require("./services");

const getAllContacts = async (req, res, next) => {
try {
const contacts = await listContacts();
res.json(contacts);
} catch (error) {
next(error);
}
};

const getContact = async (req, res, next) => {
try {
const contact = await getContactById(req.params.contactId);
if (contact) {
res.json(contact);
} else {
next();
}
} catch (error) {
next(error);
}
};

const addContact = async (req, res, next) => {
const { name, email, phone } = req.body;
try {
const result = await createContact({ name, email, phone });
res.status(201).json(result);
} catch (error) {
next(error);
}
};

const removeContact = async (req, res, next) => {
const { contactId } = req.params;
try {
await deleteContact(contactId);
res.status(200).send({ message: "Contact deleted" });
} catch (error) {
next(error);
}
};

const putContact = async (req, res, next) => {
const id = req.params.contactId;
try {
const result = await updateContact({
id,
toUpdate: req.body,
upsert: true,
});
res.json(result);
} catch (error) {
next(error);
}
};

const patchContact = async (req, res, next) => {
const id = req.params.contactId;
console.log(typeof req.body.favorite);
try {
const result = await updateStatusContact({
id,
favorite: req.body.favorite,
});
if (req.body.favorite === undefined) {
return res.status(400).send({ message: "missing field favorite" });
} else {
res.status(200).json(result);
}
} catch (error) {
next(error);
}
};

module.exports = {
getAllContacts,
getContact,
addContact,
removeContact,
putContact,
patchContact,
};
41 changes: 41 additions & 0 deletions controllers/services.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const Contact = require("../models/contacts");

const listContacts = () => {
return Contact.find();
};

const getContactById = (id) => {
return Contact.findOne({ _id: id });
};

const createContact = ({ name, email, phone }) => {
return Contact.create({ name, email, phone });
};

const deleteContact = (id) => {
return Contact.deleteOne({ _id: id });
};

const updateContact = async ({ id, toUpdate, upsert = false }) => {
return Contact.findByIdAndUpdate(
{ _id: id },
{ $set: toUpdate },
{ new: true, runValidators: true, strict: "throw", upsert }
);
};
const updateStatusContact = async ({ id, favorite }) => {
return Contact.findByIdAndUpdate(
{ _id: id },
{ $set: { favorite } },
{ new: true, runValidators: true, strict: "throw" }
);
};

module.exports = {
listContacts,
getContactById,
deleteContact,
createContact,
updateContact,
updateStatusContact,
};
16 changes: 16 additions & 0 deletions helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const Jimp = require("jimp");

const isImageAndTransform = async (inputPath, outputPath) => {
try {
const image = await Jimp.read(inputPath);
image.resize(256, 256);
await image.writeAsync(outputPath);

return true;
} catch (err) {
console.error(err);
return false;
}
};

module.exports = { isImageAndTransform };
45 changes: 28 additions & 17 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
// const fs = require('fs/promises')
const mongoose = require("mongoose");
const { Schema } = mongoose;
const contactSchema = new Schema(
{
name: {
type: String,
required: [true, "Set name for contact"],
},
email: {
type: String,
required: [true, "Set email for contact"],
},
phone: {
type: String,
required: [true, "Set phone for contact"],
},
favorite: {
type: Boolean,
default: false,
},
},
{
versionKey: false,
timestamps: true,
}
);

const listContacts = async () => {}
const Contact = mongoose.model("contact", contactSchema);

const getContactById = async (contactId) => {}

const removeContact = async (contactId) => {}

const addContact = async (body) => {}

const updateContact = async (contactId, body) => {}

module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
}
module.exports = Contact;
Loading