简体   繁体   English

通过 MongoDB 的 Node.js 登录表单

[英]Node.js login form via MongoDB

Earlier, I had a site with login forms and such but no database connectivity.早些时候,我有一个带有登录表单等但没有数据库连接的站点。 I've now connected it to one with mongodb and have gotten some things working.我现在已经用 mongodb 将它连接到一个,并且已经开始工作了。 I'm able to use RESTED to send requests and create accounts and validate accounts within the database.我能够使用 RESTED 在数据库中发送请求并创建帐户和验证帐户。

I'm wondering, how would I be able to implement this functionality inside of a form?我想知道,我如何才能在表单内实现此功能? Where it would take the form details, query it through the database, and login if successful?它将在哪里获取表单详细信息,通过数据库查询,并在成功后登录? Same with registering.注册也是一样。

Here's the index:这是索引:

const config = require('config');
var Joi = require('joi');
Joi.objectId = require('joi-objectid')(Joi);
const mongoose = require('mongoose');
const users = require('./routes/users');
const auth = require('./routes/auth');
var express = require("express");
var hbs = require('express-handlebars');
var app = express();
var bodyParser = require('body-parser');

if (!config.get('PrivateKey')) {
    console.error('Error: PrivateKey is not defined.');
    process.exit(1);
}

mongoose.connect('mongodb://localhost/airbnb')
    .then(() => console.log('Now connected to MongoDB!'))
    .catch(err => console.error('Something went wrong', err));

app.use(bodyParser.urlencoded({ extended: true }));

app.set('view engine', 'hbs');

app.engine('hbs', hbs({
    extname: 'hbs', 
    defaultLayout: 'main',
    layoutsDir: __dirname + '/views/layouts',
    partialsDir: __dirname + '/views/partials/' 
}));


app.use('/static', express.static('public'));
app.use(express.json());
app.use('/api/users', users);
app.use('/api/auth', auth);

var HTTP_PORT = process.env.PORT || 8080;

// call this function after the http server starts listening for requests
function onHttpStart() {
    console.log("Express http server listening on: " + HTTP_PORT);
}

// setup a 'route' to listen on the default url path (http://localhost)
app.get("/", function (req, res) {
    res.render('home', {layout: false})
});

// setup another route to listen on /about
app.get("/roomList", function (req, res) {
    res.render('roomList', {layout: false})
});

app.get("/dashboard", function (req, res) {
    res.render('dashboard', {layout: false})
});

// setup http server to listen on HTTP_PORT
app.listen(HTTP_PORT, onHttpStart);

here's user.js这是 user.js

// require mongoose and setup the Schema
var mongoose = require("mongoose");
var Joi = require('joi');
const joiObjectid = require("joi-objectid");

// connect to the localhost mongo running on default port 27017
mongoose.connect("mongodb://localhost/airbnb");

// define the company schema
// register the Company model using the companySchema
// use the web322_companies collection in the db to store documents
var User = mongoose.model('User', new mongoose.Schema({
    email: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 255,
        unique: true
    },
    password: {
        type: String,
        required: true,
        minlength: 6,
        maxlength: 55555
    }
}));

// validate
function validateUser(user) {
    const schema = Joi.object({
        email: Joi.string().min(5).max(255).required().email(),
        password: Joi.string().min(6).max(55555).required()
    });
    return schema.validate(user);
}

// export

exports.User = User;
exports.validate = validateUser;

here's users.js这是 users.js

const jwt = require('jsonwebtoken');
const config = require('config');
const bcrypt = require('bcrypt');
const _ = require('lodash');
const { User, validate } = require('../models/user');
const express = require('express');
const router = express.Router();

router.post('/', async (req,res) => {
    const { error } = validate(req.body);
    if (error) {
        console.log(req.body.email);
        console.log(req.body.password);
        return res.status(400).send(error.details[0].message);
    }

    let user = await User.findOne({ email: req.body.email });
    if (user) {
        return res.status(400).send('That user already exists!');
    } else {
        user = new User(_.pick(req.body, ['name', 'email', 'password']));
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
        await user.save();
        const token = jwt.sign({_id: user._id }, config.get('PrivateKey'));
        res.header('x-auth-token', token).send(_.pick(user, ['_id', 'name', 'email']));
    }
});

module.exports = router;

here's auth.js这是 auth.js

const config = require('config');
const jwt = require('jsonwebtoken');
const Joi = require('joi');
const bcrypt = require('bcrypt');
const _ = require('lodash');
const { User } = require('../models/user');
const express = require('express');
const router = express.Router();

router.post('/', async (req, res) => {
    const { error } = validate(req.body);
    if (error) {
        return res.status(400).send(error.details[0].message);
    }

    let user = await User.findOne({ email: req.body.email });
    if (!user) {
        return res.status(400).send('Incorrect email or password');
    }

    const validPassword = await bcrypt.compare(req.body.password, user.password);
   if (!validPassword) {
       return res.status(400).send('Incorrect email or password');
   } 

   const token = jwt.sign({_id: user._id }, config.get('PrivateKey'));

   res.send(token);
});

function validate(req)
 {
    const schema = Joi.object({
        email: Joi.string().min(5).max(255).required().email(),
        password: Joi.string().min(6).max(55555).required()
    });
    return schema.validate(req);
 }
 
module.exports = router;

This is what my signup modal looks like currently:这是我的注册模式目前的样子:

 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Registration</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form name="regForm" method="get" action="dashboard" onsubmit="return validateSignupForm()">
                        <div class="form-group mb-0">
                            <label for="formGroupEmail"></label>
                            <input type="email" class="form-control" id="formGroupEmail" placeholder="Email address"
                                name="signupEmail">
                        </div>
                        <div class="form-group mb-0">
                            <label for="formGroupPassword"></label>
                            <input type="password" class="form-control" id="formGroupPassword" placeholder="Password"
                                name="signupPassword">
                        </div>
                </div>
                <div class="modal-footer">
                    <input type="submit" value="Sign up" class="btn btn-danger">
                </div>
                </form>
            </div>
        </div>
    </div>
function validateSignupForm() {

                var signupEmail = document.forms["regForm"]["signupEmail"].value;
                var signupPassword = document.forms["regForm"]["signupPassword"].value;

                if (signupPassword.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/)) {
                    return true;
                }
                else {
                    alert('Password must be between 6 and 20 characters and contain at least one number and uppercase letter');
                    return false;
                }

                

            }

Seems like that's a lot of efforts you are putting up with all that code, whereas you can simply use passport.js specifically passport-local-mongoose to get the register/login working with few lines of code.似乎这是您为所有代码付出的大量努力,而您可以简单地使用passport.js 特别是passport-local-mongoose来使用几行代码来获得注册/登录。 For submitting the form, You'll have to use something like ajax which can send requests to your backend server.为了提交表单,您必须使用类似 ajax 的东西,它可以向您的后端服务器发送请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM