response.headers.add('X-Script-Version', 'secret-24.10.20')

'use api/lib/protect.js'

function main() {
    const chiper = payload.get().path.split('/').pop()
    if (!chiper) {
        return errMsg(507, "参数错误");
    }

    let token
    if (chiper == 'undefined') {
        token = payload.get().headers["Authorization"] || payload.get().query["token"] || payload.get().headers["X-Token"] || (payload.get().cookie ? payload.get().cookie["token"] : null);
    } else {
        token = decryptData(chiper)
    }

    let tokenInfo = jwt_parse(token)
    // 判断token颁发时间,如果大于10秒则secret失效
    // tokenInfo.nbf 单位秒 -> 时间戳 -> token的启用时间
    // 在此时间之前token不能使用
    // 在此之后secret可能被盗用
    if (!tokenInfo || tokenInfo.nbf > Date.now() / 1000 + 10) {
        return errMsg(507, "secret失效");
    }

    if (payload.get().method === 'POST') {
        let data = payload.get().body?.toObject()
        if (data.name && data.idno) {
            SQL.push('system_sql', `UPDATE sys_users SET real_name = ?,idno = ? WHERE user_id = ?`, tokenInfo.uid, data.name, data.idno)
        }
    }

    response.cookies.setRaw(`token=${token}; Path=/; Max-Age=604800; SameSite=Strict; CrossSite=Strict; Priority=High; PartitionKeySite=Main; HttpOnly; Secure`)
    return okMsg(tokenInfo)
}