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
2 changes: 1 addition & 1 deletion client/src/componets/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const Header = () => {
if (savedTheme !== null) {
dispatch(setDarkmode(JSON.parse(savedTheme)));
}
}, []);
}, [dispatch]);
useEffect(() => {
const path = location.pathname;
if (path.startsWith("/blogs/add")) {
Expand Down
72 changes: 44 additions & 28 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 @@ -27,38 +27,54 @@ const Login = () => {
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}`, {
name: inputs.name,


const sendRequest = async (type = "login") => {
try {
const res = await fetch(`${config.BASE_URL}/api/users/${type}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: inputs.email,
password: inputs.password,
})
.catch((err) => console.log(err));
name: inputs.name,
}),
});

const data = await res.data;
console.log("return");
console.log(data);
return data;
};
const data = await res.json();

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"));
if(data.success === true) {
alert(data.message)
} else {
sendRequest()
.then((data) => localStorage.setItem("userId", data.user._id))
.then(() => dispath(authActions.login()))
.then(() => naviagte("/blogs"));
alert("Wrong Email or password")
}
};

console.log(data)

return data;
} catch (err) {
console.error("Request error:", err);
}
};

const handleSubmit = async (e) => {
e.preventDefault();

const type = isSignup ? "signup" : "login";
const data = await sendRequest(type);

if (data?.user?._id) {
localStorage.setItem("userId", data.user._id);
dispatch(authActions.login());
navigate("/blogs");
} else {

}
};


return (
<div>
<form onSubmit={handleSubmit}>
Expand Down
10 changes: 7 additions & 3 deletions server/controller/user-contoller.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,20 @@ const signUp = async (req, res, next) => {
}
};

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

if(!email || !password) {
return res.status(404).json(new ApiError(404, "All fields are required"));
}

try {
const existingUser = await User.findOne({ email });
if (!existingUser) {
return res.status(404).json(new ApiError(404, "User not found"));
return res.status(404).json(new ApiError({statusCode: 404}, {message: 'User not found'}));
}

const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password);
const isPasswordCorrect = await bcrypt.compare(password, existingUser.password);
if (!isPasswordCorrect) {
return res.status(400).json(new ApiError(400, "Incorrect Password"));
}
Expand Down
4 changes: 3 additions & 1 deletion server/model/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ const userSchema = new Schema({
blogs: [{ type: mongoose.Types.ObjectId, ref: "Blog", required: true }],
})

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

module.exports = User
125 changes: 65 additions & 60 deletions server/package.json
Original file line number Diff line number Diff line change
@@ -1,83 +1,88 @@
{


"name": "blogapp",


"version": "1.0.0",


"description": "",


"main": "server.js",


"scripts": {




"start": "nodemon server.js",




"test": "echo \"Error: no test specified\" && exit 1"


},


"author": "khushi patel",


"license": "ISC",


"devDependencies": {




"nodemon": "^2.0.16"


},


"dependencies": {




"bcryptjs": "^2.4.3",








"body-parser": "^2.2.0",




"cors": "^2.8.5",




"dotenv": "^16.5.0",




"express": "^4.18.1",




"helmet": "^8.1.0",




"mongoose": "^6.3.4"


}
}
Expand Down
31 changes: 16 additions & 15 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,27 @@ const cors = require("cors");

const app = express();

app.use(cors());
app.use(cors({
origin: "http://localhost:3000",
methods: ["GET", "POST", "DELETE", "PATCH", "PUT"],
credentials: true,
}));

//setting helmet middleware
app.use(helmet(
{
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
}
));
// ✅ Use only express.json() — it replaces bodyParser.json()
app.use(express.json());
app.use(express.urlencoded({ extended: true })); // for form data

// ✅ Helmet middleware
app.use(helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
}));

app.set("view engine", "ejs");
app.use(express.json());

// ✅ Routes
app.use("/api/users", userRouter);
app.use("/api/blogs", blogRouter);

app.use("/api", (req, res, next) => {
res.send("hello");
});

//define port

// ✅ Start server
app.listen(5001, () => console.log("app started at 5001..."));
Loading