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 #5524

Open
wants to merge 11 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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
node_modules/
.env
.idea
.vscode
.vscode
50 changes: 35 additions & 15 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,45 @@
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 connectDB = require("./config/db");

const contactsRouter = require('./routes/api/contacts')
const contactsRouter = require("./routes/api/contacts");
const signupRouter = require("./routes/api/users/signup");
const loginRouter = require("./routes/api/users/login");
const logoutRouter = require("./routes/api/users/logout");
const currentRouter = require("./routes/api/users/current");
const avatarsRouter = require("./routes/api/users/avatars");
const verifyRouter = require("./routes/api/users/verify");
const resendVerifyRouter = require("./routes/api/users/resendVerify");

const app = express()
const app = express();

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

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

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

app.use(express.static("public"));

app.use("/api/contacts", contactsRouter);
app.use("/api/users/signup", signupRouter);
app.use("/api/users/login", loginRouter);
app.use("/api/users/logout", logoutRouter);
app.use("/api/users/current", currentRouter);
app.use("/api/users/avatars", avatarsRouter);
app.use("/api/users/verify", verifyRouter);
app.use("/api/users/verify/resend", resendVerifyRouter);

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

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

module.exports = app
module.exports = app;
53 changes: 53 additions & 0 deletions authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const jwt = require("jsonwebtoken");
const User = require("./models/User");
require("dotenv").config();

const authMiddleware = async (req, res, next) => {
try {
const { authorization } = req.headers;

if (!authorization || !authorization.startsWith("Bearer ")) {
return res.status(401).json({
status: "401 Unauthorized",
contentType: "application/json",
responseBody: {
message: "Not authorized",
},
});
}

const token = authorization.split(" ")[1];

let decodedToken;
try {
decodedToken = jwt.verify(token, process.env.JWT_SECRET);
} catch (error) {
return res.status(401).json({
status: "401 Unauthorized",
contentType: "application/json",
responseBody: {
message: "Not authorized",
},
});
}

const user = await User.findById(decodedToken.id);

if (!user || user.token !== token) {
return res.status(401).json({
status: "401 Unauthorized",
contentType: "application/json",
responseBody: {
message: "Not authorized",
},
});
}

req.user = user;
next();
} catch (error) {
next(error);
}
};

module.exports = authMiddleware;
15 changes: 15 additions & 0 deletions config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const mongoose = require("mongoose");

require("dotenv").config();

const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log("Database connection successful");
} catch (error) {
console.error("Database connection error:", error);
process.exit(1);
}
};

module.exports = connectDB;
20 changes: 20 additions & 0 deletions models/Contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mongoose = require("mongoose");

const contactSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Set name for contact"],
},
email: {
type: String,
},
phone: {
type: String,
},
favorite: {
type: Boolean,
default: false,
},
});

module.exports = mongoose.model("Contact", contactSchema);
40 changes: 40 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const mongoose = require("mongoose");
const { Schema } = mongoose;

const userSchema = new Schema({
password: {
type: String,
required: [true, "Password is required"],
},
email: {
type: String,
required: [true, "Email is required"],
unique: true,
},
subscription: {
type: String,
enum: ["starter", "pro", "business"],
default: "starter",
},
token: {
type: String,
default: null,
},
owner: {
type: Schema.Types.ObjectId,
ref: "User",
},
avatarURL: { type: String },
verify: {
type: Boolean,
default: false,
},
verificationToken: {
type: String,
default: null,
},
});

const User = mongoose.model("User", userSchema);

module.exports = User;
41 changes: 34 additions & 7 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,46 @@
// const fs = require('fs/promises')
const Contact = require("./Contact");

const listContacts = async () => {}
const listContacts = async (page = 1, limit = 20, favorite) => {
const skip = (page - 1) * limit;
const query = favorite !== undefined ? { favorite } : {};

const getContactById = async (contactId) => {}
return await Contact.find(query).skip(skip).limit(limit).exec();
};

const removeContact = async (contactId) => {}
const getContactById = async (contactId) => {
return await Contact.findById(contactId);
};

const addContact = async (body) => {}
const removeContact = async (contactId) => {
return await Contact.findByIdAndDelete(contactId);
};

const updateContact = async (contactId, body) => {}
const addContact = async ({ name, email, phone }) => {
const newContact = new Contact({ name, email, phone });
return await newContact.save();
};

const updateContact = async (contactId, { name, email, phone }) => {
return await Contact.findByIdAndUpdate(
contactId,
{ name, email, phone },
{ new: true }
);
};

const updateStatusContact = async (contactId, { favorite }) => {
return await Contact.findByIdAndUpdate(
contactId,
{ favorite },
{ new: true }
);
};

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