facing error in passports login method its saying user not defined

19 views Asked by At
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import session from "express-session";
import passport from "passport";
import passportLocalMongoose from "passport-local-mongoose";

// ________________________________Defining constant______________________________________________

const app = express();
app.use(bodyParser.json());
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    // cookie: { secure: true } set this true before deploing
}))

app.use(passport.initialize());
app.use(passport.session());

// ________________________________ mongodb setup______________________________________________

mongoose.connect("mongodb://localhost:27017/HealR")
    .then(() => console.log('Connected to MongoDB'))
    .catch(err => console.error('MongoDB connection error:', err));



const subscription = new mongoose.Schema({

    email: String,
    planId: String,
    active: Boolean,
    startDate: Date,
    endDate: Date,
    paymentHash: String

})
const subscriptionDetail = mongoose.model("subscriptionDetail", subscription);

const appoinment = new mongoose.Schema({

    clientEmail: String,
    docEmail: String,
    type: String,
    date: Date,
    time: { type: Number, min: 0, max: 24 },
    active: Boolean,
    startDate: Date,
    en: Date,
    paymentHash: String

})
const appoinmentdetail = mongoose.model("appoinmentdetail", appoinment);

const userSchema = new mongoose.Schema(
    {
        username: String,
        email: {type:String,unique: true},
        password: String,
        wrokingProfession: String,
        age: Number,


    });



userSchema.plugin(passportLocalMongoose)
const userData = mongoose.model("userCred", userSchema);
passport.use(userData.createStrategy());
passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});


app.post("/healR/join", (req, res) => {

    userData.register({ username: req.body.username, email: req.body.email, wrokingProfession: req.body.wrokingProfession, age: req.body.age }, req.body.password, function (err, user) {
        if (err) {
            console.log(err);
            if (err="UserExistsError"){
                res.send( "user exist")
            }
        } else {

            passport.authenticate("local")(req, res, function () {
                res.send("signup complete")

            });
        }
    });

});

app.post("/healR/signIn",function(req,res){

    const User = new userData({
        email:req.body.email,
        password:req.body.password
    })

    req.logIn(User,function(err){
        console.log(User.email)

        console.log(req.body)
        console.log(err)
        if(err){
            console.log(err)
        }
        else{
            passport.authenticate("local")(req, res, function () {
                res.send("login complete")

            });
        }
    })
});


const Port = process.env.Port || 3000
app.listen(Port, () => {

    console.log('server listing on port :' + Port);
})

my registers method works just fine without any error but when i try to login i'm getting this error

ReferenceError: User is not defined
    at file:///P:/HealR/backend/index.js:78:5
    at pass (P:\HealR\backend\node_modules\passport\lib\authenticator.js:372:9)
    at Authenticator.deserializeUser (P:\HealR\backend\node_modules\passport\lib\authenticator.js:377:5)
    at SessionStrategy.authenticate (P:\HealR\backend\node_modules\passport\lib\strategies\session.js:112:10)
    at attempt (P:\HealR\backend\node_modules\passport\lib\middleware\authenticate.js:378:16)
    at authenticate (P:\HealR\backend\node_modules\passport\lib\middleware\authenticate.js:379:7)
    at Layer.handle [as handle_request] (P:\HealR\backend\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (P:\HealR\backend\node_modules\express\lib\router\index.js:328:13)
    at P:\HealR\backend\node_modules\express\lib\router\index.js:286:9
    at Function.process_params (P:\HealR\backend\node_modules\express\lib\router\index.js:346:12)`

this is frontend code. its very basic i just want test my function if they work.

signin.jsx

import { useState } from "react";
import axios from 'axios';

function signup() {


  const [email ,setemail]=useState("");
  const [password ,setpassword]=useState("");
 
  const handleSubmit = async(event) =>{
    event.preventDefault();
    if (!email || !password  ) {
      alert("Please fill in all required fields");
    }
    {
     
      try {
        const url = '/healR/signIn';
        const data = {
          email: email, 
          password :password,
          }; 
        const response = await axios.post(url, data);
        alert(response.data);
      } catch (error) {
        console.error(error);
      }
    
    }

  }
  return (
    <div className="sign up">
      <form >

      <input  onChange={(e) =>setemail(e.target.value)}  value={email} type="email" name="email" required/>
      <input  onChange={(e) =>setpassword(e.target.value)} value={password} type="password" name="password" required/>
      <button type="submit" onClick={handleSubmit} > submit</button>
  </form>
      
    </div>
    
  ); 
}

export default signup;

signup.jsx

import { useState } from "react";
import axios from 'axios';
import { Link } from "react-router-dom";

function signup() {

  const [name ,setname]=useState("");
  const [email ,setemail]=useState("");
  const [password ,setpassword]=useState("");
  const [cPassword ,setcPassword]=useState("");
  const [age ,setage]=useState("");
  const [profession ,setProfession]=useState();
  const [checkbox ,setCheckbox]=useState(false);
  const [isButtonDisabled, setIsButtonDisabled] = useState(false);
  

  
  const handleSubmit = async(event) =>{
    event.preventDefault();
    
    if (!name || !email || !password || !cPassword || !age || !profession || !checkbox) {
      alert("Please fill in all required fields and check the box.");
    }
    if(password !=cPassword){
      alert("password Does not match")
    }else{
      setIsButtonDisabled(true)
      try {
        const url = '/healR/join';
        const data = {
          username:name,
          email: email, 
          password :password,
          wrokingProfession : profession,
          age: age };
        const response = await axios.post(url, data);
        alert(response.data);
      } catch (error) {
        console.error(error);
      }
    
    }

  }
  return (
    <div className="sign up">
      <form action="/action_page.php">
    

      <input onChange={(e) =>setname(e.target.value)}value={name} type="text" name="name" required/>
      <input  onChange={(e) =>setemail(e.target.value)}  value={email} type="email" name="email" required/>
      <input  onChange={(e) =>setpassword(e.target.value)} value={password} type="password" name="password" required/>
      <input onChange={(e) =>setcPassword(e.target.value)}  value={cPassword} type="password" name="cPassword" required/>
      <input  onChange={(e) =>setage(e.target.value)} value={age} type="number" name="age" min="10" required/>

      <label htmlFor="cars">Choose a car:</label>
      <select  onChange={(e) => setProfession(e.target.value)}  value={profession}  name="profession" id="cars" required>
      <option value="">Select a profession</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
  </select>
  <input
  onChange={(e) =>setCheckbox(e.target.value)}
  type="checkbox"
  checked={checkbox}
  required
/>
<label>I liked this</label>
  <button type="submit" onClick={handleSubmit} disabled={isButtonDisabled}> submit</button>
  </form>
      
    </div>
    
  );
}

export default signup;

home.jsx

import { Link } from "react-router-dom";

function Home() {
    return (
        <div>
            <Link to="/healR/join"><button>signup</button></Link>
            <Link to="/healR/signIn"><button>signin</button></Link>
        </div>
    );
}

export default Home;

app.jsx


import {Route,Routes} from "react-router-dom"
import Signup from './signup';
import Home from './home';
import Signin from './signin';

function App() {
  return (
      <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/healR/join" element={<Signup />} />
          <Route path="/healR/signIn" element={<Signin />} />
      </Routes>
  );
}

export default App;


main.jsx

import ReactDOM from 'react-dom/client'
import App from './App.jsx'

import { BrowserRouter } from 'react-router-dom'

ReactDOM.createRoot(document.getElementById('root')).render(
  <BrowserRouter><App/></BrowserRouter>,
)

Is there a more easy way to do this?

i tried to login and i was expecting message::"login complete"

0

There are 0 answers