Exemple #1
0
    def get():
        """ 获取邮箱数据 """

        resp = Response(payload={})

        log.info('邮箱接口请求参数: [payload: %s]' % (resp['payload']))

        return resp
Exemple #2
0
def getJobLibrary():
    """ Return simplified library overview in json format """
    log.debug(f"<{request.remote_addr}> getting job library")
    try:
        library = Library.objects().get()
    except DoesNotExist:
        log.info(f"<{request.remote_addr}> returning empty library")
        return "", 204
    log.info(f"<{request.remote_addr}> returning library overview")
    return {"library": library.to_json()}, 200
Exemple #3
0
    def get():
        """ 获取红包数据 """

        resp = Response(
            payload={
                "hb_id": get_arg_or_400("hb_id"),
                "node_id": get_arg_or_400("node_id"),
                "click_time": get_arg_float_or_none("click_time"),
            })

        log.info('红包接口请求参数: [payload: %s]' % (resp['payload']))

        return resp
Exemple #4
0
def getRegistrationKey():
    """ Get or generate the registration key that agents need to register with commander """
    log.debug(f"<{request.remote_addr}> getting registration key")
    # return current key if one exists
    regKeyQuery = RegistrationKey.objects()
    if regKeyQuery:
        return {"registration-key": regKeyQuery[0]["regKey"]}
    # create registration key in db
    newKey = str(uuid4())
    regKey = RegistrationKey(regKey=newKey)
    regKey.save()
    # return new key
    log.info(f"<{request.remote_addr}> successfully fetched registration key")
    return {"registration-key": newKey}
Exemple #5
0
def updateRegistrationKey():
    """ Generate and return a new registration key that agents need to register with commander """
    log.debug(f"<{request.remote_addr}> updating registration key")
    # make sure a current key exists
    regKeyQuery = RegistrationKey.objects()
    if not regKeyQuery:
        regKey = RegistrationKey(regKey="placeholder")
    else:
        regKey = regKeyQuery[0]
    # update the registration key and save to db
    newKey = str(uuid4())
    regKey["regKey"] = newKey
    regKey.save()
    # return new key
    log.info(
        f"<{request.remote_addr}> successfully regenerated the registration key"
    )
    return {"registration-key": newKey}
Exemple #6
0
def on_admin_push(request):
    #TODO:要求用户验证
    #前端传过来的是序列化后的json字符串, 需要loads一下
    watcher=None
    try:
        if request.session['account']!=settings.SUPER_USER:
            try:
                Watcher.objects.get(account=request.session['account'],iswatching=True)
            except:
                raise Exception(unicode("非法用户尝试修改值班干事"))
        push_json_str=request.POST['data']
        push_json=json.loads(push_json_str)
        for item in push_json['watch_list']:
            #检查输入
            log.debug('on_admin_push','for item start checking')
            keys = ['account','watchsum','name','spnumber','iswatching','lpnumber','type']
            for key in keys:
                if key not in item:
                    raise Exception('incomplete data')
                if check.is_clean_input(key,item[key]) == False:
                    print key, item[key]
                    raise Exception('unsafe data')
            log.debug('on_admin_push','for item end checking')
            #先删除
            log.debug('on_admin_push','delete items')
            if item.get('type')=='delete':
                is_logined = (item['account']==request.session['account'])
                log.debug('on_admin_push','%s deleted'%item['account'])
                Watcher.objects.all().filter(account=item['account']).delete()
                if is_logined: 
                    del request.session['account']
            else:
                if item.get('type')=='new':
                    default_password=hashlib.md5(item['account']).hexdigest()
                    default_password=hashlib.sha1(default_password).hexdigest()
                    log.debug('on_admin_push','trying to create new watcher %s'%item['account'])
                    watcher=Watcher(
                        account=B(item['account']),
                        name=B(item['name']),
                        lpnumber=B(item['lpnumber']),
                        spnumber=B(item['spnumber']),
                        password=B(default_password),
                        watchsum=0,
                        iswatching=False)
                    log.debug('on_admin_push','succeed to create new watcher')
                else:
                    log.debug('on_admin_push','trying to get item %s'%item['account'])
                    watcher=Watcher.objects.get(account=item['account'])
                    log.debug('on_admin_push','succeed to get item')
                if('yes'==item['iswatching']):
                    watcher.iswatching=True
                elif('no'==item['iswatching']):
                    watcher.iswatching=False
                    if watcher.account == request.session['account'] and watcher.account!=settings.SUPER_USER:
                        del request.session['account']
                log.info('on_admin_push','after setting watching state')
                watcher.save()
                log.info('on_admin_push','after save')
        return HttpResponse(json.dumps({'flag_succeed':'true',}))

    except Exception as e:
        log.error('exception in on_admin_push:',unicode(e))
        error=Error(what=B(unicode(e)))
        error.save()
        return HttpResponse(json.dumps({'flag_succeed':'false',}))
Exemple #7
0
def testAuthentication():
    """ Authenticate using session token to test and see if it is still valid """
    log.info(
        f"<{request.remote_addr}> successfully test authenticated '{get_jwt_identity()}' with a valid JWT"
    )
    return {"success": "authentication token is valid"}, 200
Exemple #8
0
    response = requests.get(
        "https://github.com/lawndoc/commander/releases/latest/download/version.txt",
        allow_redirects=True)
    if response.status_code != 200:
        log.error("failed to fetch agent version information from GitHub")
        raise CommanderError(
            "failed to fetch agent version information from GitHub")
    version = response.content.decode("utf-8").strip()
    # check if we have the newest installers
    if not path.exists(f"agent/installers/{version}/{filename}"):
        try:
            getLatestAgentInstallers(version)
        except CommanderError as e:
            log.error(e)
            raise e
    log.info(f"<{request.remote_addr}> sending agent installer for {targetOS}")
    return send_from_directory(f"agent/installers/{version}/{filename}",
                               filename=filename), 200


def getLatestAgentInstallers(version):
    """ Gets the latest agent installers from GitHub """
    log.debug(
        f"fetching latest agent installers for commander agent {version}")
    # get client cert from CAPy if we don't already have it
    if not path.exists("agent/certs/client.crt") or not path.exists(
            "agent/certs/client.key") or not path.exists(
                "agent/certs/root.crt"):
        response = requests.get("http://" + app.config["CA_HOSTNAME"] +
                                "/ca/host-certificate",
                                headers={"Content-Type": "application/json"},