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
1 change: 1 addition & 0 deletions client/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ function App() {
</header>
<main>
<Routes>
<Route path="/" element={<Blogs />} />
<Route path="/login" element={<Login/>}></Route>
<Route path="/blogs" element={<Blogs/>}></Route>
<Route path="/myBlogs" element={<UserBlogs/>}></Route>
Expand Down
50 changes: 36 additions & 14 deletions client/src/componets/Blogs.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,54 @@ import Blog from "./Blog";
import config from "../config";

const Blogs = () => {
const [blogs, setBlogs] = useState();
const [blogs, setBlogs] = useState([]);
const [loading, setLoading] = useState(true);

const sendRequest = async () => {
const res = await axios
.get(`${config.BASE_URL}/api/blogs`)
.catch((err) => console.log(err));
const data = await res.data;
return data;
try {
const res = await axios.get(`${config.BASE_URL}/api/blogs`);
return res.data;
} catch (err) {
console.error("API Error:", err.message);
return { blogs: [] };
}
};

useEffect(() => {
sendRequest().then((data) => setBlogs(data.blogs));
sendRequest().then((data) => {
if (data && data.blogs) {
setBlogs(data.blogs);
} else {
setBlogs([]);
}
setLoading(false);
});
}, []);
console.log(blogs);

if (loading) {
return <p>Loading blogs...</p>;
}

return (
<div>
{blogs &&
blogs.map((blog, index) => (
{blogs.length > 0 ? (
blogs.map((blog) => (
<Blog
key={blog._id}
id={blog._id}
isUser={localStorage.getItem("userId") === blog.user._id}
isUser={localStorage.getItem("userId") === blog.user?._id}
title={blog.title}
desc={blog.desc}
img={blog.img}
user={blog.user.name}
date={new Date(blog.date).toLocaleDateString()}
user={blog.user?.name || "Unknown User"}
date={
blog.date ? new Date(blog.date).toLocaleDateString() : "N/A"
}
/>
))}
))
) : (
<p>No blogs found.</p>
)}
</div>
);
};
Expand Down
58 changes: 32 additions & 26 deletions client/src/componets/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import config from "../config";

const Login = () => {
const location = useLocation();
const naviagte = useNavigate();
const dispath = useDispatch();
const navigate = useNavigate();
const dispatch = useDispatch();
const { isSignupButtonPressed } = location.state || {};

const [inputs, setInputs] = useState({
Expand All @@ -18,47 +18,53 @@ const Login = () => {
password: "",
});
const [isSignup, setIsSignup] = useState(isSignupButtonPressed || false);

useEffect(() => {
setIsSignup(isSignupButtonPressed);
}, [isSignupButtonPressed]);

const handleChange = (e) => {
setInputs((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}));
};
useEffect(() => {
setIsSignup(isSignupButtonPressed);
}, [isSignupButtonPressed]);

const sendRequest = async (type = "login") => {
console.log("inside send req");
console.log(`${config.BASE_URL}/api/users/${type}`);
const res = await axios
.post(`${config.BASE_URL}/api/users/${type}`, {
try {
const res = await axios.post(`${config.BASE_URL}/api/users/${type}`, {
name: inputs.name,
email: inputs.email,
password: inputs.password,
})
.catch((err) => console.log(err));

const data = await res.data;
console.log("return");
console.log(data);
return data;
});
return res.data;
} catch (err) {
console.error("Error in request:", err.response?.data || err.message);
alert(err.response?.data?.message || "Invalid credentials or server error");
}
};

const handleSubmit = (e) => {
e.preventDefault();
console.log(inputs);
if (isSignup) {
sendRequest("signup")
.then((data) => localStorage.setItem("userId", data.user._id))
.then(() => dispath(authActions.login()))
.then(() => naviagte("/blogs"));
sendRequest("signup").then((data) => {
if (data?.user?._id) {
localStorage.setItem("userId", data.user._id);
dispatch(authActions.login());
navigate("/blogs");
}
});
} else {
sendRequest()
.then((data) => localStorage.setItem("userId", data.user._id))
.then(() => dispath(authActions.login()))
.then(() => naviagte("/blogs"));
sendRequest("login").then((data) => {
if (data?.user?._id) {
localStorage.setItem("userId", data.user._id);
dispatch(authActions.login());
navigate("/blogs");
}
});
}
};

return (
<div>
<form onSubmit={handleSubmit}>
Expand All @@ -85,7 +91,7 @@ const Login = () => {
placeholder="Name"
margin="normal"
/>
)}{" "}
)}
<TextField
name="email"
onChange={handleChange}
Expand Down
2 changes: 2 additions & 0 deletions server/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
MONGO_URI=mongodb+srv://mubashar:[email protected]/BlogApp?retryWrites=true&w=majority&appName=Cluster0
PORT=5001
1 change: 0 additions & 1 deletion server/.env.example

This file was deleted.

22 changes: 13 additions & 9 deletions server/config/db.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
const mongoose = require("mongoose");
require('dotenv').config();
require("dotenv").config();

mongoose.set("strictQuery", false);

mongoose.set('strictQuery', false);


mongoose.connect(process.env.MONGO_URI || "mongodb://mongo:27017/Blog").then(()=>{
console.log("connected!");
}).catch((err)=>{
console.log(err);
})
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("✅ MongoDB Atlas Connected!");
})
.catch((err) => {
console.error("❌ MongoDB Connection Error:", err.message);
});
97 changes: 49 additions & 48 deletions server/controller/user-contoller.js
Original file line number Diff line number Diff line change
@@ -1,65 +1,66 @@
const User = require("../model/User");
const bcrypt = require("bcryptjs");
const { ApiResponse } = require("../utils/ApiResponse");
const { ApiError } = require("../utils/ApiError");

const getAllUser = async (req, res, next) => {
try {
const users = await User.find();
if (!users || users.length === 0) {
return res.status(404).json(new ApiError(404, "Users not found"));
}
return res.status(200).json(new ApiResponse(200, { users }, "Users fetched successfully"));
} catch (err) {
console.error(err);
return res.status(500).json(new ApiError(500, "Server error while fetching users"));
// ✅ Get All Users
const getAllUser = async (req, res) => {
try {
const users = await User.find();
if (!users || users.length === 0) {
return res.status(404).json({ message: "Users not found" });
}
return res.status(200).json({ users, message: "Users fetched successfully" });
} catch (err) {
console.error(err);
return res.status(500).json({ message: "Server error while fetching users" });
}
};

const signUp = async (req, res, next) => {
const { name, email, password } = req.body;
// ✅ Signup
const signUp = async (req, res) => {
const { name, email, password } = req.body;

try {
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json(new ApiError(400, "User already exists"));
}
try {
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: "User already exists" });
}

const hashedPassword = bcrypt.hashSync(password, 10);
const user = new User({
name,
email,
password: hashedPassword,
blogs: []
});
const hashedPassword = bcrypt.hashSync(password, 10);
const user = new User({
name,
email,
password: hashedPassword,
blogs: []
});

await user.save();
return res.status(201).json(new ApiResponse(201, { user }, "User registered successfully"));
} catch (e) {
console.error(e);
return res.status(500).json(new ApiError(500, "Server error while signing up"));
}
await user.save();
return res.status(201).json({ user, message: "User registered successfully" });
} catch (e) {
console.error(e);
return res.status(500).json({ message: "Server error while signing up" });
}
};

const logIn = async (req, res, next) => {
const { email, password } = req.body;

try {
const existingUser = await User.findOne({ email });
if (!existingUser) {
return res.status(404).json(new ApiError(404, "User not found"));
}
// ✅ Login
const logIn = async (req, res) => {
const { email, password } = req.body;

const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(400).json(new ApiError(400, "Incorrect Password"));
}
try {
const existingUser = await User.findOne({ email });
if (!existingUser) {
return res.status(404).json({ message: "User not found" });
}

return res.status(200).json(new ApiResponse(200, { user: existingUser }, "Login successful"));
} catch (err) {
console.error(err);
return res.status(500).json(new ApiError(500, "Server error while logging in"));
const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(400).json({ message: "Incorrect Password" });
}

return res.status(200).json({ user: existingUser, message: "Login successful" });
} catch (err) {
console.error(err);
return res.status(500).json({ message: "Server error while logging in" });
}
};

module.exports = { getAllUser, signUp, logIn };
Loading