Я хочу выполнить функцию при запуске моего экспресс-сервера node.js и выполнить модуль auth, это правильный путь? - PullRequest
0 голосов
/ 06 марта 2019

В настоящее время я собираю свой сервер для выполнения функции аутентификации при запуске с использованием прослушивателя сервера / приложения. Я пытаюсь использовать внешнюю функцию в моем файле контроллера, чтобы сделать это, мой код сервера ниже:

//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()
});

И я использую эти асинхронные модули в моей аутентификации, это правильный способ выполнения функции запуска? Для данных, которые я хочу отправить обратно, я должен сохранить их в глобальных переменных и затем использовать '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 Ответ

1 голос
/ 25 апреля 2019

Вы можете использовать свою 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...