Jarek Ostrowski
Jarek Ostrowski

Reputation: 137

Get user ID from google authentication in express (passport.js)

I'm trying to get the user.id after a user logs in, but I can't figure it out.

When I do a hard GET request in Postman (../api/users/829ug309hf032j), I get that user, but I don't know how to get the ID to set before the GET request.

app.component.ts

const id = // id I need of logged-in user //;

this.http.get('http://localhost:3000/api/users/' + id).subscribe(data => {
  console.log(data)
});

server.js

app.get('/api/users/:id', (req, res) => {
    User.findById(req.params.id, (err, users) => {
        res.send(users)
    })
})

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/ask' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/answer');
  });

I'd like to show the user their name and only show it if they're logged in...

<p *ngIf="user">{{ user.name }}</p>

Upvotes: 2

Views: 1767

Answers (1)

Pace
Pace

Reputation: 43817

Passport populates the req object with req.user if the authentication is successful so just use some variation of:

app.get('/api/users/me', (req, res) => {
  if (req.user) {
    res.json(req.user);
  } else {
    res.sendStatus(204);
  }
});

Upvotes: 1

Related Questions