Angular/LocalStorage: Keep getting logged out on p

2019-08-22 01:46发布

I've been working on my first MEAN stack application. Currently, I am able to sign up new users and log them in. However, when I do either (login or sign up), I am unable to refresh the home page without getting logged out.

I have successfully setting my localStorage, and can get it in my parent component, but the issue remains. I've been looking through lots of S.O. questions, but can't seem to nail it down.

Here's my Login post route

//LOGIN POST
router.post('/login', (req, res) => {
  let email;
  let password;

  if(req.body.email && req.body.password) {
    email = req.body.email;
    password = req.body.password;
  }

  if (email === "" || password === "") {
    res.status(401).json({message: "Please provide both email and password"});
    return;
  }

  //Find the user in database.
  User.findOne({ "email": email }, (err, user) => {
    if ( !user ){
      res.status(401).json({message: "Email doesn't exist!"});
    } else {
      bcrypt.compare(password, user.password, function(err, isMatch) {
        if (!isMatch) {
          return res.status(401).json({message: "Password doesn't match.  Please try again..."});
        } else {

          req.session.user = user;  //Storing user data in the session

          var payload = {id: user._id};
          var token = jwt.sign(payload, jwtOptions.secretOrKey, { expiresIn: "24h" });
          return res.json({ message: "ok", token: token, user: user });
          // res.status(200).json({message: "Welcome back...", token: token, user: user});


        }
      });
    }
  });
});

Here's my login method in my authService

public token: string;
isAuth: EventEmitter<any> = new EventEmitter();

login(user) {
  return this.http.post(`${this.BASE_URL}/login`, user)
    .map((response) => {
      console.log("here's the response", response);
      console.log("here's the token", response.json());
      let token = response.json() && response.json().token;
      // let currentUser = response.json().user;
      let currentUser = JSON.stringify(response.json().user);

      if(token) {
        console.log("here's the token", token);
        //set token property
        this.token = token;

        this.isAuth.emit(true);

        //store username and jwt in local storage to keep user logged in between page refreshes
        localStorage.setItem('token', token);
        localStorage.setItem('user', currentUser);


        return true; //return true to indicate successful login
      } else {
        return false;
    }
    })
    .catch((err) => {
      return Observable.throw(err);
    });
}

Here's what I'm doing in my Categories Component (the parent component)

isAuth: boolean;
  user: any;
  token: any;

  constructor(
    private session: AuthService,
    private router: Router
  ) {
    //checks isAuth event emitter in login to see if it's true.  If it is, subscribe the result to our local isAuth variable
    this.session.isAuth
      .subscribe((isAuth: boolean) => this.isAuth = isAuth );

    //if token exists, authenticated
    if (this.session.token) {
      this.isAuth = true;
      localStorage.getItem('token');
      localStorage.getItem('user');
    //if not, not authenticated
    } else {
      this.isAuth = false;
    }


  }



  ngOnInit() {

    localStorage.getItem('token');
    localStorage.getItem('user');

  }

I should note that when I console.log my localStorage items after getting them, they appear just fine. I've tried the above code in various components, but keep getting logged out.

Any help is much appreciated. Does anyone know what might be happening here? Thanks a lot.

1条回答
我命由我不由天
2楼-- · 2019-08-22 02:17

You’re checking this.session.token in the component which is only set in the instance of that service while you’re in the app. When you refresh that value won’t exist and you won’t be authenticated (because the service will be reinitialized).

You should rework the logic to check local storage for a valid token on init.

查看更多
登录 后发表回答