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

问题描述 投票:0回答:1

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

//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}`);
                });
        }
}
node.js express routing node-modules
1个回答
1
投票

你可以使用你的auth.main()作为中间件,或者只是运行你的代码

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

或者只需放置在bootstrap运行所需的任何代码。

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

auth.main();

app.listen(444);
© www.soinside.com 2019 - 2024. All rights reserved.