-
Notifications
You must be signed in to change notification settings - Fork 7.1k
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
WojD89
wants to merge
12
commits into
goitacademy:master
Choose a base branch
from
WojD89:hw06-email
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Hw06 email #5463
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6969658
commit
WojD89 c35ea47
init commit and server.js create
WojD89 3669617
adding services and conn to db
WojD89 79e7e12
create user schema
WojD89 411b44b
adding middleware
WojD89 d2561c1
auth add and final comm
WojD89 36cffcd
adding avatar file
WojD89 3dc7fac
adding avatar url to schema
WojD89 38480b8
adding gravatar and final touches
WojD89 6fc657d
initial commit and file strusture
WojD89 36d3da8
mailgun smtp connection
WojD89 3005c96
file reorganization and last fixes
WojD89 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
}, | ||
}); | ||
|
||
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"); | ||
} | ||
}, | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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ą.