Skip to content
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
53 changes: 37 additions & 16 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,46 @@
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 mongoose = require("mongoose");

const contactsRouter = require('./routes/api/contacts')
require("dotenv").config();

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

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("public"));

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

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

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

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 })
})

module.exports = app
res.status(500).json({ message: err.message });
});

const { DB_HOST, PORT = 3000 } = process.env;

mongoose
.connect(DB_HOST)
.then(() => {
console.log("Database connection succesful^_^");
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
})
.catch((error) => {
console.error("Database connection error:", error.message);
});

module.exports = app;
71 changes: 71 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/user");

//POST /users/login
const login = async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ message: "Email not found ^_^" });
}

const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
console.log(
password + " " + user.password + " ispasswordvalid: " + isPasswordValid
);
return res.status(401).json({ message: "Password is wrong ^_^" });
}

const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: "1h",
});
user.token = token;
await user.save();

res.status(200).json({
token,
user: {
email: user.email,
subscription: user.subscription,
},
});
};

//POST /users/signup
const signup = async (req, res) => {
const { email, password } = req.body;
const existingUser = await User.findOne({ email });
if (existingUser)
return res.status(409).json({ message: "Email in use ^_^" });
const user = new User({ email, password });
await user.save();
res.status(201).json({
// Schimbă .send() cu .json()
message: "User created successfully ^_^", // Adaugă un mesaj pentru succes
user: {
email: user.email,
subscription: user.subscription,
},
});
};

//GET /users/logout
const logout = async (req, res) => {
try {
const user = await User.findById(req.user._id);
if (!user) {
return res.status(404).json({ message: "User not found ^_^" });
}

user.token = null;
await user.save();

res.status(200).json({ message: "Logged out successfully ^_^" });
} catch (error) {
res.status(500).json({ message: "Logout failed", error: error.message });
}
};

module.exports = { login, signup, logout };
64 changes: 64 additions & 0 deletions controllers/contacts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const Contact = require("../models/contact");

//GET /api/contacts
const listContacts = async (page, limit, filter) => {
const contacts = await Contact.find({ ...filter })
.skip((page - 1) * limit)
.limit(limit)
.exec();
const totalContacts = await Contact.countDocuments({ ...filter });
return {
totalContacts,
totalPages: Math.ceil(totalContacts / limit),
page,
limit,
contacts,
};
};

//GET /api/contacts/:id
const getContactById = async (req, res) => {
const contact = await Contact.findById(req.params.id);
if (!contact) return res.status(404).json({ message: "Contact not found" });
res.status(200).json(contact);
};

//POST /api/contacts
const addContact = async (req, res) => {
const { name, email, phone, favorite } = req.body;
const contact = new Contact({ name, email, phone, favorite, owner: req.user._id });
await contact.save();
res.status(201).json(contact);
};

//DELETE /api/contacts/:id
const removeContact = async (req, res) => {
const contact = await Contact.findByIdAndDelete(req.params.id);
if (!contact) return res.status(404).json({ message: "Contact not found" });
res.status(200).json({ message: "Contact deleted" });
};

//PUT /api/contacts/:id
const updateContact = async (req, res) => {
const contact = await Contact.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!contact) return res.status(404).json({ message: "Contact not found" });
res.status(200).json(contact);
};

//PATCH /api/contacts/:id/favorite
const updateFavorite = async (req, res) => {
const contact = await Contact.findById(req.params.id);
if (!contact) return res.status(404).json({ message: "Contact not found" });
contact.favorite = !contact.favorite;
await contact.save();
res.status(200).json(contact);
};

module.exports = {
listContacts,
getContactById,
addContact,
removeContact,
updateContact,
updateFavorite,
};
50 changes: 50 additions & 0 deletions controllers/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const User = require("../models/user");
const { processAvatar, moveAvatar } = require("../services/avatar");

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

await processAvatar(req.file.path);

const avatarURL = await moveAvatar(req.file.path, req.file.filename);
const user = await User.findByIdAndUpdate(
req.user._id,
{ avatarURL },
{ new: true }
);
res.status(200).json({ avatarURL });
} catch (error) {
res
.status(500)
.json({ message: "Failed to update avatar ^_^", error: error.message });
}
};

const getCurrentUser = (req, res) => {
res.status(200).json({
email: req.user.email,
subscription: req.user.subscription,
});
};

const updateSubscription = async (req, res) => {
const { subscription } = req.body;
if (!["starter", "pro", "business"].includes(subscription)) {
return res.status(400).json({ message: "Invalid subscription type ^_^" });
}
req.user.subscription = subscription;
await req.user.save();
res.status(200).json({
email: req.user.email,
subscription: req.user.subscription,
});
};

module.exports = {
updateAvatar,
getCurrentUser,
updateSubscription,
};
20 changes: 20 additions & 0 deletions middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const jwt = require("jsonwebtoken");
const User = require("../models/user");

const authMiddleware = async (req, res, next) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ message: "Not authorized ^_^" });

try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.id);
if (!user || user.token !== token)
return res.status(401).json({ message: "Not authorized ^_^" });
req.user = user;
next();
} catch (error) {
return res.status(401).json({ message: "Not authorized ^_^" });
}
};

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

const tempDir = path.join(__dirname, "../tmp");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, tempDir);
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});

const upload = multer({ storage });
module.exports = upload;
25 changes: 25 additions & 0 deletions models/contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const mongoose = require("mongoose");

const contactSchema = new mongoose.Schema({
name: {
type: String,
},
email: {
type: String,
},
phone: {
type: String,
},
favorite: {
type: Boolean,
default: false,
},
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
});

const Contact = mongoose.model("Contact", contactSchema);

module.exports = Contact;
19 changes: 0 additions & 19 deletions models/contacts.js

This file was deleted.

62 changes: 0 additions & 62 deletions models/contacts.json

This file was deleted.

Loading