Client not receiving session data from server using Node, Passport JS, and cookie-session
so i've been using development servers this entire time, and everything's worked fine. Now, as I've deployed my client and backend, i'm running into an issue where my client cannot grab the sessional data from the cookie. i've checked both the backend and client cookies, and it seems like the session and session.sig are identical, so i don't know what's the deal... here's the relevant code:
my backend:
server.js:
dotenv.config({ path: "./.env" });
const cookieKey = process.env.COOKIE_KEY;
const express = require("express");
const cookieSession = require("cookie-session");
const connectDB = require("./config/db");
const passport = require("passport");
const PORT = process.env.PORT || 4500;
const cors = require("cors");
connectDB();
const app = express();
//middleware
app.use(express.json());
app.use(
cors({
origin: true, // replace with your frontend domain
credentials: true,
})
);
app.use(
cookieSession({
maxAge: 24 * 60 * 60 * 1000, // 1 day
keys: [cookieKey],
cookie: {
secure: true,
sameSite: "none",
},
})
);
app.use(passport.initialize());
app.use(passport.session());
const authentication = require("./routes/Authentication.js");
app.use("/api/v1/auth", authentication);
const tabs = require("./routes/Tabs.js"); // Adjust the path as necessary
app.use("/api/v1/tabs", tabs);
const preferences = require("./routes/Preferences.js");
app.use("/api/v1/preferences", preferences);
const google = require("./routes/Google.js"); // Adjust the path as necessary
app.use("/api/v1/google", google);
app.listen(PORT, () => console.log("Server is connected"));
authentication.js:
dotenv.config({ path: "./.env" });
const sucessRedirectURL = process.env.SUCCESS_REDIRECT_URL;
const express = require("express");
const passport = require("passport");
require("../services/Passport");
const router = express.Router();
router.get(
"/google",
passport.authenticate("google", {
scope: ["profile", "email", "https://www.googleapis.com/auth/calendar"],
accessType: "offline",
approvalPrompt: "force",
})
);
router.get(
"/google/callback",
passport.authenticate("google", {
successRedirect: sucessRedirectURL,
})
);
router.get("/me", (req, res) => {
if (req.user) {
res.send(req.user);
} else {
res.status(401).json({ message: "Not authenticated" });
}
});
router.get("/logout", (req, res) => {
console.log("logging out");
req.logout();
res.redirect("/");
});
module.exports = router;
and my own service file, passport.js:
dotenv.config({ path: "./.env" });
const googleClientID = process.env.GOOGLE_CLIENT_ID;
const googleClientSecret = process.env.GOOGLE_CLIENT_SECRET;
const backendAppURL = process.env.BACKEND_APP_URL;
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20");
const User = require("../models/User");
//when a user logs in, we get a 'user object' which is serialized to our session by storing a user's ID,
//which is called automatically after logging
passport.serializeUser((user, done) => {
done(null, user.id);
});
//now, when we want to take the data stored in our session, we use the ID to recreate the full user object on
//each request, which is automatically done on each request
passport.deserializeUser((id, done) => {
User.findById(id).then((user) => {
done(null, user);
});
});
//this code happens first to find/create a user object
passport.use(
new GoogleStrategy(
{
clientID: googleClientID,
clientSecret: googleClientSecret,
callbackURL: backendAppURL + "/api/v1/auth/google/callback", //FULL CALLBACK URL IN PRODUCTION VS RELATIVE PATH IN DEVELOPMENT
},
async (accessToken, refreshToken, profile, done) => {
try {
const existingUser = await User.findOneAndUpdate(
{ googleId: profile.id },
{
accessToken,
refreshToken,
name: profile.displayName,
avatarUrl: profile.picture,
isVerified: profile.emails[0].verified,
}
);
if (existingUser) {
console.log("Existing user found:", existingUser);
return done(null, existingUser);
}
const user = await new User({
accessToken,
refreshToken,
name: profile.displayName,
email: profile.emails[0].value,
googleId: profile.id,
avatarUrl: profile.picture,
isVerified: profile.emails[0].verified,
}).save();
console.log("New user saved:", user);
done(null, user);
} catch (error) {
console.error("Error during authentication: ", error);
done(error);
}
}
)
);
here's the backend cookie:
0 comments:
Post a Comment
Thanks