GithubHelp home page GithubHelp logo

manjeshpv / node-express-passport-mysql Goto Github PK

View Code? Open in Web Editor NEW
402.0 26.0 214.0 17 KB

Login Express + Passport + MySQL

Home Page: https://github.com/manjeshpv/awesome-sandbox

JavaScript 68.85% EJS 31.15%
mysql passport database javascript

node-express-passport-mysql's Introduction

Complete Guide to Node Authentication with MySQL

❤️ Visit FullStack Framework 2023

Code for the entire scotch.io tutorial series: Complete Guide to Node Authentication with MongoDB

Current version database is ported to MySQL

We will be using Passport to authenticate users locally,

Instructions

If you would like to download the code and try it for yourself:

  1. Clone the repo: git clone [email protected]:manjeshpv/node-express-passport-mysql.git
  2. Install packages: npm install
  3. Edit the database configuration: config/database.js
  4. Create the database schema: node scripts/create_database.js
  5. Launch: node server.js
  6. Visit in your browser at: http://localhost:8080

Licence: 1

node-express-passport-mysql's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-express-passport-mysql's Issues

TypeError: Cannot read property 'insertId' of undefined

Hi, I add a new column and like this:

connection.query('
CREATE TABLE IF NOT EXISTS ' + dbconfig.database + '.' + dbconfig.users_table + ' (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
password CHAR(60) NOT NULL,
PRIMARY KEY (id),
email CHAR(60) NOT NULL,
UNIQUE INDEX id_UNIQUE (id ASC),
UNIQUE INDEX username_UNIQUE (username ASC)
)');

And on signup comes:

The magic happens on port 8080
GET /signup 200 20ms - 1.09kb
D:\node-express-passport-mysql\node_modules\mysql\lib\protocol\Parser.js:82
throw err;
^
TypeError: Cannot read property 'insertId' of undefined
at Query._callback (D:\node-express-passport-mysql\config\passport.js:67:47)

at Query.Sequence.end (D:\node-express-passport-mysql\node_modules\mysql\lib

\protocol\sequences\Sequence.js:96:24)
at Query.ErrorPacket (D:\node-express-passport-mysql\node_modules\mysql\lib
protocol\sequences\Query.js:94:8)
at Protocol._parsePacket (D:\node-express-passport-mysql\node_modules\mysql
lib\protocol\Protocol.js:271:23)
at Parser.write (D:\node-express-passport-mysql\node_modules\mysql\lib\proto
col\Parser.js:77:12)
at Protocol.write (D:\node-express-passport-mysql\node_modules\mysql\lib\pro
tocol\Protocol.js:39:16)
at Socket. (D:\node-express-passport-mysql\node_modules\mysql\lib
\Connection.js:96:28)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)

How i can fix it?

Rethrow non-MySQL errors

Hi, thank you for sharing this useful project.
When I launch this project, I encounter a mysql problem.
It's always happened when I try to login.

./node-express-passport-mysql-master/node_modules/mysql/lib/protocol/Parser.js:78
        throw err; // Rethrow non-MySQL errors
        ^
Incorrect arguments

However, when I did signup, then I wouldn't have this problem. Everything works fine.
I tried to find solutions from the internet, but it didn't work.
Do you have any idea about this error?
I really appreciate your help.

bcrypt not used

Thank you for this work, it really help me.
I think you missed the bcrypt function on mysql version.
the hash is being used only in the user model but you don't use it here so the passwords are stored without any hash.

Passport JS auth middleware issue

I am implementing auth using passport js and database is mysql. My successRedirect route is '/main' and in the main route, I have added a middleware (isAuthenticated). But the issue is that, after entering valid credentials, I am not being redirected to '/main', instead, it just timeouts. I tried without adding middleware to '/main' route and it works fine.

var isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
return next;
}
res.redirect("/login")
}

// AUTH Implementation

app.use(session( {
secret: "asdnoifjasofijmaofmjkneknf",
resave: false,
saveUninitialized: false
}))

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

passport.use(new localStrategy(
function(username, password, done) {
connection.query("SELECT password FROM user" +
" WHERE email = ?", [username], function (err, results, fields) {
if (err) {
console.log(err);
}
else if (results.length === 0) {
done(null, false);
}
else {
console.log("Results");
console.log(results[0]);
hashedPassword = results[0].password;
bcrypt.compare(password, hashedPassword, function (err, response) {
if (response) {
console.log("True");
return done(null, true);
}
else {
console.log("False");
return done(null, false);
}
})
}
})
}
));

passport.serializeUser(function(ID, done) {
done(null, ID);
});

passport.deserializeUser(function(ID, done) {
connection.query("SELECT * FROM user WHERE userID = ?", [ID], function (err, results, fields) {
if (err) throw err;
else if (results.length === 0) done(null, false);
else {
done(null, results[0]);
}
})
done(null, ID);
});

app.post("/login", passport.authenticate('local', {
successRedirect: "/main",
failureRedirect: "/login"
}))

app.get("/main", isAuthenticated, function(req, res) {
res.send("In the main page");
})

ER_NOT_SUPPORTED_AUTH_MODE

I had this problem.
It helped me:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'

I used it one time via Workbench.

'PROTOCOL_ENQUEUE_AFTER_QUIT'

The problem is from the managing of connection.end() and connection.connect(). I deleted all these commands and it worked pretty well. I'm assuming the code needs a review so the connections at the database don't make problems anymore

Thanks

Thanks for sharing this, it helped me get started with things. One thing I added was I use mysql escaping on the email otherwise you could suffer from a SQL injection attack right ?

database errors

Apologies for the newbie question: but running "node scripts/create_database.js" during the setup process returns the error:

Success: Database Created!
events.js:160
      throw er; // Unhandled 'error' event
      ^
Error: connect ECONNREFUSED 127.0.0.1:3306
    at Object.exports._errnoException (util.js:1018:11)
    at exports._exceptionWithHostPort (util.js:1041:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)

And if I try running "node server.js" (even though the previous step didn't work), I get:

The magic happens on port 8080
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED 127.0.0.1:3306
    at Object.exports._errnoException (util.js:1018:11)
    at exports._exceptionWithHostPort (util.js:1041:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14) 

I'm confused because, I don't even understand which file the error is occurring in. Searching the error online did not yield any fruitful results for me. Are there a specific couple of lines of code I have to change, and if so in which file (and how)? Thank you.

DB close connection

Hi,

Thank you for your project it help me a lot !
I dont know if you still maintain the project but i use it today and i got this error:

Error: Connection lost: The server closed the connection.
at Protocol.end (C:\wamp\www\Test_projects\fb\node-express-passport-mysql-ma
ster\node_modules\mysql\lib\protocol\Protocol.js:109:13)
at Socket. (C:\wamp\www\Test_projects\fb\node-express-passport-my
sql-master\node_modules\mysql\lib\Connection.js:102:28)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at nextTickCallbackWith2Args (node.js:474:9)
at process._tickCallback (node.js:388:17)

I solved it by closing the connection after every db request.

POST /login 500

I run the sever is ok at the first time,but when I try to login after a time.That will be "POST /login 500 217.833 ms - 1355".My code:

passport.use(
        'local-login',
        new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'username',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, username, password, done) { // callback with email and password from our form
            connection.query("SELECT * FROM palcan_datacenter.user_tbl WHERE name = ?;",[username],function(err,rows){
                if (err){
                    return done(err);
                }

                if (!rows.length) {
                    return done(null, false, req.flash('loginMessage', 'No user here.')); // req.flash is the way to set flashdata using connect-flash
                }
                
                // if the user is found but the password is wrong
                if (!( rows[0].password == password)){
                    return done(null, false, req.flash('loginMessage', 'Passport is not correct.')); // create the loginMessage and save it to session as flashdata
                }
                var json={};
                json.id=rows[0].uid;
                json.name=rows[0].name;
                json.password=rows[0].password;
                return done(null, json);
            });
        })
    );`
```

strange call

Greetings from Barcelona,

I just started with node + mysql ... etc, my apologies, firstly.
He implemented the application and it works very well even though the server has returned me

C:\Balances\ServidorNode\node-express-passport-mysql-master>node server.js
The magic happens on port 8080
.....etc etc
GET http://www.teddybrinkofski.com/ip_json.php 404 14.663 ms - 150

You could indicate why you call that page ....

I regret this amateur question;)

Saludos desde Barcelona,

Acabo de empezar con node+mysql...etc, mis disculpas, primeramente.
He implementado s/aplicación y funciona muy bien aunque el servidor me ha devuelto

C:\Balances\ServidorNode\node-express-passport-mysql-master>node server.js
The magic happens on port 8080

GET http://www.teddybrinkofski.com/ip_json.php 404 14.663 ms - 150

Podrias indicar porque llama a dicha pagina....

lamento esta pregunta de aficionado ;)

PROTOCOL_ENQUEUE_AFTER_QUIT or PROTOCOL_ENQUEUE_HANDSHAKE_TWICE

PROTOCOL_ENQUEUE_AFTER_QUIT or PROTOCOL_ENQUEUE_HANDSHAKE_TWICE is created with so many connect() and end() in the code, I tried removing many of these from the code. I don't think it's a perfect solution even tho I could connect it with my database for storing details.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.