我想在我的node.js Express服务器启动时执行一个函数并执行一个auth模块,这是正确的方法吗?

时间:2019-03-06 10:41:27

标签: node.js express routing node-modules

我目前正在构建服务器,以便在启动时使用服务器/应用程序侦听器执行身份验证功能。我正在尝试在控制器文件中使用外部函数来执行此操作,服务器代码如下:

//Start listener on the port
app.listen(port, () => {
    console.log(`Server is listening to port ${port}... (http\://localhost\:3000)`);
});

//Start Authentication when server starts
app.on('listening', () => {
    console.log('Running Authentication...')
    auth.main()
});

并且正在我的auth中使用这些异步模块,这是执行启动功能的正确方法吗?对于要发送回的数据,是否应该将它们存储在全局变量中,然后在函数末尾使用“ res.send”?有什么办法可以改善我的代码?

const main = (req, res) => {
//Asynchronous Waterfall Call of 'Getting Access Tokens' (Stages 1-3)
async.waterfall([
    getCookieData,
    getAuthCode,
    getAccessToken
], (err, result) => {
    if (err) {
        alert('Something is wrong!');
    }
    return alert('Done!');
});

//STAGE 1 - USE CUSTOMER DETAILS TO RETRIEVE COOKIE AND CSRF SESSION DATA
getCookieData = async (callback) => {
        //If the paramter test passes then proceed
        var options = {
            //Type of HTTP request
            method: 'POST',
            //URI String
            uri: authURL,
            //HTTP Query Strings
            qs: {
                'client_id': clientID
            },
            //HTTP Headers
            headers: {
                'cache-control': 'no-cache',
                'Accept': 'application/json',
                'Host': host,
                'Content-Type': 'application/json'
            },
            //HTTP Body
            body: {
                'username': username,
                'password': password
            },
            json: true // Automatically stringifies the body to JSON
            //resolveWithFullResponse: true // Get the full response instead of just the body
            //simple: false // Get a rejection only if the request failed for technical reasons
        };
        console.log(`Beginning HTTP POST Request to ${authURL}...`);

        //await literally makes JavaScript wait until the promise settles, and then go on with the result.
        await rp(options)
        .then((parsedBody) => {
            //POST Succeeded...
            Console.log('Successful HTTP POST!');
            try {
                let csrf = response.body('csrftoken'),
                    ses = response.body('session'),
                    sesk = `session=${ses}`;
            } catch (e) {
                console.log(`STAGE 1 - Error occurred when assigning url variables. Error: ${e}`);
                console.error('STAGE 1 - Error occurred when assigning url variables. Error:', e);
                callback(`STAGE 1 - Error occurred when assigning url variables. Error: ${e}`)
            }
            console.log(`Successful grab of the cookie: ${ses} and csrf token: ${csrf}. Getting authorisation code now!`);
            //Asynchronous callback for the next function - return = defensive architecture 
            return callback(null, authCodeURL, customerID, clientID, csrf, sesk);
        })
        .catch((err) => {
            if (res.statusCode == 400) {
                console.log(`Error Message: ${res.body.message}. Status: ${res.body.status}`);
                console.error('Error Message:', res.body.message, 'Status:', res.body.status);
                callback(`Error Message: ${res.body.message}. Status: ${res.body.status}`);
            } else if (res.statusCode == 401) {
                console.log(`Error Message: ${res.body.message}. Status: ${res.body.status}`);
                console.error('Error Message:', res.body.message, 'Status:', res.body.status);
                callback(`Error Message: ${res.body.message}. Status: ${res.body.status}`);
            } else {
                console.log(`Failed to retrieve the cookie data! Error: ${error}`);
                console.error('Failed to retrieve the cookie data! Error:', error);
                callback(`Failed to retrieve the cookie data! Error: ${error}`);
            }
        });
    },

    //STAGE 2 - USE COOKIES AND CSRF TOKEN TO GET AUTH CODE
    //Is the word async needed? it is not asyncchronous but sequential
    getAuthCode = async (authCodeURL, customerID, clientID, csrf, sesk, callback) => {
            //If successful, proceed:
            var options = {
                method: 'POST',
                uri: authCodeURL,
                qs: {
                    'client_id': clientID,
                    'response_type': 'code',
                    'scope': 'all'
                },
                headers: {
                    'X-CSRF-TOKEN': csrf,
                    'Accept': 'application/json',
                    'Cookie': sesk,
                    'Content-Type': 'application/json'
                },
                body: {
                    'customer_id': customerID
                },
                json: true // Automatically stringifies the body to JSON
            };
            console.log(`Beginning HTTP POST Request to ${authCodeURL}...`);

            //await literally makes JavaScript wait until the promise settles, and then go on with the result.
            await rp(options)
                .then((parsedBody) => {
                    //POST Succeeded...
                    Console.log('Successful HTTP POST!');
                    try {
                        let authCode = response.body.JSON('auth_code'),
                            swapurl = `https://${host}${url3}`;
                    } catch (e) {
                        console.log(`STAGE 2 - Error occurred when assigning url variables. Error: ${e}`);
                        console.error('STAGE 2 - Error occurred when assigning url variables. Error:', e);
                        callback(`STAGE 2 - Error occurred when assigning url variables. Error: ${e}`);
                    }
                    console.log(`The authorisation Code is ${authcode}. Getting Access Token now!`);
                    //Asynchronous callback for the next function - return = defensive architecture
                    return callback(null, swapURL, clientID, clientSecret, authCode);
                })
                .catch((err) => {
                    if (res.statusCode == 400) {
                        console.log(`Error Message: ${res.body.message}. Extra: ${res.body.extra}`);
                        console.error('Error Message:', res.body.message, 'Extra:', res.body.extra);
                        callback(`Error Message: ${res.body.message}. Extra: ${res.body.extra}`);
                    } else {
                        console.log(`Failed to retrieve the authorisation code! Error: ${error}`);
                        console.error('Failed to retrieve the authorisation code! Error: ', error);
                        callback(`Failed to retrieve the authorisation code! Error: ${error}`);
                    }
                });
        },

        //STAGE 3 - USE AUTH CODE TO GET ACCESS TOKEN
        //ASYNC NEEDED?
        getAccessToken = async (swapURL, clientID, clientSecret, authCode, callback) => {
            //If successful, proceed:
            var options = {
                method: 'POST',
                uri: swapURL,
                qs: {
                    'client_id': clientID,
                    'grant_type': 'authorization_code',
                    'client_secret': clientSecret,
                    'code': authCode
                },
                json: true // Automatically stringifies the body to JSON
            };
            console.log(`Beginning HTTP POST Request to ${swapURL}...`);

            //await literally makes JavaScript wait until the promise settles, and then go on with the result.
            await rp(options)
                .then((parsedBody) => {
                    //POST Succeeded...
                    Console.log('Successful HTTP POST!');
                    try {
                        let accessToken = response.body('access_token'),
                            refreshToken = response.body('refresh_token');
                    } catch (e) {
                        console.log(`STAGE 3 - Error occurred when assigning url variables. Error: ${e}`);
                        console.error('STAGE 3 - Error occurred when assigning url variables. Error:', e);
                        callback(`STAGE 3 - Error occurred when assigning url variables. Error: ${e}`);
                    }
                    console.log(`The access Token is ${accessToken} and the refreshToken which is ${refreshToken}! These are only valid for 2 hours!`);
                    //Asynchronous callback for the waterfall - return = defensive architecture
                    return callback(null, 'done');
                })
                .catch((err) => {
                    console.log(`Failed to retrieve the access/refresh Token! Error: ${error}`);
                    console.error('Failed to retrieve the access/refresh Token! Error:', error);
                    callback(`Failed to retrieve the access/refresh Token! Error: ${error}`);
                });
        }
}

1 个答案:

答案 0 :(得分:1)

您可以将您的 auth.main()用作中间件,也可以简单地将您的代码运行为

    app.listen(port, () => {
      console.log(`Server is listening to port ${port}...(http\://localhost\:3000)`);
      auth.main();
    });

或只需将您需要运行的任何代码放在此处的引导程序中即可。

let express = require("express");
...

auth.main();

app.listen(444);