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

Hw04 auth #5515

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
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;
39 changes: 22 additions & 17 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
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 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());

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;
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,
};
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;
41 changes: 41 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const mongoose = require("mongoose");
const bCrypt = require("bcrypt");
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,
},
},
{
versionKey: false,
timestamps: true,
}
);

userSchema.methods.setPassword = async function (password) {
this.password = await bCrypt.hash(password, 10);
};

userSchema.methods.validatePassword = function (password) {
return bCrypt.compare(password, this.password);
};

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

module.exports = User;
Loading