Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getting an error "ReferenceError: User is not defined",how to fix it #7273

Closed
mushthaque7 opened this issue Mar 18, 2023 · 3 comments
Closed

Comments

@mushthaque7
Copy link

Node version: 18.14.2
Sails version (sails):
ORM hook version (sails-hook-orm):
Sockets hook version (sails-hook-sockets):
Organics hook version (sails-hook-organics):
Grunt hook version (sails-hook-grunt):
Uploads hook version (sails-hook-uploads):
DB adapter & version (e.g. sails-mysql@5.55.5):
Skipper adapter & version (e.g. skipper-s3@5.55.5):


//jshint esversion:6 require("dotenv").config(); const express = require("express"); //hash encryption method //const md5 = require("md5"); const bodyParser = require("body-parser"); const ejs = require("ejs"); // const bcrypt = require("bcrypt"); const mongoose = require("mongoose"); const session = require('express-session'); const passport = require("passport"); const findOrCreate = require('mongoose-find-or-create') const passportlocalMongoose = require("passport-local-mongoose"); var GoogleStrategy = require('passport-google-oauth20').Strategy; // const saltRounds=10; //const encrypt = require("mongoose-encryption") const app = express(); app.use(express.static("public")); app.use(bodyParser.urlencoded({extended:true})); app.set("view engine","ejs"); app.use(session({ secret: 'A little secret', resave: false, saveUninitialized: false })); app.use(passport.initialize()); mongoose.connect("mongodb://127.0.0.1:27017/userDB",{useNewUrlParser:true}); const userSchema =new mongoose.Schema({ email : String, password : String }); userSchema.plugin(passportlocalMongoose); userSchema.plugin(findOrCreate); //password encryption using mongoose-encryption //userSchema.plugin(encrypt,{secret:process.env.SECRET,encryptedFields: ['password']}); const user = mongoose.model("user",userSchema);

passport.use(user.createStrategy())
passport.serializeUser(function(user, cb) {
process.nextTick(function() {
cb(null, { id: user.id, username: user.username });
});
});

passport.deserializeUser(function(user, cb) {
process.nextTick(function() {
return cb(null, user);
});
})

passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/secret",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));

app.get("/",(req,res)=>{
res.render("home");
});
app.get('/auth/google',
passport.authenticate('google', { scope: ["profile"] }));
app.get("/register",(req,res)=>{
res.render("register");
});
app.get("/auth/google/secret",
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});
app.get("/login",(req,res)=>{
res.render("login");
});
app.get("/secrets",(req,res)=>{
if(req.isAuthenticated()){
res.render("secrets");
}else{
res.redirect("/login");
}
});
app.get("/logout",(req,res)=>{
req.logout(function(err) {
if (err) {
return next(err);
}
res.redirect('/');
});
})
app.post("/register", (req,res)=>{
user.register({username:req.body.username},req.body.password,function(err,user){
if(err){
console.log(err)
res.redirect("/register");
}else{
passport.authenticate('local', {successRedirect: '/secrets',failureRedirect: '/register'});
}
});

// bcrypt.hash(req.body.password, saltRounds, function(err, hash) 
//     const newUser= new user({
//         email: req.body.username,
//         password: hash
//     });
//     newUser.save().then(()=>{
//         res.render("secrets");
//     }).catch((err)=>{
//         console.log(err)
//     });
// });

});
app.post("/login",(req,res)=>{
const users = new user({
username : req.body.username,
password : req.body.password
});
req.login(users,function(err){
if(err){
console.log(err);
}else{
passport.authenticate("local")(req,res,function(){
res.redirect("/secrets")
});
}
})

// const username= req.body.username;
// const password = req.body.password;
// user.findOne({email:username}).then((foundUser)=>{
//     if(foundUser){
//         bcrypt.compare(password, foundUser.password, function(err, result) {
//             if(result){
//                 res.render("secrets");
//             }
//         });
            
//         // else{
//         //     res.send("Invalid Password");
//         // }
//     }
// }).catch((err)=>{
//     console.log(err);
// });

});
app.listen(3000,function(){
console.log("Server started");
});

error output

ReferenceError: User is not defined
at Strategy._verify (C:\Users\MUSHTHAQUE\Downloads\Authentication\app.js:59:5)
at C:\Users\MUSHTHAQUE\Downloads\Authentication\node_modules\passport-oauth2\lib\strategy.js:205:24
at C:\Users\MUSHTHAQUE\Downloads\Authentication\node_modules\passport-google-oauth20\lib\strategy.js:122:5
at passBackControl (C:\Users\MUSHTHAQUE\Downloads\Authentication\node_modules\oauth\lib\oauth2.js:134:9)
at IncomingMessage. (C:\Users\MUSHTHAQUE\Downloads\Authentication\node_modules\oauth\lib\oauth2.js:157:7)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1359:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

@sailsbot
Copy link

@mushthaque7 Thanks for posting! We'll take a look as soon as possible.

In the mean time, there are a few ways you can help speed things along:

  • look for a workaround. (Even if it's just temporary, sharing your solution can save someone else a lot of time and effort.)
  • tell us why this issue is important to you and your team. What are you trying to accomplish? (Submissions with a little bit of human context tend to be easier to understand and faster to resolve.)
  • make sure you've provided clear instructions on how to reproduce the bug from a clean install.
  • double-check that you've provided all of the requested version and dependency information. (Some of this info might seem irrelevant at first, like which database adapter you're using, but we ask that you include it anyway. Oftentimes an issue is caused by a confluence of unexpected factors, and it can save everybody a ton of time to know all the details up front.)
  • read the code of conduct.
  • if appropriate, ask your business to sponsor your issue. (Open source is our passion, and our core maintainers volunteer many of their nights and weekends working on Sails. But you only get so many nights and weekends in life, and stuff gets done a lot faster when you can work on it during normal daylight hours.)
  • let us know if you are using a 3rd party plugin; whether that's a database adapter, a non-standard view engine, or any other dependency maintained by someone other than our core team. (Besides the name of the 3rd party package, it helps to include the exact version you're using. If you're unsure, check out this list of all the core packages we maintain.)

Please remember: never post in a public forum if you believe you've found a genuine security vulnerability. Instead, disclose it responsibly.

For help with questions about Sails, click here.

@eashaw
Copy link
Member

eashaw commented Mar 31, 2023

@mushthaque7 This doesn't seem to use Sails.

@DominusKelvin
Copy link
Contributor

Hey @mushthaque7 as @eashaw this doesn't look like Sails hence I will be closing this issue. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

4 participants