Ejemplo n.º 1
0
def utils_domain():
    """
    utils_domain
    ---
    tags:
     - utils
    parameters:
      - name: ip
        in: formData
        required: true
      - name: domain
        in: formData
        required: true
    responses:
     200:
       description: ok
    """

    ip = request.form.get("ip", None)
    domain = request.form.get("domain", None)
    if ip is None or domain is None:
        raise Exception("ip or domain is invalid")
    if Setting.get("CloudflareZone") not in domain:
        raise Exception("domain is not allow")
    obj = CloudFlare(Setting.get("CloudflareAuthEmail"),
                     Setting.get("CloudflareAuthKey"))
    obj.get_zone_id(domain)
    body = obj.update_domain_ip(ip, domain)
    return jsonify(body)
Ejemplo n.º 2
0
def task_handler():
    """
    task handler
    ---
    tags:
     - task
    security:
      - apiKeyAuth : []
    responses:
     200:
       description: ok
    """
    payload = flask.request.get_data(as_text=True) or '(empty payload)'
    logging.info('Received task with payload: {}'.format(payload))
    payload = json.loads(str(payload))

    task_id = payload['task_id']
    auth = payload['auth']
    if Setting.get("TASK_AUTH", default="TASK_AUTH_KEY", update=True) != auth:
        logging.error("TASK_AUTH is invalid")
        raise Exception("auth is invalid", 500)
    status, result = Model.exec(payload['action'], payload['params'])
    logging.info("exe result: %s %s", status, result)
    res = requests.post("https://{}.appspot.com/api/task/result/{}".format(Setting.get("COMPUTE_PROJECT_ID"), task_id), data=dict(
        status=status,
        result=result,
        executor=os.getenv("EXECUTOR", "docker")
    ))
    logging.info("upload response code: %d", res.status_code)
    return status
Ejemplo n.º 3
0
    def std_handler(self, error):
        if isinstance(error, HTTPException):
            msg = error.name
            code = error.code
            body = ""
        else:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            msg = str(exc_value.args[0]) if len(
                exc_value.args) > 0 else "system error"
            code = exc_value.args[1] if len(exc_value.args) > 1 else 500

            if current_app and not current_app.debug:
                log = "msg: {},type:{},trace: {}".format(
                    exc_value, exc_type, traceback.format_tb(exc_traceback))
                logging.error(log)
                body = []
                if len(exc_value.args) <= 1 or code == 505:
                    try:
                        mail_send(
                            Setting.get("ADMIN_EMAIL"),
                            "[Alarm]{}".format(str(error)),
                            "<b>{}</b>  {}<br />{}".format(
                                exc_value, exc_type, "<br />".join(
                                    traceback.format_tb(exc_traceback))))
                    except Exception as e:
                        logging.error("send email error: %s, %s", e,
                                      traceback.format_exc())
            else:
                body = [str(exc_type), traceback.format_tb(exc_traceback)]

        response = jsonify(msg=msg, code=code, body=body)
        response.status_code = 200
        return response
Ejemplo n.º 4
0
def get_constant():
    """
    get constant
    ---
    tags:
     - front/setting
    responses:
     200:
       description: ok
    """
    constant = Setting.rows("constant")
    constant['port'] = os.getenv("PORT")
    constant['executor'] = os.getenv("EXECUTOR")
    constant['version'] = os.getenv("VERSION")
    constant['debug'] = current_app.config['DEBUG']

    return jsonify(constant)
Ejemplo n.º 5
0
 def exec(cls, action, params):
     res = ""
     status = STATUS['ok']
     try:
         if action == 'email':
             mail_send(**params)
             res = "ok"
         if action == 'shell':
             from app.helpers.setting import Setting
             cmd = params.format(**Setting.rows())
             if "build.sh" in str(params):
                 res = file_write("/opt/worker/build.sh", cmd)
             elif "deploy.sh" in str(params):
                 res = file_write("/opt/worker/deploy.sh", cmd)
             else:
                 res = shell_exec_result(cmd)
         if action == 'instance.delete':
             res = json.dumps(
                 get_compute().instances().delete(**params).execute())
         if action == 'instance.create':
             res = json.dumps(
                 get_compute("beta").instances().insert(**params).execute())
         if action == 'instance.stop':
             res = json.dumps(
                 get_compute().instances().stop(**params).execute())
         if action == 'instance.start':
             res = json.dumps(
                 get_compute().instances().start(**params).execute())
         if action == 'instance.reset':
             res = json.dumps(
                 get_compute().instances().reset(**params).execute())
         if action == 'instance.create_machine_image':
             res = json.dumps(
                 get_compute("beta").machineImages().insert(
                     **params).execute())
     except Exception as e:
         res = str(e)
         status = STATUS['error']
     return status, res
Ejemplo n.º 6
0
def check():
    logging.info("checking...")
    if not Setting.get("INITED", default=False):
        if os.path.exists("/opt/worker/setting.json"):
            logging.info("init setting.json")
            Var.set("setting.json",
                    utils.file_read("/opt/worker/setting.json"))
            Setting.set("INITED", True)

    url = "https://{}.appspot.com/api/compute/instance/worker/{}".format(
        Setting.get("COMPUTE_PROJECT_ID"),
        os.getenv("EXECUTOR", "docker").split("__")[0])
    logging.info("upload worker status... %s", url)

    res = requests.post(url,
                        data=dict(ip=os.getenv("IP"), port=os.getenv("PORT")),
                        auth=(Setting.get("BASIC_AUTH_USERNAME"),
                              Setting.get("BASIC_AUTH_PASSWORD")))
    logging.info("res: %s", res)
    return "ok"
Ejemplo n.º 7
0
def spec():
    if Setting.get("DISABLE_SWAGGER", default="false", update=True) == "true":
        raise Exception("DISABLED", 403)
    swag = get_spec(swagger(app))
    return jsonify(swag)
Ejemplo n.º 8
0
def swagger():
    if Setting.get("DISABLE_SWAGGER", default="false", update=True) == "true":
        raise Exception("DISABLED", 403)
    swagger_api_url = utils.get_base_url() + "/api/spec"
    return render_template('swagger.html', swagger_api_url=swagger_api_url)
Ejemplo n.º 9
0
def email_captcha_verify():
    """
    email captcha verify
    ---
    tags:
     - auth
    parameters:
      - name: email
        in: formData
        required: true
      - name: code
        in: formData
        required: true
    responses:
     200:
       description: ok
    """

    data = request.get_json()
    # print(data)
    if data is None:
        email = request.form.get("email", None)
        code = request.form.get("code", None)
    else:
        email = data.get("email", None)
        code = data.get("code", None)

    if not check_email(email):
        raise Exception("不合法的Email", 500)
    captcha = EmailCaptcha.get_by_email(email)
    if captcha is None:
        raise Exception("请重新发送验证码", 500)

    logging.debug(captcha)
    logging.debug("created_at: %s, expired_at: %s,now: %s", captcha.created_at,
                  captcha.created_at + timedelta(minutes=10), datetime.utcnow())

    if captcha is not None and captcha.code == code and captcha.created_at + timedelta(hours=1) > datetime.utcnow():
        user = User.get_by_email(email)
        msg = "登录成功"
        if user is None:
            msg = "登录成功,密码已发送到您的邮箱,请查收!"
            user = User(email=email, name=email.split("@")[0])

            if email in Setting.get("SUPER_EMAILS", default="SUPER_EMAILS1|SUPER_EMAIL2", update=True).split("|"):
                user.level = 0
            else:
                user.level = 1
            password = generate_random(6)
            template = Var.get("template-email-reg-ok.html", is_json=False)
            if template and "####################" in template:
                title = template.split("####################")[0].strip()
                content = template.split("####################")[1].strip()
                mail_send(
                    email,
                    title,
                    content.format(
                        email=email, password=password,
                        name=email.split("@")[0], balance_silver=user.balance_silver
                    )
                )
            user.password = md5(password)
            user.created_at = datetime.utcnow()
            user.updated_at = user.created_at
            user.save()

        access_token = get_access_token(user)
        captcha.remove()

        return jsonify({"code": 200, "msg": msg, "body": {
            "user": {
                "level": user.level,
            },
            "access_token": "JWT " + access_token}})
    else:
        if captcha is not None and captcha.created_at + timedelta(hours=1) < datetime.utcnow():
            EmailCaptcha.delete(captcha)
            raise Exception("验证码已过期", 500)
        else:
            raise Exception("验证码不正确", 500)