1

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:

  1. Logging in sets req.user to every incoming request
  2. 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
    })
  }, [])
Assassin
  • 11
  • 2

1 Answers1

0

Ladies and gentlemen, after 4 days of headaches.

I had to tack in a withCredentials: true to the axios request. So:

 useEffect(() => {
    axios(
      {
        method: "GET",
        url: "http://localhost:4000/tasks",
        withCredentials:true,
      }
    ).then(res => {
      console.log(res) // undefined
    })
  }, [])

Apparently this has something to do with sending cookies back to the server to identify the user.

This answer helped me: Stackover Link. I glossed over this answer the first time since it was for fetch and I was using axios.

Assassin
  • 11
  • 2