Node.js的用户身份验证

时间:2017-04-06 02:41:53

标签: node.js mongodb authentication express passport.js

我正在使用护照进行用户身份验证。首先,我创建了默认的管理员用户。现在,此管理员必须能够创建用户,但不能创建任何其他用户。为此,我在数据库中创建了一个Admin用户。现在我的问题是如何通过管理员创建其他用户,并且只有这个管理员应该可以访问所有API的路由,但不能让任何其他用户如何保护API?在server.js文件中,我创建了中间件函数

product = 0
for x in range(1,11):
    for y in range(1,11):
        product = x * y
        print('{:<4}'.format(product), end='')
    print()

请帮助解决这个问题。我希望你们不介意发布这么长的文件。

'authentication.js'

//Catch unauthorized errors
app.use(function (err, req, res, next) {
    if(err.name === 'UnauthorizedError') {
        res.status(401);
        res.json({"message": err.name + ":" + err.message});
    }
});

'用户model.js'

'use strict';
var passport = require('passport'),
    mongoose = require('mongoose'),
    Users = mongoose.model('Users');


var authentication = {

    register: function(req, res, name, email, password) {
        var userData = req.body;

        var user = new Users({
            email: userData.email,
            name: userData.name,
        });

        user.setPassword(userData.password);

        if(!user) {
            res.status(400).send({error: 'All fields required'});
        }

        user.save(function(err, result) {
            if(err) {
                console.log('Could not save the User');
                res.status(500).send({error: 'Could not save the User'});
            }else {
                res.send('New User Created Successfully');
            }
        });
    },

    login: function (req, res) {
        if(!req.body.email || !req.body.password) { 
            res.status(400).send({"message": "All fields required"});
            return;    
        }

        passport.authenticate('local', function (err, user, info) { 
            var token;

            if (err) { 
        res.status(404).send({err: 'An Error Occured'});
                return;
            }

            if(user) { 
                token = user.generateJwt();
        res.status(300).send({"token": token});
            }else { 
        res.status(401).send('Unauthorized User');
            }
        });
    }

};

module.exports = authentication;

'用户route.js'

'use strict';
var mongoose = require('mongoose'),
    crypto = require('crypto'),
    jwt = require('jsonwebtoken'),
    Schema = mongoose.Schema;

var userSchema = new mongoose.Schema({
    email: { 
        type: String,
        required: true,
        unique: true
    },
    name: { 
        type: String,
        required: true
    },
    hash: String, 
    salt: String
});



userSchema.methods.setPassword = function (password) {
    this.salt = crypto.randomBytes(16).toString('hex'); 
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); 
};

//Validating a submitted password
userSchema.methods.validPassword = function (password) {
    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
    return this.hash === hash;
};

//Generating a JSON Web Token
userSchema.methods.generateJwt = function () {
    var expiry = new Date();
    expiry.setDate(expiry.getDate() + 7);

    return jwt.sign({ 
        _id: this._id,
        email: this.email, 
        name: this.name,   
        exp: parseInt(expiry.getTime() / 1000) 
    }, process.env.JWT_SECRET); 
};

var User = mongoose.model('Users', userSchema);
var user = new User();
user.name = 'Arjun Kumar';
user.email = 'arjun@kumar.com';
user.setPassword('myPassword');
user.save();

'passport.js'

'use strict';
var express = require('express'),
    userRoute = express.Router(),
    jwt = require('express-jwt'),
    authentication = require('../controllers/authentication');

var auth = jwt({
    secret: process.env.JWT_SECRET,
    userProperty: 'payload'
});

userRoute.post('/:adminuserid/register', auth, authentication.register)
    .post('/login', authentication.login);

module.exports = userRoute;

1 个答案:

答案 0 :(得分:0)

有一件事你可以把所有的功能放在像这样的条件中,只给admin一个访问权限:

 If(req.user.email === your admin email) {

Your function 

}

这应该在您只想要管理员有权访问的路由下。

或者,如果您有多个管理员,那么您应该稍微更改一下架构并添加admin : Number,稍后您可以声明,例如,admin:1的任何用户都是系统管理员,否则不是。

我希望我能正确理解你的问题。

祝你好运