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

Cannot read the undefined reading 'access_token'. When I sign-in using postman, I see the cookies set but when I am signing in the browser the cookies are not getting set. May be something because of cors. I have tried some changes which I found on the internet but nothing works. #25

Open
gautam899 opened this issue Nov 22, 2024 · 0 comments

Comments

@gautam899
Copy link

The below is my route in the server.js
`import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import cors from "cors";
import authRoutes from "./routes/auth.route.js";
import userRoutes from "./routes/user.route.js";
import postRoutes from "./routes/post.route.js";
import commentRoutes from "./routes/comment.route.js";
dotenv.config();

mongoose
.connect(process.env.MONGODB_URI)
.then(() => {
console.log("MongoDb is running");
})
.catch((error) => {
console.log(error);
});
const app = express(); //create express app
app.use(
cors({
origin: "http://localhost:5173",
credentials: true,
})
); //Enable cross origin requests.
app.use(express.json()); //To parse json req body.
app.listen(3000, () => {
console.log("Server is running on port 3000");
});

app.use("/api/auth", authRoutes);
app.use("/api/user", userRoutes);
app.use("/api/post", postRoutes);
app.use("/api/comment", commentRoutes);
app.get("/", (req, res) => {
res.send("API is running");
});
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
const message = err.message || "Internal Server Error";
res.status(statusCode).json({
success: false,
statusCode,
message,
});
});
`
This is the auth controller to sign in.

`import User from "../models/user.model.js";
import { errorHandler } from "../utils/errors.js";
import bcryptjs from "bcryptjs";
import jwt from "jsonwebtoken";

//Sign In controller
export const signin = async (req, res, next) => {
const { email, password } = req.body;
if (!email || !password || email === "" || password === "") {
errorHandler(400, "All feilds are required");
}

try {
const validUser = await User.findOne({ email });
if (!validUser) {
return next(errorHandler(400, "Invalid Credentials"));
}
const validPassword = bcryptjs.compareSync(password, validUser.password);
if (!validPassword) {
return next(errorHandler(400, "Invalid Credentials"));
}
//token
const token = jwt.sign(
{ id: validUser._id, isAdmin: validUser.isAdmin },
process.env.JWT_SECRET_KEY
);
//We do not want to send the password to the frontend for security reasons.
const { password: pass, ...rest } = validUser._doc;
res
.status(200)
.cookie("access_token", token, {
httpOnly: true,
sameSite: "Lax",
secure: false,
path: "/",
})
.json(rest);

//The response in the frontend will look something like this
// "_id": "",
// "username": "",
// "email": "",
// "profilePicture": "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png",
// "isAdmin": boolean,
// "createdAt": "",
// "updatedAt": "",
// "__v": 0

} catch (error) {
next(error);
}
};

//SignUp Controller
export const signup = async (req, res, next) => {
const { username, email, password } = req.body;

if (
!username ||
!email ||
!password ||
username === "" ||
email === "" ||
password === ""
) {
errorHandler(400, "Please fill in all fields");
}

const hashedPassword = bcryptjs.hashSync(password, 10);
const newUser = new User({
username,
email,
password: hashedPassword,
});
try {
await newUser.save();
res.json("SignUp Successfull");
} catch (error) {
next(error);
}
};

export const google = async (req, res, next) => {
const { email, name, googlePhotoUrl } = req.body;
try {
//If the user already exist then we directly sign in the user.
const user = await User.findOne({ email });
if (user) {
const token = jwt.sign(
{ id: user._id, isAdmin: user.isAdmin },
process.env.JWT_SECRET_KEY
);
const { password, ...rest } = user._doc;
res
.status(200)
.cookie("access_token", token, {
httpOnly: true,
sameSite: "Lax",
secure: false,
path: "/",
})
.json(rest);
} else {
//create a new user with a random username and a randaom password.
const generatePassword =
Math.random().toString(36).slice(-8) +
Math.random().toString(36).slice(-8);
const hashedPassword = bcryptjs.hashSync(generatePassword, 10);
const newUser = new User({
username:
name.toLowerCase().split(" ").join("") +
Math.random().toString(9).slice(-4),
email,
password: hashedPassword,
profilePicture: googlePhotoUrl,
});
await newUser.save();
const token = jwt.sign(
{ id: newUser._id, isAdmin: newUser.isAdmin },
process.env.JWT_SECRET_KEY
);
const { password, ...rest } = newUser._doc;
res
.status(200)
.cookie("access_token", token, {
httpOnly: true,
sameSite: "Lax",
secure: false,
path: "/",
})
.json(rest);
}
} catch (error) {
next(error);
}
};
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant