Serve custom . js file in Express route

Asked

Viewed 62 times

1

I have a specific "home" page for authenticated user that is served by a router however this authentication is made via cookie if there is this cookie "session" (created after user login and set their path to root) every request other than "home" is redirected to it (home).

But I need to serve a file javascript customized that will receive a tokem to be used by socket. and will also show (embed) basic user information and I cannot do it inline for reasons of a restrictive "CSP".

How could I reconcile this?

index js.

// get routes
var GetRoutes = require('./routes/GetRoutes');
app.use('/', GetRoutes);

/**
 * Store sockets auth [in memory]
 */
var memory_auth = {};

io.on('connection', function(socket){
    // pre-store
    memory_auth[socket.id] = false;
    //
    socket.on('disconnect', function(){
        // flush socket from "memory_auth"
        try{
            delete memory_auth[socket.id];
        }catch(ex){}
    });
    //
    socket.on('authenticate', function(payload){
        //
        try{
            jwt.verify(payload, process.env.TOKEN_LOGGED, function(error, data){
                if ( !error ) {
                    /**
                     * check "socket.auth" ever "socket requests in home page"
                     */
                    memory_auth[socket.id] = true;
                    // add socket to user id room [to connect all user connections]
                    socket.join(data.id);
                }
            });
        }catch(ex){
            console.log('Authentication token failed!');
        }
        //
        setTimeout(function(){
            if ( !memory_auth[socket.id] ) {
                socket.disconnect('unauthorized');
            }
        }, 1000);
    });
});

Getroutes.js

// middleware that is specific to this router
router.use((req, res, next)=> {
    var auth_cookie = req.signedCookies['_SCD_'];
    if ( auth_cookie && req.path !== '/home' ) {
        let user = users.getSession(auth_cookie); // function to getSession
        if ( user ) {
            res.redirect('/home');
            res.end();
        } else {
            next();
        }
    } else {
        next();
    }
});

router.get('/home', (req, res, next)=> {
    var auth_cookie = req.signedCookies['_SCD_'];
    if ( auth_cookie ) {
        let user = users.getSession(auth_cookie); // function to getSession
        if ( user ) {
            let file = getFile('home'); // function to get "home.html" file
            res.send(file);
        } else {
            res.redirect('/');
        }
    } else {
        res.redirect('/');
    }
});

router.get('/home/customJavaScript.js', (req, res, next) => {
    //
    var auth_cookie = req.signedCookies['_SCD_'];
    if ( auth_cookie ) {
        let user = users.getSession(auth_cookie); // function to getSession
        if ( user ) {
            // generate auth_token
            let auth_token = jwt.sign({
                data: {
                   id: user.id
                }
            }, process.env.TOKEN_LOGGED, { issuer: 'localhost:3000', noTimestamp: true, expiresIn: 5 });
            //
            var model = getFile('homeCustomJavaScript'); // function to get "custom.js" file
            model = model.replace(/{{+[a-zA-Z0-9_]+=+[a-zA-Z0-9=:.\/@#&-]+}}/gi, function(wholeMatch){
                if ( wholeMatch ) {
                    wholeMatch = wholeMatch.replace(/{{/g, '').replace(/}}/g, '');
                    var index = wholeMatch.split('=');
                    //
                    switch(index[0]){
                        case 'basic_nf':
                            let alias = (user.alias !== '') ? user.alias : 'Anonymous';
                            let user_nf = {
                                id: user.id,
                                alias: alias,
                                avatar: user.avatar,
                                mail: user.mail
                            };
                            return JSON.stringify(user_nf, null, 4);
                        break;
                        case 'auth_token':
                            return auth_token;
                        break;
                    }
                } else {
                    return '';
                }
            });
            res.type('application/javascript')
            .send(model)
            .end();
        } else {
            res.redirect('/');
        }
    } else {
        res.redirect('/');
    }
});

home html.

<body>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="./home/customJavaScript.js"></script>
</body>

customJavaScript.js

 'use strict';
 var socket = io();
/**
 * send authentication to socket connections [ever]
 * this auto add authenticated socket to user id room [to all user connections]
 */
socket.emit('authenticate', '{{auth_token=auth}}');     

var basic_user_nf = {{basic_nf=basic}};
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.