Can not create Video Session using OpenVidu and node

75 Views Asked by At

Below you'll find my node.js server using OpenVidu sdk for creating a simple app. Now here im trying to run this code in browser but it is giving me unauthorized error while its easily working in postman and generating video sessions. I have thoroughly checked jwt and everything else to see if there is any error but i couldn't find onee. here is my server code

/* CONFIGURATION */
var OpenVidu = require('openvidu-node-client').OpenVidu;
var OpenViduRole = require('openvidu-node-client').OpenViduRole;

// For demo purposes we ignore self-signed certificate
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

// Node imports
var express = require('express');
var fs = require('fs');
var session = require('express-session');
var https = require('https');
var bodyParser = require('body-parser'); // Pull information from HTML POST (express4)
var app = express(); // Create our app with express
var cors = require("cors");
const jwt = require("jsonwebtoken");

// Session configuration
app.use(
    session({
      saveUninitialized: true,
      resave: false,
      secret: 'MY_SECRET',
  // cookie: { secure: false },
})
);

// Environment variable: PORT where the node server is listening
var SERVER_PORT = process.env.SERVER_PORT || 5000;
// Environment variable: URL where our OpenVidu server is listening
var OPENVIDU_URL = process.env.OPENVIDU_URL || process.argv[2] || 'http://localhost:4443';
// Environment variable: secret shared with our OpenVidu server
var OPENVIDU_SECRET = process.env.OPENVIDU_SECRET || process.argv[3] || 'MY_SECRET';

// Allow requests from http://localhost:5173
const allowedOrigins = ['http://localhost:5173'];
// Enable CORS with credentials
app.use(
    cors({
  origin: function (origin, callback) {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true, // If you need to send cookies or authentication headers
})
);

// Entrypoint to OpenVidu Node Client SDK
var OV = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET);

const verifyToken = (req,res,next) => {
const authHeader = req.headers.token;
if(authHeader){
    const token = authHeader.split(" ")[1];
    jwt.verify(token, process.env.JWT_SEC || "abc123", (err, user)=>{
        if(err) res.status(403).json({err, message:"Your token is not valid"})
        req.user = user
    // Retrieve the access token from the session and store it in req.accessToken
        req.accessToken = req.session.accessToken; 
    // Assuming you saved the access token in req.session.accessToken during login
 
        next();
    })
}else{
    return res.status(401).json({message:"You are not authenticated"})
    }
};

const verifyTokenAndAuthorization = (req, res, next) => {
    console.log("Verifying token and authorization...");
    verifyToken(req, res, () => {
        if (users.some(u => u.user === req.session.loggedUser)) {
            // User is verified
            console.log("User is verified");
            next();
        } else {
            console.log("User is not allowed");
            res.status(403).json("You are not allowed to do that");
        }
});
};

// Collection to pair session names with OpenVidu Session objects
var mapSessions = {};
// Collection to pair session names with tokens
var mapSessionNamesTokens = {};

// Listen (start app with node server.js)
var options = {
    key: fs.readFileSync('openvidukey.pem'),
    cert: fs.readFileSync('openviducert.pem')
};

// Mock database
var users = [{
    user: "publisher1",
    pass: "pass",
    role: OpenViduRole.PUBLISHER
}, {
    user: "publisher2",
    pass: "pass",
    role: OpenViduRole.PUBLISHER
}, {
    user: "subscriber",
    pass: "pass",
    role: OpenViduRole.SUBSCRIBER
}];



// app.use(express.static(__dirname + '/public')); // Set the static files location
app.use(bodyParser.urlencoded({
    'extended': 'true'
})); // Parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // Parse application/json
app.use(bodyParser.json({
    type: 'application/vnd.api+json'
})); // Parse application/vnd.api+json as json

https.createServer(options, app).listen(SERVER_PORT, () => {
    console.log(`App listening on port ${SERVER_PORT}`);
    console.log(`OPENVIDU_URL: ${OPENVIDU_URL}`);
    console.log(`OPENVIDU_SECRET: ${OPENVIDU_SECRET}`);
});

/* CONFIGURATION */

/* REST API */

// Login
app.post('/api-login/login', function (req, res) {

// Retrieve params from POST body
var user = req.body.user;
var pass = req.body.pass;
console.log("Logging in | {user, pass}={" + user + ", " + pass + "}");

if (login(user, pass)) { // Correct user-pass
    // Validate session and return OK
    // Value stored in req.session allows us to identify the user in future requests
    console.log("'" + user + "' has logged in");
    //generate token when the user logs in which expires in 3 days
const accessToken = jwt.sign(
    { user: users.user },
    process.env.JWT_SEC || "abc123",
    { expiresIn: "3d" }
  );
    req.session.accessToken = accessToken;
    req.session.loggedUser = user;
    res.status(200).send({user, accessToken});

} else { // Wrong user-pass
    // Invalidate session and return error
    console.log("'" + user + "' invalid credentials");
    req.session.destroy();
    res.status(401).send('User/Pass incorrect');
    }
});

// app.get('/getSession', (req, res) => {
//     const username = req.session.username || 'Guest';
//     res.send(`Hello, ${username}!`);
//   });

// Logout
app.post('/api-login/logout', function (req, res) {
    console.log("'" + req.session.loggedUser + "' has logged out");
    req.session.destroy();
    res.status(200).send();
});

// Get token (add new user to session)
app.post('/api-sessions/get-token', verifyTokenAndAuthorization, function (req, res) {
    // Access the access token from req.accessToken
    const accessToken = req.accessToken;
    console.log("Inside /api-sessions/get-token route handler");
    if (!isLogged(req.session)) {
        // User not logged in
        req.session.destroy();
        return res.status(401).send('User not logged');
    } else {
        // The video-call to connect
        var sessionName = req.body.sessionName;

        // Role associated with this user
    var role = users.find(u => u.user === req.session.loggedUser).role;

    // Optional data to be passed to other users when this user connects to the video-call
    // In this case, a JSON with the value we stored in the req.session object on login
    var serverData = JSON.stringify({ serverData: req.session.loggedUser });
    console.log("Access Token: "+ accessToken);
    console.log("Getting a token | {sessionName}={" + sessionName + "}");

    // Build connectionProperties object with the serverData and the role
    var connectionProperties = {
        data: serverData,
        role: role
    };

    if (mapSessions[sessionName]) {
        // Session already exists
        console.log('Existing session ' + sessionName);

        // Get the existing Session from the collection
        var mySession = mapSessions[sessionName];

        // Generate a new token asynchronously with the recently created connectionProperties
        mySession.createConnection(connectionProperties)
            .then(connection => {
                // Store the new token in the collection of tokens
                mapSessionNamesTokens[sessionName].push(connection.token);

                // Return the token to the client
                res.status(200).send({ 0: connection.token });
            })
            .catch(error => {
                console.error(error);
                res.status(500).send('Internal Server Error');
            });
    } else {
        // New session
        console.log('New session ' + sessionName);

        // Create a new OpenVidu Session asynchronously
        OV.createSession()
            .then(session => {
                // Store the new Session in the collection of Sessions
                mapSessions[sessionName] = session;
                // Store a new empty array in the collection of tokens
                mapSessionNamesTokens[sessionName] = [];

                // Generate a new connection asynchronously with the recently created connectionProperties
                session.createConnection(connectionProperties)
                    .then(connection => {
                        // Store the new token in the collection of tokens
                        mapSessionNamesTokens[sessionName].push(connection.token);

                        // Return the Token to the client
                        res.status(200).send({ 0: connection.token });
                    })
                    .catch(error => {
                        console.error(error);
                        res.status(500).send('Internal Server Error');
                    });
            })
            .catch(error => {
                console.error(error);
                res.status(500).send('Internal Server Error');
            });
    }
}
});





// Remove user from session
app.post('/api-sessions/remove-user', function (req, res) {
    if (!isLogged(req.session)) {
        req.session.destroy();
        res.status(401).send('User not logged');
} else {
    // Retrieve params from POST body
    var sessionName = req.body.sessionName;
    var token = req.body.token;
    console.log('Removing user | {sessionName, token}={' + sessionName + ', ' + token + '}');

    // If the session exists
    if (mapSessions[sessionName] && mapSessionNamesTokens[sessionName]) {
        var tokens = mapSessionNamesTokens[sessionName];
        var index = tokens.indexOf(token);

        // If the token exists
        if (index !== -1) {
            // Token removed
            tokens.splice(index, 1);
            console.log(sessionName + ': ' + tokens.toString());
        } else {
            var msg = 'Problems in the app server: the TOKEN wasn\'t valid';
            console.log(msg);
            res.status(500).send(msg);
        }
        if (tokens.length == 0) {
            // Last user left: session must be removed
            console.log(sessionName + ' empty!');
            delete mapSessions[sessionName];
        }
        res.status(200).send();
    } else {
        var msg = 'Problems in the app server: the SESSION does not exist';
        console.log(msg);
        res.status(500).send(msg);
    }
}
});




// Function to change roles
// function changeRoles() {

//   for (let i = 0; i < users.length; i++) {
//     if (users[i].role === OpenViduRole.PUBLISHER) {
//       users[i].role = OpenViduRole.SUBSCRIBER;
//     } else if (users[i].role === OpenViduRole.SUBSCRIBER) {
//       users[i].role = OpenViduRole.PUBLISHER; 
//     }
//   }

//   console.log("Roles changed:", users);

 // Schedule the next role change after 5 minutes (300,000 milliseconds)
//   setTimeout(changeRoles, 300000);
// }

// changeRoles();





/* REST API */



/* AUXILIARY METHODS */

function login(user, pass) {
    return (users.find(u => (u.user === user) && (u.pass === pass)));
}

function isLogged(session) {
    return (session.loggedUser != null);
}

function getBasicAuth() {
    return 'Basic ' + (Buffer.from('publisher1' + 'pass').toString('base64'));
}

/* AUXILIARY METHODS */
0

There are 0 best solutions below