{"size": 1733, "ext": "js", "max_stars_repo_path": "utils/jwtUtils.js", "max_stars_repo_name": "chamoddissanayake/Procura_REST_API", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/jwtUtils.js", "max_issues_repo_name": "chamoddissanayake/Procura_REST_API", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/jwtUtils.js", "max_forks_repo_name": "chamoddissanayake/Procura_REST_API", "max_forks_repo_forks_event_min_datetime": "2020-09-27T04:47:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T04:47:01.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1, "avg_line_length": 35.3673469388, "max_line_length": 112, "alphanum_fraction": 0.5781881131}
const jwt = require("jsonwebtoken")
/**
 * Checks whether given String property is non-empty
 * @param {String} value 
 */
module.exports.isStringPropertyNotEmpty = function isStringPropertyNotEmpty(value) {
    return !(value === null || value === undefined || value === "")
}

/**
 * @author Nisuga Jayawardana it18117110
 * 
 * JWT  Middleware Authorization Mechanism for Client Type Specific Routes
 * 
 * @param {String}  ADMIN_or_STORE_MANAGER_or_USER 

 */
module.exports.authenicateToken = function authenicateToken(userType) {

    return authenicateToken[userType] || (authenicateToken[userType] = function (req, res, next) {
        const authHeader = req.headers['authorization']
        const token = authHeader && authHeader.split(' ')[1]
        if (token == null) {
            return res.status(401).json({ success: false, error: 'You are not authorized to perform this' })
        }
        jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, userData) => {
            if (err) {
                res.status(403).json({
                    success: false,
                    error: `Unauthorized Token`
                })
            }
            // console.log(userData);
            //If permitted userType matches the current userType
            if (userData.userType === userType && userData.userType !== undefined) {
                req.user = userData.user
                //Passing access to the next DB functions
                next()
            } else {
                res.status(403).json({
                    success: false,
                    error: `Unauthorized Access. ${userData.userType.toLowerCase()}s cannot perform this action`
                })
            }
        })
    })
}

