in local host ive started the server in port 4000 and the client in 3000.I've tried several stack overfow posts (problem with cors, session config) but nothing improved my results. The following code worked as expeced and fetched the user for my function logInUser().
this is how i click the G button from Front end
const loginFn = () => {window.open(`${process.env.REACT_APP_SERVER_URL}/auth/google`, "_self")}
this is my app.js (server)
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
cookie: { httpOnly: false, maxAge: (60 * 60 * 24 * 1000) },
}));
app.use(cors({
origin: `${process.env.CLIENT_URL}`,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true,
optionsSuccessStatus: 204
}))
app.use(passport.initialize());
app.use(passport.authenticate('session'));
app.use("/auth", authrouter);
app.use("/item", itemrouter);
app.use("/cart", cartrouter);
app.use("/pay", payrouter);
app.use("/purchasehistory", purchasehistoryrouter);
app.get("/", (req, res) => {
res.status(200).json({ "status": "server active" })
})
Google Strategy
passport.use(new GoogleStrategy({
clientID: `${process.env.GOOGLE_CLIENT_ID}`,
clientSecret: `${process.env.GOOGLE_CLIENT_SECRET}`,
callbackURL: `${process.env.SERVER_URL}/auth/google/callback`,
scope: ['profile', 'email']
}, async function (accessToken, refreshToken, profile, cb) { .... }
serialise and deserialiser
passport.serializeUser((user, cb) => {
// console.log(user);
process.nextTick(() => {
cb(null, user._id);
});
console.log("---------------------serialised")
});
passport.deserializeUser((_id, cb) => {
// console.log(_id);
process.nextTick(() => {
userDetails.findById(_id, function (err, user) {
if (err) {
console.log("user not foud for deserialisation")
throw err;
}
else {
console.log("---------------------deserialised")
return cb(null, user);
}
})
});
});
from here im forwarding my user to the client side
const authorize = (req, res) => {
console.log(req.isAuthenticated());
console.log(req.user);
if (req.isAuthenticated()) {
if (req.user) {
res.status(200).json(req.user)
}
else {
console.log("req.user not found")
res.status(403).json({
status: false,
message: "req.user not found"
})
}
}
else {
console.log("unautherised")
res.status(401).json({ status: false, message: "unautherised" })
}
}
the below code fetches the user for me at the client side
axios({
url: `${process.env.REACT_APP_SERVER_URL}/auth/authorize`,
method: 'get',
withCredentials: true
})
.then((resp) => {
if (resp.status === 200) {
console.log("success")
logInUser(true, resp.data);
console.log(resp.data)
toast.success(`${resp.data.fName} logged-in`);
}
})
.catch(err => {
console.log("error api fetch: ")
console.log(err)
logOutUser();
})
Ive made the following change on the session config while deploying.
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
cookie: { httpOnly: false, secure: true, sameSite: "none", maxAge: (60 * 60 * 24 * 1000) },
}));
what i've tried
- different config for session
- cookie session instead of express session
- different config for cors
- added passport.authorize() middileware on the route to be protected
- hosting both server and client on Heroku (when i fed-up)
what i didn't tried
- using proxy server
i'm missing something that i didn't know. I know there are lots of post related to this issue. but i couldn't make anything useful for me. Please share your advice for this issue. Thanks in advance