angular and express session issue

45 Views Asked by At

My project built in angular and express server (for backend) , i am using express-session + mongostore for sessions. Each time I send a request from angular, a new session is created .. This issue cause me authentication issues (using passportjs-local) - which registers the user object to req this is my configurations:

   backend:
  // express-session-usage
    const store = MongoStore.create({
      mongoUrl: MongoUrl,
      secret: 'khkjh',
      touchAfter: 24 * 60 * 60,
      autoRemove: 'native'
    })
    
    const sessionConfig = {
      store,
      name: 'Banana',
      secret: 'kjhkhkjhyyt',
      resave: false,
      saveUninitialized: true,
      cookie: {
          httpsOnly: true,
          secure: false,
          expires: Date.now() + 18000000,//7200000 //1000 * 60 * 60 * 24 * 7, // session expires every 2 hours
          maxAge: 18000000 //7200000 1000 * 60 * 60 * 24 * 7 // // Max session Age is 2 hours
      }
    }
    app.use(session(sessionConfig));
    app.use(passport.initialize());
    app.use(passport.session());
    

//Enable CORS
var corsOptions = {
  origin: ['http://localhost:3000', 'http://localhost:4200', 'http://localhost:4000'],
  optionsSuccessStatus: 200
}
app.use(cors(corsOptions));
app.use((req, res, next) => {
  console.log(req)
  res.setHeader('Cross-Origin-Resource-Policy', 'same-site');
  next();
});

login route :

app.post('/login',passport.authenticate('local'),async(req,res)=> {
  if (req.user === false) {
    console.log(req.user)
    res.json(false);
    res.end()
  } else {
    console.log(req.user)
    res.json(true);
    res.end()
  }
})

backend is running on localhost port 4000 and angular in the normal port 4200 frontend angular request :

  checkLogin(username: string, password: string) {
    if (!username || !password) {
      alert('Please Type Username And Password')
      this.isAuth = false
    } else {
      this.http.post('http://localhost:4000/login', { username: username, password: password })
        .subscribe((data: any) => {
          console.log(data)
          if (data === true) {
            this.isAuth = true
            console.log(true)
            this.router.navigate(['/patsearch'])
          } else {
            console.log(false)
            this.isAuth = false
            alert('User or PW is Incorrect')
          }
        })
    }
  }
0

There are 0 best solutions below