const { expressjwt: expressJwt } = require('express-jwt');
const db = require('helpers/db');
const config = require('../config.json');
require('dotenv').config();

module.exports = authorize;

function authorize() {
    // const secret = process.env.SECRET_SAPPS;
    const { secret } = config.databaseConfigSAPPS;

    return [
        // authenticate JWT token and attach decoded token to request as req.auth (express new)
        expressJwt({ secret, algorithms: ['HS256'] }),

        // attach full user record to request object
        async (req, res, next) => {
            console.log("Req: ", req);

            // get user with id from token 'sub' (subject) property
            const user = await db.User.findByPk(req.auth.sub);

            // check user still exists
            if (!user) return res.status(401).json({ message: 'Unauthorized!' });

            // authorization successful
            req.user = user.get();
            next();
        }
    ];
}
