const Session = require("../models/Session"); const APIKey = require("../models/APIKey"); const Account = require("../models/Account"); module.exports = async function(req, res, next) { const authHeader = req.header("Authorization"); if (!authHeader) return res.status(401).json({message: "Missing Authorization header"}); // Check if authentication is a token if (authHeader.startsWith("Bearer ")) { req.token = authHeader.substring(7, authHeader.length); try { // Check if token is a session const {count: sessionCount, rows: sessionRows} = await Session.findAndCountAll({where: {token: req.token}}); if (sessionCount === 1) { req.sessionInfo = sessionRows[0].dataValues; req.clientId = sessionRows[0].client_id; req.tokenType = "client"; } // Check if token is a api key const {count: tokenCount, rows: tokenRows} = await APIKey.findAndCountAll({where: {token: req.token}}); if (tokenCount === 1) { req.keyInfo = tokenRows[0].dataValues; req.clientId = tokenRows[0].client_id; req.tokenType = "apikey"; } // Set data if the token is valid if (req.tokenType) { req.userInfo = await Account.findOne({where: {client_id: req.clientId}}); return next(); } res.status(401).json({message: "Invalid token"}); } catch (e) { res.status(500).json({message: "Unexpected error occurred"}); } } else res.status(401).json({message: "Authorization required"}); }