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

Hw06 email #5463

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 27 additions & 16 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
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 path = require("path");

const contactsRouter = require('./routes/api/contacts')
const contactsRouter = require("./routes/api/contacts");
const usersRouter = require("./routes/api/users");

const app = express()
const setJWTStrategy = require("./config/jwt");

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

app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())
const formatsLogger = app.get("env") === "development" ? "dev" : "short";

app.use('/api/contacts', contactsRouter)
app.use(logger(formatsLogger));
app.use(cors());
app.use(express.json());

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

app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "./public")));

app.use("/api/contacts", contactsRouter);
app.use("/api/users", usersRouter);

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

app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
})
console.error(err.stack);
res.status(500).json({ message: "Internal Server Error" });
});

module.exports = app
module.exports = app;
28 changes: 28 additions & 0 deletions config/jwt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const passport = require("passport");
const { ExtractJwt, Strategy: JWTStrategy } = require("passport-jwt");
const User = require("../models/users/user.js");

require("dotenv").config();

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

module.exports = setJWTStrategy;
125 changes: 125 additions & 0 deletions controllers/contacts/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
const {
createNewContact,
deleteContact,
fetchContact,
fetchContacts,
updateContact,
updateStatusContact,
} = require("./services.js");

const getAllContacts = async (req, res, page, limit) => {
try {
const userId = req.user._id;
const { favorite } = req.query;
const contacts = await fetchContacts(userId, page, limit, favorite);
res.json(contacts);
} catch (err) {
console.error(err);
res.status(500).json(err);
}
};

const getContact = async (req, res) => {
try {
const userId = req.user._id;
const contact = await fetchContact(userId, req.params.contactId);
if (!contact) {
console.log("Contact not found");
return res.status(404).json({ message: "Contact not found" });
}
res.json(contact);
} catch (err) {
console.error(err);
res.status(500).json(err);
}
};

const createContact = async (req, res) => {
try {
const userId = req.user._id;
const newContact = await createNewContact(userId, req.body);
console.log("Contact created successfully:", newContact);
res.status(201).json(newContact);
} catch (err) {
console.error(err);
res.status(500).json(err);
}
};

const deleteContactById = async (req, res) => {
try {
const userId = req.user._id;
const deletedContact = await deleteContact(
userId,
req.params.contactId
);
if (deletedContact) {
console.log("Contact deleted successfully:", deletedContact);
res.json({ message: "Contact deleted successfully" });
} else {
console.log("Contact not found");
res.status(404).json({ message: "Contact not found" });
}
} catch (err) {
console.error(err);
res.status(500).json(err);
}
};

const updateContactById = async (req, res) => {
try {
const userId = req.user._id;
const updatedContact = await updateContact(
userId,
req.params.contactId,
req.body
);
if (updatedContact) {
console.log("Contact updated successfully:", updatedContact);
res.json(updatedContact);
} else {
console.log("Contact not found");
res.status(404).json({ message: "Contact not found" });
}
} catch (err) {
console.error(err);
res.status(500).json(err);
}
};

const updateFavoriteStatus = async (req, res) => {
try {
const userId = req.user._id;
const { favorite } = req.body;
if (!favorite) {
return res.status(400).json({ message: "Missing field favorite" });
}
const updatedContact = await updateStatusContact(
userId,
req.params.contactId,
favorite
);
if (updatedContact) {
console.log(
"Favorite status updated successfully:",
updatedContact
);
res.json(updatedContact);
} else {
console.log("Contact not found");
res.status(404).json({ message: "Contact not found" });
}
} catch (err) {
console.error(err);
res.status(500).json(err);
}
};

module.exports = {
getAllContacts,
getContact,
createContact,
deleteContactById,
updateContactById,
updateFavoriteStatus,
};
47 changes: 47 additions & 0 deletions controllers/contacts/services.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const Contact = require("../../models/contacts/contacts.js");

const fetchContacts = (userId, page, limit, favorite) => {
const skip = (page - 1) * limit;
let query = { owner: userId };
if (favorite !== undefined) {
query.favorite = favorite;
}
return Contact.find(query).skip(skip).limit(limit);
};

const fetchContact = (userId, id) => {
return Contact.findOne({ _id: id, owner: userId });
};

const createNewContact = async (userId, contactData) => {
const newContact = await Contact.create({ ...contactData, owner: userId });
console.log("Contact created successfully:", newContact);
return newContact;
};

const deleteContact = async (userId, id) => {
return Contact.findOneAndDelete({ _id: id, owner: userId });
};

const updateContact = async (userId, id, updatedData) => {
return Contact.findOneAndUpdate({ _id: id, owner: userId }, updatedData, {
new: true,
});
};

const updateStatusContact = async (userId, id, favorite) => {
return Contact.findOneAndUpdate(
{ _id: id, owner: userId },
{ favorite },
{ new: true }
);
};

module.exports = {
fetchContacts,
fetchContact,
createNewContact,
deleteContact,
updateContact,
updateStatusContact,
};
43 changes: 43 additions & 0 deletions controllers/email/emial.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const nodemailer = require("nodemailer");
const mgMail = require("@mailgun/mail");
const ejs = require("ejs");
const path = require("path");
require("dotenv").config();


const transporter = nodemailer.createTransport({
host: "smtp.mailgun.org",
port: 587,
secure: false,
auth: {
user: "postmaster@sandbox9cab1fdc00254a859bf4b329af9215b1.mailgun.org",
pass: "dec8cecc1a727f073dc6b092162d0b88-afce6020-884407cb",
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To przenieś sobie do .env

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mailgun moze Ci zablokować możliwość wysyłania emails jeśli to są prawdziwe dane. Spotkałem się z tym że tak robią.

},
});

module.exports = {
sendVerificationEmail: async (email, verificationToken, req) => {
try {
const verificationLink = `${req.protocol}://${req.get(
"host"
)}/api/users/verify/${verificationToken}`;

const html = await ejs.renderFile(
path.join(__dirname, "../../views/verificationEmail.ejs"),
{ verificationLink }
);

const mailOptions = {
to: email,
from: process.env.SENDER_EMAIL,
subject: "Verify Your Email",
html: html,
};

await transporter.sendMail(mailOptions);
} catch (err) {
console.error("Error sending verification email:", err);
throw new Error("Error sending verification email");
}
},
};
Loading