I'm almost beginner to web dev. I'm making a pretty basic web page for login authentication. All I'm trying to do is to check user credentials (username & password) on my LoginPage from the database (mongoose) and redirect to the next page (MainPage) if they are correct.
Login.ejs (.html) file
<html>
<head>
<title>Login</title>
</head>
<body>
<form id="form_Login" action="/MainPage" method="post">
<input id="txt_username" type="text" required>
<br><input id="txt_password" type="password" required>
<br><input type="submit" value="Login">
</form>
</body>
</html>
app.js file
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema ({
username : String,
password : String
});
mongoose.model('User',User);
mongoose.connect('mongodb://localhost:27017/MyDB');
app.set('view engine', 'ejs');
app.get('/',function(req, res) {
res.render('LoginPage');
});
app.get('/MainPage',function(req, res) {
res.render('MainPage');
});
app.post('/MainPage', function(req, res) {
// new code should e over here
res.redirect('/MainPage');
});
app.get('*', function(req, res) {
res.send('Bad Route!');
});
var server = app.listen(3000, function() {
console.log('listening on port 3000.');
});
Any help would be appreciated.
I'm almost beginner to web dev. I'm making a pretty basic web page for login authentication. All I'm trying to do is to check user credentials (username & password) on my LoginPage from the database (mongoose) and redirect to the next page (MainPage) if they are correct.
Login.ejs (.html) file
<html>
<head>
<title>Login</title>
</head>
<body>
<form id="form_Login" action="/MainPage" method="post">
<input id="txt_username" type="text" required>
<br><input id="txt_password" type="password" required>
<br><input type="submit" value="Login">
</form>
</body>
</html>
app.js file
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema ({
username : String,
password : String
});
mongoose.model('User',User);
mongoose.connect('mongodb://localhost:27017/MyDB');
app.set('view engine', 'ejs');
app.get('/',function(req, res) {
res.render('LoginPage');
});
app.get('/MainPage',function(req, res) {
res.render('MainPage');
});
app.post('/MainPage', function(req, res) {
// new code should e over here
res.redirect('/MainPage');
});
app.get('*', function(req, res) {
res.send('Bad Route!');
});
var server = app.listen(3000, function() {
console.log('listening on port 3000.');
});
Any help would be appreciated.
Share Improve this question edited Jun 19, 2015 at 9:26 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Jun 16, 2015 at 12:10 aayaniaayani 39310 silver badges19 bronze badges 2- It's helpful to show any errors you are getting or to describe what undesired behavior your code demonstrates so that others can try to assist with specific questions rather than just a general task. – Ryan Livingston Commented Jun 16, 2015 at 12:46
- sir I've mentioned a ment in the second file where logic for code authentication from the db is required. – aayani Commented Jun 17, 2015 at 13:26
4 Answers
Reset to default 2If you try to pass a callback in findOne method it will generate an error written below :
MongooseError: Model.findOne() no longer accepts a callback
So, you don't need to pass a callback in findOne method(pass username in the Parameter), just assign the return value of the object in a variable if the object is found you will just check the condition of the password, by matching it with an entered value of the password from the frontend and already saved value of password in that object so if it matches it will redirect to the new page
var express = require('express');
var app = express();
var mongoose = require('mongoose');
/*use this library to get text from the form*/
var bodyParser=require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }));
var Schema = mongoose.Schema;
var User = new Schema ({
username : String,
password : String
});
mongoose.model('User',User);
mongoose.connect('mongodb://localhost:27017/MyDB');
app.set('view engine', 'ejs');
app.get('/',function(req, res) {
res.render('LoginPage');
});
app.get('/MainPage',function(req, res) {
res.render('MainPage');
});
app.post('/MainPage', function(req, res) {
/* add name attribute( e.g: name="username")in both html input tags*/
var chk_username= req.body.username;
var chk_password= req.body.password;
/* checking login credential here */
var check=User.findOne({username:chk_username})
if(chk){
if(User.password===chk_password){
res.redirect('/MainPage');}
else{
/*customize it according to your senario*/
console.log("incorrect password");}}
else{
/*customize it according to your senario*/
console.log("user does not exist")
}
});
app.get('*', function(req, res) {
res.send('Bad Route!');
});
var server = app.listen(3000, function() {
console.log('listening on port 3000.');
})
I would suggest you use the passport.js library for that. Not only does it provide you with a good way to create local authentication, you can later on integrate google, facebook and twitter (or any oAuth) social authentication methods.
You can read the documentation which should provide you with a good starting point, or any one of these examples:
- http://passportjs/docs
- http://mherman/blog/2013/11/11/user-authentication-with-passport-dot-js/#.VYAS0PlViko
- http://mherman/blog/2015/01/31/local-authentication-with-passport-and-express-4/#.VYAS0vlViko
- https://scotch.io/tutorials/easy-node-authentication-setup-and-local ( I have used this one in the past)
I suggest you start by using the passport-local scheme, which will give you exactly what you need. https://github./jaredhanson/passport-local
Use the body-parser middleware to get your form data and use it to query your database. First you need to do a npm install body-parser
. Then you could try something like the following. Note that this is very rough code however and you should probably use some other excellent libraries to handle authentication.
var express = require('express');
var app = express();
var bodyParser = require('body-parser);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema ({
username : String,
password : String
});
mongoose.model('User',User);
mongoose.connect('mongodb://localhost:27017/MyDB');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/',function(req,res)
{
res.render('LoginPage');
});
app.get('/MainPage',function(req,res)
{
res.render('MainPage');
});
app.post('/MainPage', function(req, res)
{
// new code should e over here
User.findOne({username: req.body.username, password: req.body.password}, function(err, user){
if(err) {
console.log(err);
}
else if(user){
res.redirect('/MainPage');
}
else {
console.log('Invalid');
}
});
});
app.get('*', function(req,res)
{
res.send('Bad Route!');
});
var server = app.listen(3000, function() {
console.log('listening on port 3000.');
});
You can use bodyPasser to get input from the html. (npm i body-parser. https://www.npmjs./package/body-parser).
You can use the mongoose to save the user and find the user (npm i mongoose) https://www.npmjs./package/mongoose.
I used here ejs.
Using the findOne you can find the register user is available or not https://mongoosejs./docs/api/model.html#model_Model-findOne.
//jshint esversion:6
const express = require('express');
const bodyPasser = require('body-parser');
const ejs = require('ejs');
const mongoose = require('mongoose');
const app = express();
app.use(express.static('public'));
app.set('view engine','ejs');
app.use(bodyPasser.urlencoded({ extended: true }));
mongoose.set("strictQuery", false);
mongoose.connect('mongodb://localhost:27017/userDB',{useNewUrlParser:true})
.then(() => console.log('Connected!'));
const userSchema = {
email:String,
password:String
}
const User = new mongoose.model("User",userSchema);
app.get("/",(req,res)=>{
res.render("home")
})
app.get("/register",(req,res)=>{
res.render("register")
})
app.get("/login",(req,res)=>{
res.render("login")
})
app.post("/register",(req,res)=>{
const newUser = new User({
email: req.body.username,
password: req.body.password,
});
newUser.save((err)=>{
if(err){
console.log(err);
}else{
res.render("secrets")
}
})
})
app.post("/login",(req,res)=>{
const username = req.body.username;
const password = req.body.password;
User.findOne({email:username},(err,user)=>{
if(err){
console.log(err);
}else{
if(user){
if(user.password === password){
res.render("secrets")
}
}
}
})
})
app.listen(3000,function(){
console.log("port is statrt at 3000");
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745230738a4617666.html
评论列表(0条)