Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
nodejs mysql login and signup project
// config/database.js
module.exports = {
'connection': {
'host': '127.0.0.1', // localde iseniz bu , local değilse ip adresini yazınız .
'user': 'root', // kullanıcı adı
'password': 'password', // şifreniz
'database': 'db'// database ismi .
},
'database': 'db',
};
<!DOCTYPE HTML>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="keyword" content="HTML, CSS, JAVASCRİPT">
<meta name="author" content="">
<title>Kayıt işlemi</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<title></title>
</head>
<body><br><br><br>
<div class="container">
<div class="">
<% rows.forEach(function(rows) { %>
<h2>name :<%=rows.username%> </h2><br>
<h2>pass : <%=rows.password%> </h2>
<% }); %>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Giriş yap</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
body { padding-top:80px; }
</style>
</head>
<body>
<div class="container" >
<div class="col-sm-6 col-sm-offset-3">
<h1><span class="fa fa-sign-in" ></span> Login</h1>
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<!-- LOGIN FORM -->
<form action="/login" method="post" >
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">login</button>
</form>
<hr>
<p>new user <a href="/signup">register</a></p>
</div>
</div>
</body>
</html>
var LocalStrategy = require('passport-local').Strategy;
var mysql = require('mysql');
var bcrypt = require('bcrypt-nodejs');
var dbconfig = require('./database');
var connection = mysql.createConnection(dbconfig.connection);
connection.query('USE ' + dbconfig.database);
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
connection.query("SELECT * FROM users WHERE id = ? ",[id], function(err, rows){
done(err, rows[0]);
});
});
passport.use(
'local-signup',
new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true
},
function(req, username, password, done) {
connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows) {
if (err)
return done(err);
if (rows.length) {
return done(null, false, req.flash('signupMessage', 'That username is already taken.'));
} else {
var newUserMysql = {
username: username,
password: bcrypt.hashSync(password, null, null)
};
var insertQuery = "INSERT INTO users ( username, password ) values (?,?)";
connection.query(insertQuery,[newUserMysql.username, newUserMysql.password],function(err, rows) {
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
}
});
})
);
passport.use(
'local-login',
new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true
},
function(req, username, password, done) {
connection.query("SELECT * FROM users WHERE username = ?",[username], function(err, rows){
if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'bulunamadi.'));
}
if (!bcrypt.compareSync(password, rows[0].password))
return done(null, false, req.flash('loginMessage', 'yanlis parola.'));
return done(null, rows[0]);
});
})
);
};
var dbconfig = require('../config/database');
var mysql = require('mysql');
var connection = mysql.createConnection(dbconfig.connection);
var bcrypt = require('bcrypt-nodejs');
module.exports = function(app,passport) {
app.get('/',isLoggedIn,function(req,res){
var row = [];
var row2=[];
connection.query('select * from users where id = ?',[req.user.id], function (err, rows) {
if (err) {
console.log(err);
} else {
if (rows.length) {
for (var i = 0, len = rows.length; i < len; i++) { //query den gelen bütün parametreleri rows sınıfına ekliyoruz .
row[i] = rows[i];
}
}
console.log(row);
}
res.render('index.ejs', {rows : row}); // user.ejs ye gönderiyoruz .
});
});
app.get('/login', function(req, res) {
res.render('login.ejs',{ message: req.flash('loginMessage') });
});
app.get('/signup', function(req, res){
res.render('signup.ejs',{message: req.flash('message')});
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/login',
failureRedirect: '/signup',
failureFlash : true
}));
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/',
failureRedirect : '/login',
failureFlash : true
}),
function(req, res) {
console.log("hello");
if (req.body.remember) {
req.session.cookie.maxAge = 1000 * 60 * 3;
} else {
req.session.cookie.expires = false;
}
res.redirect('/');
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
};
function isLoggedIn(req,res,next){
if(req.isAuthenticated())
return next();
res.redirect('/login');
}
var dbconfig = require('./config/database');
var mysql = require('mysql');
var connection = mysql.createConnection(dbconfig.connection);
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app = express();
var port = process.env.PORT || 3000;
var passport = require('passport');
var flash = require('connect-flash');
require('./config/passport.js')(passport);
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/views'));
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({
secret: 'kodizimcomisrunning',
resave: true,
saveUninitialized: true
} )); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('kodizimcomisrunning localhost: ' + port);
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="keyword" content="HTML, CSS, JAVASCRİPT">
<meta name="author" content="">
<title>Kayıt işlemi</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
body { padding-top:80px; }
</style>
</head>
<body>
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
<h1><span class="fa fa-sign-in"></span> Register</h1>
<!-- show any messages that come back with authentication -->
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<!-- LOGIN FORM -->
<form action="/signup" method="post">
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Save</button>
</form>
<hr>
<p>Already have user <a href="/login">login</a></p>
<p><a href="/">Home Page</a>.</p>
</div>
</div>
</body>
</html>
@sumitsngh000

This comment has been minimized.

Copy link

@sumitsngh000 sumitsngh000 commented May 25, 2018

where is the database of this code???????

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Dec 26, 2018

can u add email id and conform password in that

@vimalshaggy

This comment has been minimized.

Copy link

@vimalshaggy vimalshaggy commented Jan 21, 2019

im used this but get the error please solve it

F:\Tutorial\nodejs\login\node_modules\mysql\lib\protocol\Parser.js:80
throw err; // Rethrow non-MySQL errors

TypeError: Cannot read property 'insertId' of undefined

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