简体   繁体   English

使用JWT进行登录验证和密码恢复

[英]Login verification and Password recovery with JWT

I'm working on a web app and I wanna try using JWT for my user authentication and password recovery. 我正在开发一个Web应用程序,我想尝试使用JWT进行用户身份验证和密码恢复。 I need JWT to verify the valid user from my DB. 我需要JWT来验证数据库中的有效用户。 I tried this: 我尝试了这个:

login.js : login.js

var User        = require("../model/user/registerSchema").User;
var bcrypt      = require('bcrypt');
var utils       = require('../util/util'),
    config      = require('../config'),
    jwt         = require('jsonwebtoken');

/* Login Route. */

route = (app)=>{

    //POST
    app.post ('/login', (req, res) => {
        let {userName, password} = req.body;

        if (!utils.noEmptyParams(req.body)) res.json({success: false, message: config.messages.NO_DATA});

        else
            User.findOne({userName, password}, {password: 0})
                .exec()
                .then(user => {
                    if (user) {
                        user = JSON.parse(JSON.stringify(user));
                        jwt.sign(user, config.jwt.secret, config.jwt.options, (err, token) => {
                            res.json({
                                success: true,
                                user,
                                token,
                            });
                        });
                    } else {
                        res.json({success: false, message: config.messages.INVALID_CREDENTIALS});
                    }
                })
                .catch(error => {
                    utils.error(error);
                    res.json({success: false});
                });


    });
}

module.exports.route = route;

registerSchema.js registerSchema.js

var mongoose = require("mongoose"),
        db   = global.db,
    bcrypt   = require('bcrypt');
    var User = new mongoose.Schema();


// MONGOOSE MODEL CONFIGURATION
const RegisterSchema = new mongoose.Schema({
    access:{
        type: String,
        required:[true, 'please select proffession']
    },
    phone: {
        type: String,
        required: [true, 'Please add a username'],
        unique: true
    },
    firstName: {
        type: String,
        required: [true, 'Please enter your firstname']
    },
    lastName: {
        type: String,
        required: [true, 'Please add your last name']
    },
    password: {
        type: String,
        required: [true, 'Please add a password']
    },
    userName: {
        type: String,
        required: [true, 'Please add an email address'],
        unique: true
    },
    companyName: {
        type: String        
    },
});

    RegisterSchema.pre('save', function(next){
        var user = this;
        bcrypt.hash(user.password, 10, function(err, hash){
            if(err){
                return next(err);
            }
            user.password= hash;
            next()
        })
    })


module.exports = mongoose.model('User', RegisterSchema);

I am running on Node version: v9.4.0, I'm using postman to test. 我在Node版本:v9.4.0上运行,我正在使用邮递员进行测试。 When I try posting the require fields, 当我尝试发布要求字段时,

{

    "userName":       "njksdnf@fds.com",
    "password":       "1234567"
}

I got this error: 我收到此错误:

TypeError: Cannot read property 'findOne' of undefined
    at app.post (/home/user/Home/Node/Routers/login.js:19:18)

I have seen WT-user-authentication-API-bolilerplate , but it doesn't seem to help fully. 我已经看过WT-user-authentication-API-bolilerplate ,但是它似乎并没有完全帮助您。

Any idea on how I can resolve it and how JWT can be used in this case for password recovery? 关于如何解决它以及在这种情况下如何将JWT用于密码恢复的任何想法?

For the 为了

TypeError: Cannot read property 'findOne' of undefined
    at app.post (/home/user/Home/Node/Routers/login.js:19:18)

gotten from postman, all thanks to Striped in the comment. 从邮递员那里得到的,这一切都归功于Striped的评论。 removing the .User did the whole magic for me. 删除.User了我.User

Making my code to now be: 使我的代码现在是:

var User        = require("../model/user/registerSchema");

instead of: 代替:

var User        = require("../model/user/registerSchema").User;

Still left with the question "Any idea on how JWT can be used in this case for password recovery? 仍然有一个问题“关于在这种情况下如何使用JWT进行密码恢复的任何想法?

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

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