var request = require('request');
var jwt = require('jsonwebtoken');
function HnustSSO(config) {
    this.config = config;
    this.publicKey = '';
}

HnustSSO.prototype.getPublicKey = function (code, redirectUri) {
    // var url = 'https://cas-i.hnust.edu.cn/cas/jwt/publicKey';   // 湖南科技
    var url = 'https://cas.cqmu.edu.cn/cas/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)
            }
        })
    })
}

HnustSSO.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 = HnustSSO

