почему req.session.user "неопределен" после того, как я проверил авторизацию входа - PullRequest
0 голосов
/ 05 апреля 2020

Я вошел в систему пользователя и присвоил req.session.user значение, но когда я проверяю аутентификацию пользователя, я все еще получаю «undefined» в req.session.user, я не знаю, как это исправить Не могу понять почему "req.session.user" не определен при проверке аутентификации пользователя. Где мне не хватало?

const express = require('express');
const app = express();
const db = require ('../server/database/db.config');
const bodyparser  = require('body-parser');
const session = require('express-session');
const cors = require('cors')

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:true}))

app.use(cors({
  origin:'http://localhost:3000',
  methods: ["GET", "HEAD", "POST", "DELETE", "PUT", "PATCH", "OPTIONS"],
  credentials: true
}))

app.use(session({
    secret: 'secretkey',
    resave: false,
  saveUninitialized: true,
  cookie:{
    httpOnly:true,
    secure:false,
    expires: new Date(Date.now()+ 60*60*1000) 
  }
}));

app.post('/auth/login',(req,res)=>{
    var userdata = {
        email: req.body.email,
        password : req.body.password
    }
    User.findOne({where:{Email:userdata.email}}).then(user=>{
        if(!user){
            res.json({isLogin:false,statusMsg:'wrong email'})
        }
        bcrypt.compare(userdata.password,user.Password,(err,isMatch)=>{
            if (err) throw err;
            if(!isMatch){
                res.json({isLogin:false,statusMsg:'wrong password'})
            }
        })
        req.session.user = user.id;
        res.json({isLogin:true,statusMsg:'login success'})
        console.log(req.session.user) ---> this is working, i still get  the value
    }).catch(function(error) {
        console.log(error);
      });
})  

app.get('/auth/user',(req,res)=>{
    console.log(req.session.user) --->  undefined ? why ???? 
    if(req.session.user){
        res.json({isLogin:true})
    }else{
        res.json({isLogin:false})
    }
})

это моя клиентская сторона

import React, { Component } from 'react';
import Login from './component/login';
import {BrowserRouter ,Switch,Route,Redirect} from 'react-router-dom'
import Register from './component/register';
import './App.css';
import Dashboard from './component/Dashboard';
import Axios from 'axios';



class App extends Component {
   state={
    IsLoggedIn : false
   } 
   CheckUserAuth = ()=>{
       Axios.get("http://localhost:8080/auth/user",{withCredentials:true}).then(res=>{
         var data =  res.data;
         if(data.isLogin && !this.state.IsLoggedIn){
           this.setState({
             IsLoggedIn : true
           })
         }else if(!data.isLogin && this.state.IsLoggedIn ){
          this.setState({
            IsLoggedIn : false
          })
         }
      })
   }
  componentDidMount(){
    this.CheckUserAuth()
  }
  render(){
    const{IsLoggedIn} = this.state;
    const EnsureRoute = ({ component: Component, ...rest }) => (
      <Route {...rest} render={(props) => (
        IsLoggedIn === true
          ? <Component {...props} />
          : <Redirect to='/login' />
      )} />
    )
    const ForwardRoute = ({ component: Component, ...rest }) => (
      <Route {...rest} render={(props) => (
        IsLoggedIn === true
          ?<Redirect to='/dashboard' /> 
          : <Component {...props} />
      )} />
    )
    return (
      <div className="App">
        <BrowserRouter>
          <Switch> 
        <ForwardRoute path="/login" exact component={Login}/>
        <ForwardRoute path="/register" exact component={Register}/>
        <EnsureRoute path="/dashboard" exact component={Dashboard}/>
        </Switch>
      </BrowserRouter> 
      </div>
    );
  }
}

export default App;

и моя страница входа

import React,{Component} from "react";
import '../assets/css/login.css'
import {Link}  from  'react-router-dom'
import axios from "axios";


class Login extends Component {
  constructor(props){
    super(props)

  this.state= {
    Email : '',
    Password :'',
  }
}

  onChangeForm = (e) =>{
      this.setState({
        [e.target.id] : e.target.value
      })
  }
  onSubmitForm = (e)=>{
    e.preventDefault();
    axios.post('http://localhost:8080/auth/login',{
      email: this.state.Email,
      password: this.state.Password
    }).then(res=>{
      var data = res.data;
      if(data.isLogin){
        this.props.history.push('/dashboard')
    }else if(!data.isLogin){
      alert('login fail')
    }
    })
  }

render(){
  return (
    <div className="full-contain">
      <div className="form-box">
        <div class="form-part" style={{margin:"0px auto",marginBottom:"20px",backgroundColor:"#82b74b"}}>
          <h1>SIGN IN</h1>
          </div>
          <div class="form-part InputColorBg">
            <input type="text" placeholder="Email" id="Email" value={this.state.Email}onChange={this.onChangeForm}/>
            <i class="fa fa-user" aria-hidden="true"></i>
          </div>
          <div class="form-part InputColorBg">
            <input type="password"placeholder="Password" id="Password" value={this.state.Password} onChange={this.onChangeForm}/>
            <i class="fa fa-lock" aria-hidden="true"></i>
          </div>

          <div class="form-part"style={{marginBottom:"0px"}}>
          <label>
            <input type="checkbox" />
             <span style={{marginLeft:"10px",}}>Remember Me</span>
         </label>
          </div>

          <div class="form-part">
            <button onClick={this.onSubmitForm}>Login</button>
          </div>
          <div class="form-part">
          <p>Don't Have an Account? <Link to="/register">Register now !</Link> </p>
          </div>
      </div>
    </div>
  );
  }
}

export default Login;

...