验证节点 js 中的特定请求

Validation on specific request(s) in node js

我参考这个 link 创建了一个 api 它以下列方式验证请求:

router.post('/authenticate', function(req, res) {

        var query = "SELECT * FROM ?? WHERE ??=? and ??=? LIMIT 1";
        var table = ["users","user_email",req.body.user_email, "user_password",md5(req.body.user_password)];
        query = mysql.format(query,table);
        connection.query(query,function(err,rows){
            if(err) {
                res.json({"Error" : true, "Message" : "Error executing MySQL query"});
            } else {
                if(rows.length > 0){
                    var user = {'user_email':rows.user_email, 'user_password':rows.user_password}
                    var token = jwt.sign(user, app.get('superSecret'), {
                        expiresIn: '24h' // expires in 24 hours
                    });
                    delete rows[0].user_password;
                    // return the information including token as JSON
                    res.status(200).json({
                        error: false,
                        message: 'success',
                        token: token,
                        user:rows
                    });
                } else {

                    res.status(404).json({"Error" : true, "Message" : "No records found"});
                }
            }
        });
    });

    router.post("/users",function(req,res){
        req.checkBody({
            'user_email': {
                notEmpty: true,
                isEmail: {
                    errorMessage: 'Invalid Email'
                }
            },
            'user_password': {
                notEmpty: true,
                isLength: {
                    options: [{ min: 6, max: 10 }],
                    errorMessage: 'Password must be between 6 and 10 chars long' // Error message for the validator, takes precedent over parameter message
                },
                errorMessage: 'Invalid Password' // Error message for the parameter
            },
            'user_name': { //
                notEmpty: true, // won't validate if field is empty
                isLength: {
                    options: [{ min: 2, max: 10 }],
                    errorMessage: 'Must be between 2 and 10 chars long' // Error message for the validator, takes precedent over parameter message
                },
                errorMessage: 'Invalid User Name'
            },
            'phone_number': { //
                notEmpty: true,
                isLength: {
                    options: [{ min: 10, max: 15}],
                    errorMessage: 'Must be between 10 and 15 chars long' // Error message for the validator, takes precedent over parameter message
                },
                errorMessage: 'Invalid Phone Number'
            },
            'address': { //
                notEmpty: true,
                isLength: {
                    options: [{ min: 10, max: 100}],
                    errorMessage: 'Must be between 10 and 100 chars long' // Error message for the validator, takes precedent over parameter message
                },
                errorMessage: 'Invalid Address'
            },
            'device_type': { //
                notEmpty: true,
                errorMessage: 'Invalid device type'
            },
            'login_type': { //
                notEmpty: true,
                errorMessage: 'Invalid login type'
            },
            'gcm_user_id': { //
                notEmpty: true,
                errorMessage: 'Invalid gcm id'
            }
        });
        var errors = req.validationErrors();
        if (errors) {
            res.status(500).json(errors);
            return;
        }

        var query = "INSERT INTO ??(??,??,??,??,??,??,??,??) VALUES (?,?,?,?,?,?,?,?)";
        var table = ["users","user_name", "user_email", "user_password", "phone_number", "address", "device_type", "login_type", "gcm_user_id",
            req.body.user_name, req.body.user_email, md5(req.body.user_password), req.body.phone_number, req.body.address,
            req.body.device_type, req.body.login_type,req.body.gcm_user_id];
        query = mysql.format(query,table);
        connection.query(query,function(err,record){
            if(err) {
                res.status(500).json({"Error" : true, "Message" : err.message});
            } else {
                var query = "select * from ?? WHERE ?? = ?";
                var table = ["users", "id", record.insertId];
                query = mysql.format(query,table);
                connection.query(query,function(err,rows){
                    if(err) throw err;
                    res.status(200).json({"Error" : false, "message" : "User Added !", "data":rows});
                });
            }
        });
    });

    // route middleware to verify a token
    router.use(function(req, res, next) {

        // check header or url parameters or post parameters for token
        var token = req.headers['x-access-token'];
        console.log(token,'token');
        // decode token
        if (token) {

            // verifies secret and checks exp
            jwt.verify(token, app.get('superSecret'), function(err, decoded) {
                if (err) {
                    console.log(err);
                    return res.json({ success: false, message: 'Failed to authenticate token.' });
                } else {
                    // if everything is good, save to request for use in other routes
                    req.decoded = decoded;
                    next();
                }
            });

        } else {

            // if there is no token
            // return an error
            return res.status(401).send({
                success: false,
                message: 'No token provided.'
            });

        }
    });

我想通过以下方式验证请求:

示例: router.get("/users", jwtValidate ,function(req,res)

目前为了避免身份验证,我必须在中间件之上应用路由。

您可以通过以下方式验证请求:

router.get("/users", router.jwtValidate ,function(req,res){
      //logic here
});

    /**
     * Require Mobile Login Routing middleware
     * This function check if user loggedIn from mobile then verify it's Token.
     * Here we implement middleware of mobile Auth
     */
    router.jwtValidate = function(req, res, next) {
            var token;
            if (req.headers && req.headers.authorization) {
                var parts = req.headers.authorization.split(' ');

                if (parts.length == 2) {
                    var scheme = parts[0],
                        credentials = parts[1];

                    if (/^Bearer$/i.test(scheme)) {
                        token = credentials;
                    }
                } else {
                    return res.json(401, {message: 'Format is Authorization: Bearer [token]'});
                }
            } else if (req.param('token')) {
                token = req.param('token');

                // We delete the token from query and body to not mess with blueprints
                delete req.query.token;
                delete req.body.token;
            } else {
                return res.status(401).send({
                    message: 'No Authorization header was found'
                });
            }


            tokenService.verifyToken(token, function (error, token) {
                if (error) {
                    return res.json(401, {message: 'User is not logged in'});
                } else {
                    req.token = token;
                    req.user = token;
                    return next();
                }
            });
    }

对于令牌服务,您可以使用以下代码:

/**
 * jwt token service
 */

var jwt = require('jsonwebtoken');
var config = require('config');

// With this method we generate a new token based on payload we want to put on it
module.exports.issueToken = function(payload) {
    return jwt.sign(
        payload, // This is the payload we want to put inside the token
        'config.secret' // Secret string which will be used to sign the token
    );
};

// Here we verify that the token we received on a request hasn't be tampered with.
module.exports.verifyToken = function(token, verified) {
    if(token && verified) {
        return jwt.verify(
            token, // The token to be verified
            'config.secret', // The secret we used to sign it.
            {}, // Options, none in this case
            verified // The callback to be call when the verification is done.
        );
    }
};