const jwt = require('jsonwebtoken');

module.exports = {


    friendlyName: 'JWT Verify',


    description: '',


    inputs: {
        token: {
            type: 'string',
            required:true
        },
        callback: {
            type: 'ref'
        }
    },


    exits: {
        success: {
            description: 'Success'
        },
        forbidden:{
            description: 'Error authenticating'
        },
        sessionTimeOutError:{
            description:"Session timed out, please login again"
        },
        authenticationError:{
            description:"sessionTimeOutError"
        },
        verificationError:{
            description:"Erreur de vérification"
        }
    },


    fn: async function (inputs, exits) {

        await jwt.verify(inputs.token,sails.config.custom.secret, async function (err, decoded) {
            if (err) {
                sails.log("verification error", err);
                throw ' verificationError';
                if (err.name === "TokenExpiredError")
                    throw 'sessionTimeOutError';
                else
                   throw 'authenticationError';
            }

            return exits.success(decoded);

        })

    }
};

