I have been at this for a few days now. Req.user is undefined outside of the /login route. Also, deserialize does run. Does it have anything to do with react-router?
This is what the auth flow looks like in my head:
- Logging in sets req.user to every incoming request
- If req.user exists in the route they are trying to access, allow user to interact with the database.
Complete code at: Github
server.js
const app = express()
// Middleware
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
)
app.use(
session({
secret: "secretcode",
resave: true,
saveUninitialized: true,
})
)
app.use(cookieParser("secretcode"))
app.use(passport.initialize())
app.use(passport.session())
require("./passportConfig")(passport)
// Routes
app.post("/login", passport.authenticate('local'), (req, res) => {
console.log(req.user) // req.user is defined here
res.send("Logged in")
})
app.get("/tasks", (req, res) => {
console.log(req.user) // req.user is undefined here
res.send(req.user)
})
passportConfig.js
module.exports = (passport) => {
passport.serializeUser((user, cb) => {
cb(null, user.id)
})
passport.deserializeUser((id, cb) => { // Deserialize does run
db.get("SELECT * FROM users WHERE id = ?", [id], (err, user) => {
cb(err, user)
})
})
}
Client Side: Login.js
axios({
method: "POST",
data: {
username: usernameInput,
password: passwordInput
},
url: `http://localhost:4000/${route}`,
withCredentials: true,
}).then(res => {
console.log(res.data.message)
if (res.data === "Logged in") {
history.push("/tasks")
}
})
Tasks.js
useEffect(() => {
axios(
{
method: "GET",
url: "http://localhost:4000/tasks"
}
).then(res => {
console.log(res) // undefined
})
}, [])