//访问控制规则：
//针对如果是DOIP请求的调用
//仅包括Repo.doipRetrive
//Registry的publish/subscribe不做访问控制
//如果是HTTP请求的调用
//管理员具有所有权限
//一些”写入接口“添加权限检查
module DOAuth {
    function initDOAuth(req, createParam, doipFunctions) {
        Global.owner = req;
        Global.doipFunctions = doipFunctions;
        Global.accessInfo = RocksDBUtil.loadDB("accessControl", "false");
    }
    function isOwner(req) {
        return req == Global.owner;
    }
    function doipAccessCheck(argPack) {
        print("in doipAcceccCheck, requester:" + argPack.requester);
        var stored = Global.accessInfo.get(argPack.arg.header.identifier);
        return stored == argPack.requester;
    }
    function checkByManager(action) {
        return Global.doipFunctions.indexOf(action) == - 1;
    }

    @Description("针对某一DO，添加用户的访问权限")
    @ArgSchema({
        "doId" : "string", "publicKey" : "string"
    })
    export function addAuthedUser(arg) {
    //把requester和 arg.doId放到accessInfo里即可。
        Global.accessInfo.put(arg.doId, arg.publicKey);
        return {
            "code" : 0
        };
    }

    function acceptJudgementInternal(argPack) {
        if (checkByManager(argPack.action)){
            return isOwner(argPack.requester);
        } else {
            return doipAccessCheck(argPack);
        }
    }
    function acceptJudgement(argPack) {
        if (! acceptJudgementInternal(argPack)){
            print("acceptJudgement, requester:" + argPack.requester + "false!!");
            YancloudUtil.exceptionReturn({
                "code" : 401, "msg" : "no permission: " + argPack.action
            });
        } else print("acceptJudgement, requester:" + argPack.requester + "true!!");
    }

    @Description("针对某一DO，删除用户的访问权限")
    @ArgSchema({
        "doId" : "string", "publicKey" : "string"
    })
    export function deleteAuthedUser(arg) {
        return {
            "code" : 0
        };
    }

    @Description("针对某一DO，添加节点的访问权限，所有调用进带该节点授权的用户均可访问")
    @ArgSchema({
        "doId" : "string", "publicKey" : "string"
    })
    export function addAuthedNode(arg) {
        return {
            "code" : 0
        };
    }


    @Description("针对某一DO，删除节点的访问权限")
    @ArgSchema({
        "doId" : "string", "publicKey" : "string"
    })
    export function deleteAuthedNode(arg) {
        return {
            "code" : 0
        };
    }
}