Wednesday 10 May 2017

How to make auth with callback hell?

Create a auth system. When user make a post-query (router.js):

var user = require("../controllers/user");

router.post("/login", function(req, res, next){
    user.login(req, function(result) {
        res.send(result);
    });

File controllers/user.js:

var mongo = require("./mongo");

exports.login = function (req, callback) {
    var res;
    var login = req.body.login,
        password = req.body.password;

    var user = new mongo.User({
        login: login,
        password: password
    });

    //check if exist user
    user.findOne({
        login: login
    }, function (err, obj) {
        if (err) {
            console.log("user not found -> save");
            user.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    callback("OK");
                }
            });
        } else {
            console.log("ELSE");
            if (password == obj["password"]) {
                callback("OK");
            }
        }
    });
}

I want when user.login will finished create/make new user -> call callback with result.

exports.login = function(req, callback){
user.findOne(/...login or sign up new user.../);
callback("Success");
}

So in case when user authorized ->

user.login(req, function(result) {
        res.send(result); //this executes
    });

How to make this?



via user7103883

No comments:

Post a Comment