var request = require('request');
var x509 = require('@peculiar/x509');
var jwt = require('jsonwebtoken');
var { Config } = require('../lib/Config');
function JmuSSO(config) {
    this.config = config;
    this.publicKey = '';
}

JmuSSO.prototype.getPublicKey = function (code, redirectUri) {
    var url = 'https://token.paas.jmu.edu.cn/jwt/publicKey';
    var self = this;
    let option = {
        url: url,
        method: 'GET',
        headers: {
            "content-type": "application/json"
        },
    }
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            if (error) {
                reject(error)
            } else {
                self.publicKey = body;
                resolve(body)
            }
        })
    })
}

JmuSSO.prototype.GetUserInfo = function (userToken) {
    var self = this;
    return new Promise((resolve, reject) => {
        this.getPublicKey().then((key) => {
            if (key) {
                self.publicKey = key;
                const publicKey = Buffer.from(key);
                const user = jwt.verify(userToken, publicKey, { algorithms: ["RS512"] })
                user ? resolve(user) : reject(false);
            }
        }).catch(() => {
            if (self.publicKey) {
                const publicKey = Buffer.from(self.publicKey);
                const user = jwt.verify(userToken, publicKey, { algorithms: ["RS512"] })
                user ? resolve(user) : reject(false);
            } else {
                reject(false);
            }
        })
    })
}

module.exports = JmuSSO

