def update_solution():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    ctx.current_user = DccaUser.get_by_id(uid)

    check_json(request)
    solution_id = get_json(request).get('id')
    url = get_json(request).get('url')
    is_default = bool_helper(get_json(request).get('is_default'))

    is_owner = DccaAssSolutionImage.is_solution_owner(solution_id)
    if not is_owner:
        return jsonify({
            'status':
            'fail',
            'message':
            'Solution not exist or you are not permit to access'
        })

    image = url.split('/')[-1]
    if not image:
        return jsonify({'status': 'fail', 'message': 'Bad URL format'})

    solution = DccaAssSolutionImage.query_by_id(solution_id)
    solution.image = image
    solution.link = url
    if is_default:
        if not DccaModel.check_model_owner(solution.model_id):
            return jsonify({
                'status':
                "fail",
                'message':
                "Not the model owner, can't set default solution"
            })

        if solution.is_public != DccaModel.check_model_permission(
                solution.model_id):
            return jsonify({
                'status':
                "fail",
                'message':
                "Solution and model have different permission, can't set default solution"
            })
        solution.model.default_solution_id = solution_id
    else:
        solution.model.default_solution_id = None

    try:
        session.commit()
    except Exception as e:
        err_msg = "Fail to update solution. {}".format(str(e))
        raise DCCAException(err_msg)

    return jsonify({
        'id': solution_id,
        'status': 'success',
        'message': 'Update the solution successfully'
    })
def reset_password():
    check_json(request)
    token = get_json(request).get('token')
    password = get_json(request).get('password')

    crypter = DCCACrypt(MAIL_TOKEN_KEY)
    decrypt_token = crypter.decrypt(token)
    user_id, time_str = decrypt_token.split(' ')

    delta = datetime.now() - datetime.strptime(time_str, TIME_FORMAT_STR)
    if delta.seconds / 60 > DEFAULT_MAIL_TOKEN_TIMEOUT:
        return jsonify({'status': 'fail', 'message': 'The token timeout '})
    else:
        password_hash, password_salt = encrypt_with_random_salt(password)
        try:
            request.cursor.execute(update_password_confirm_email_sql,
                                   (password_hash, password_salt, user_id))
            request.conn.commit()
        except Exception:
            raise DCCAException('Fail to reset password')

        return jsonify({
            'status': 'success',
            'message': 'Success to reset password'
        })
Exemple #3
0
def modify_common_service(service_id):
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    name = get_json(request).get('name')
    url = get_json(request).get('url')
    port = get_json(request).get('port')
    access_token = get_json(request).get('access_token')

    if not is_service_owner(request.cursor, user_id=uid,
                            service_id=service_id):
        return jsonify({
            'status':
            'fail',
            'message':
            'Not the service owner or the service cannot access.'
        })

    try:
        update_service(request.cursor, name, url, port, access_token,
                       service_id)
        request.conn.commit()
    except Exception as e:
        raise DCCAException(
            make_error_msg(IS_DEBUG,
                           'Exception, fail to update common service.',
                           str(e)))

    return jsonify({
        'status': 'success',
        'message': 'Success to update the commont service'
    })
Exemple #4
0
def create_common_service():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    name = get_json(request).get('name')
    url = get_json(request).get('url')
    port = get_json(request).get('port')
    access_token = get_json(request).get('access_token')

    try:
        service_id = create_service(request.cursor,
                                    name,
                                    url,
                                    port,
                                    access_token,
                                    user_id=uid)
        request.conn.commit()
    except Exception as e:
        raise DCCAException(
            make_error_msg(IS_DEBUG,
                           'Exception, fail to create common service', str(e)))

    return jsonify({
        'status': 'success',
        'message': 'Success to create service ID',
        'id': service_id
    })
def create_device_group():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    ctx.current_user = DccaUser.get_by_id(uid)

    check_json(request)
    name = get_json(request).get('name')
    desc = get_json(request).get('description')
    customer = get_json(request).get('customer')

    if desc is None:
        desc = ''

    empty_check(name, error_message='Name cannot be empty')

    DccaDeviceGroup.is_name_taken(name, ctx.current_user)

    group = DccaDeviceGroup(name, description=desc, customer=customer)
    try:
        session.add(group)
        session.commit()
    except Exception:
        raise DCCAException('Fail to create device group')

    results = OrderedDict()
    results['status'] = 'success'
    results['message'] = 'Success to create a group'
    results['group'] = group.as_dict(schema=DeviceGroupSchema)

    return jsonify(results)
def create_resource():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    name = get_json(request).get('name')
    resource_type = get_json(request).get('resource_type')
    action = get_json(request).get('action')
    url_pattern = get_json(request).get('path')

    contain_whitespace(name)
    duplicate_name(name)
    contain_whitespace(resource_type)
    action_validate(action)
    contain_whitespace(url_pattern)

    try:
        resource = DccaResource(name, action, url_pattern)
        session.add(resource)
        session.flush()

        perm = DccaPermission(name, resource_type, resource)
        session.add(perm)
        session.commit()
    except Exception:
        raise DCCAException('Fail to create resource')

    return jsonify({
        'status': 'success',
        'message': 'Success tgrant_user_one_roleo create resource',
        'resource': perm.as_dict(schema=FullResourceSchema)
    })
def delete_tag():
    check_json(request)
    solution_id = get_json(request).get('solution_id')
    tag_name = get_json(request).get('tag_name')

    if not tag_name:
        return jsonify({
            'status': 'fail',
            'message': 'Tag name cannot be empty'
        })

    # Check if tag exist, if not exist, do nothing
    tag_id = query_tag(request.cursor, tag_name)
    if not tag_id:
        return jsonify({
            'status': 'success',
            'message': 'Solution does not have the tag'
        })

    # Remove tag from solution
    remove_tag_from_solution_command = remove_tag_from_solution_sql.format(
        sol_id=solution_id, tag_id=tag_id)
    try:
        request.cursor.execute(remove_tag_from_solution_command)
        request.conn.commit()
    except Exception:
        raise DCCAException('Fail to remove tag from solution')

    return jsonify({
        'status': 'success',
        'message': 'Success to remove tag from solution'
    })
def update_template(tid):
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    name = get_json(request).get('name')
    desc = get_json(request).get('desc')
    body = get_json(request).get('body')

    if len(tid) < 5:
        raise DCCAException('Error: invalid  parameter for "id"')

    try:
        t = update_one_tasktmplt(request.cursor, uid, tid, name, desc, body)
        request.conn.commit()
        if t and 'name' in t:
            r = {
                "status": "success",
                "message": "update template successfully"
            }
            r.update(t)
            return jsonify(r)
    except Exception as e:
        raise DCCAException(f"Error: update_template: {str(e)}")
def send_email_register():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    username = get_json(request).get('username')
    email = get_json(request).get('email')

    is_admin = True if request.headers.get('admin') == 'true' else False
    if not is_admin:
        return jsonify({
            'status': 'fail',
            'message': 'Only administrator can create user.'
        })

    password = rand_generator(size=8)

    # random password
    result = create_user(username, password, email)

    if result['status'] == 'fail':
        return jsonify(result)

    token = generate_token(result['uid'])
    account = account_str(username, email)

    # If success to create the user, then send an email
    return jsonify(
        send_email_reset_pwd(SMTP_HOST, SMTP_PORT, ADMIN_EMAIL,
                             ADMIN_EMAIL_PASSWD, email, token, account,
                             HOST_SITE))
def modify_certificate():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    body = get_json(request).get('body')
    private_key = get_json(request).get('private_key')
    chain = get_json(request).get('chain')

    update_items = {}
    if body:
        update_items['body'] = body

    if private_key:
        update_items['private_key'] = private_key

    if chain or chain is None:
        update_items['chain'] = chain

    try:
        update_solution_certificate(request.cursor, uid, update_items)
        request.conn.commit()
    except Exception as e:
        raise DCCAException(str(e))

    return jsonify({
        'status': 'success',
        'message': 'Success to modify certificate'
    })
def create_certificate():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    cert_body = get_json(request).get('body')
    cert_private_key = get_json(request).get('private_key')
    cert_chain = get_json(request).get('chain')

    result = validate_create_cert(request.cursor,
                                  user_id=uid,
                                  cert_body=cert_body,
                                  cert_private_key=cert_private_key,
                                  cert_chain=cert_chain)

    if result['status'] == 'fail':
        return jsonify(result)

    try:
        create_solution_cert(request.cursor, cert_body, cert_private_key,
                             cert_chain, uid)
        request.conn.commit()
    except Exception as e:
        error_msg = 'Fail to create solution certificate.'
        if IS_DEBUG:
            error_msg += str(e)
        raise DCCAException(error_msg)

    return jsonify({
        'status': 'success',
        'message': 'Success to create certificate.'
    })
def create_vendor():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    is_admin = True if request.headers.get('admin') == 'true' else False
    if not is_admin:
        return jsonify({
            'status': 'fail',
            'message': NOT_ADMIN_CANNOT_CREATE_MSG
        })

    check_json(request)
    name = get_json(request).get("name")
    is_public = get_json(request).get("is_public") or False
    if not name:
        raise InvalidInputException("vendor name is empty.")

    new_item = DccaVendor(name, is_public)
    try:
        status = DccaVendor.create_one(new_item)
    except Exception:
        raise DCCAException("Create vendor failed")

    return jsonify(status)
def modify_role(role_id):
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    current_user = DccaUser.get_by_id(uid)
    if not current_user.admin:
        return jsonify({
            'status': 'fail',
            'message': 'Only admin can modify role'
        })

    check_json(request)
    name = get_json(request).get('name')
    _desc = get_json(request).get('description')
    resources = get_json(request).get('resources')

    role_id_empty(role_id)

    role = DccaRole.get_by_id(role_id)
    role_not_exist(role)

    if name:
        role.name = name

    if _desc:
        role.description = _desc
    elif _desc == '':
        role.description = ''

    role.updated_at = datetime.utcnow()

    try:
        session.add(role)
        session.flush()
    except Exception:
        raise DCCAException('Fail to modify role')

    if resources:
        try:
            for res_id in resources:
                res = DccaPermission.get_by_id(res_id)
                if res not in role.perms:
                    role.perms.append(res)
        except Exception:
            raise DCCAException('Fail to update role resource')

    try:
        session.commit()
    except Exception:
        raise DCCAException('Fail to commit')

    results = OrderedDict()
    results['status'] = 'success'
    results['message'] = 'Success to update the role'
    results['role'] = role.data()

    return jsonify(results)
def create_role():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    current_user = DccaUser.get_by_id(uid)
    if not current_user.admin:
        return jsonify({
            'status': 'fail',
            'message': 'Only admin can modify role'
        })

    check_json(request)
    name = get_json(request).get('name')
    _desc = get_json(request).get('description')
    resources = get_json(request).get('resources', [])

    role_name_empty(name)
    contain_whitespace(name)
    role_name_taken(name)

    role = DccaRole(name, _desc)
    try:
        session.add(role)
        session.flush()
    except Exception:
        raise DCCAException('Fail to create role')

    not_exist_resources = []
    appended_resources = []
    try:
        for res_id in resources:
            res = DccaPermission.get_by_id(res_id)
            if not res:
                not_exist_resources.append(res_id)

            if res and res not in role.perms:
                role.perms.append(res)
                appended_resources.append(res)

        session.commit()
    except Exception as e:
        if IS_DEBUG:
            print(e)
        raise DCCAException('Fail to append permission to role')

    results = OrderedDict()
    results['status'] = 'success'
    results['message'] = 'Success to create a role'
    results['role'] = role.data(resources=appended_resources)
    results['resource_cannot_access'] = not_exist_resources

    return jsonify(results)
def create_audit_request():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    ctx.current_user = DccaUser.get_by_id(uid)

    check_json(request)
    solution_id = get_json(request).get('solution_id')
    comments = get_json(request).get('description')
    permission = get_json(request).get('permission')

    if not DccaAssSolutionImage.is_solution_owner(solution_id):
        return jsonify({
            'status':
            "fail",
            'message':
            "Solution not exist or you are not permit to access."
        })

    solution = DccaAssSolutionImage.get(solution_id)
    if not DccaModel.check_model_permission(
            solution.model_id) and not solution.is_public:
        return jsonify({
            'status': "fail",
            'message': "Model is private, Fail ro create request."
        })

    if DccaModel.check_model_permission(
            solution.model_id) and solution.is_public:
        if DccaModel.is_bind_solution(solution_id):
            return jsonify({
                'status':
                "fail",
                'message':
                "Solution is default solution of public model, Fail to create request."
            })

    to_public = check_permission(permission)
    req = DccaSolutionAudit(uid, comments, solution_id, to_public)

    try:
        session.add(req)
        session.commit()
    except Exception as e:
        err_msg = "Fail to create request. {}".format(str(e))
        raise DCCAException(err_msg)

    return jsonify({
        "status": "success",
        "message": "Request has been created, please wait for approval",
        "id": req.id
    })
def batch_bind_customer_to_device(customer_id):
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    ctx.current_user = DccaUser.get_by_id(uid)

    empty_check(customer_id,
                error_message='The "customer_id" can not be empty.')

    customer = DccaCustomer.query_by_id(customer_id)
    empty_check(customer,
                error_message='The customer not exists or cannot accessable.')

    check_json(request)
    device_ids = get_json(request).get('device_ids', [])
    devices = Host.batch_bind_customer(device_ids, customer)

    data = []
    success = set()
    try:
        for device in devices:
            data.append(device.as_dict(schema=DeviceShortSchema))
            success.add(device.id)
            session.add(device)
        session.commit()
    except Exception:
        raise DCCAException('Fail to bind customer to devices')

    results = OrderedDict()
    results['customer'] = customer.as_dict(schema=CustomerSchema)
    results['devices'] = data
    results['failure'] = list(set(device_ids) - success)

    return jsonify(results)
def remove_vendor():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    is_admin = True if request.headers.get('admin') == 'true' else False
    ids = get_json(request).get("ids")

    if not ids:
        return jsonify({
            'status': 'fail',
            'message': 'The "vendor_ids" can not be empty'
        })

    if not is_admin:
        return jsonify({
            'status': 'fail',
            'message': NOT_ADMIN_CANNOT_CREATE_MSG
        })

    try:
        status = DccaVendor.delete(ids)
    except Exception:
        raise DCCAException("Delete vendor failed")

    return jsonify(status)
def confirm_to_reset_password():
    check_json(request)
    account = get_json(request).get('account')

    if not account:
        return jsonify({
            'status': 'fail',
            'message': 'Username or email cannot be empty'
        })

    request.cursor.execute(query_user_by_name_email_sql, (account, account))

    user = request.cursor.fetchone()
    if not user:
        return jsonify({
            'status': 'fail',
            'message': 'Invalid username or email'
        })

    user = UserInfo._make(user)
    _user = user._asdict()
    username = _user['username']
    email = _user['email']

    token = generate_token(user.uid)
    account = account_str(username, email)
    return jsonify(
        send_email_reset_pwd(SMTP_HOST, SMTP_PORT, ADMIN_EMAIL,
                             ADMIN_EMAIL_PASSWD, email, token, account,
                             HOST_SITE))
def remove_app_by_names():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    app_name_list = get_json(request).get('names', [])

    client = connect_redis(REDIS_HOST, port=REDIS_PORT, pwd=REDIS_PASSWD)
    result = check_exceed_per_time_max_limit(request.cursor, client, user_id=uid,
                                             limit_type_id=LIMIT_TYPE_ID_MAX_PER_SEC_UNINSTALL,
                                             res_key=DEPLOY_APP_KEY_UNINSTALL)

    if result['status'] == 'fail':
        return jsonify(result)

    results = []
    for app_name in app_name_list:
        headers = {
            'User-Agent': 'kubectl/v1.7.0 (linux/amd64) kubernetes/d3ada01',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }

        data = '{"kind":"DeleteOptions", "apiVersion":"v1", "gracePeriodSeconds":0}'
        resource = RESOURCE_DELETE_APP_V2.format(dns=_DNS, port=APPSERVER_PORT, uid=uid, app_name=app_name)
        resp = requests.delete(resource, data=data, cert=certs, headers=headers, verify=False, timeout=7)
        results.append(json.loads(resp.content))

    return jsonify(results)
def check_deploy_params():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    parameters = get_json(request).get("parameters", {})
    # dynamic arguments
    dynamic_host_network = parameters.get('dynamic_host_network')
    dynamic_ports = parameters.get('dynamic_ports')
    dynamic_volumes = parameters.get('dynamic_volumes')
    dynamic_cap_add = parameters.get('dynamic_cap_add')

    # Handle dynamic arguments
    validate_host_network(dynamic_host_network)

    if dynamic_ports:
        validate_ports(dynamic_ports)

    if dynamic_volumes:
        validate_volumes_v2(dynamic_volumes)

    validate_cap_add(dynamic_cap_add)

    return jsonify({
        'status': 'success',
        'message': 'Valid parameters'
    })
Exemple #21
0
def attach_tag_to_applications(app_id):
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    tag_name = get_json(request).get('name')

    check_tag_name(tag_name)

    tag_id = query_tag(request.cursor, tag_name)
    if not tag_id:
        tag_id = create_tag(request.cursor, tag_name)

    attach_tag_to_app_cmd = attach_tag_to_app_sql.format(app_id=app_id,
                                                         tag_id=tag_id)
    try:
        request.cursor.execute(attach_tag_to_app_cmd)
    except Exception:
        raise DCCAException('Fail to attach tag to application!')

    request.conn.commit()
    return jsonify({
        'status':
        'success',
        'message':
        'Success attached "{}" to application'.format(tag_name)
    })
Exemple #22
0
def remove_tag_from_application(app_id):
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    tag_name = get_json(request).get('name')

    check_tag_name(tag_name)
    check_application_id(app_id)

    remove_tag_from_app_cmd = remove_tag_from_app_sql.format(
        application_id=app_id, tag_name=tag_name)
    try:
        request.cursor.execute(remove_tag_from_app_cmd)
    except Exception:
        raise DCCAException('Fail to remove tag from application')

    request.conn.commit()
    return jsonify({
        'status':
        'success',
        'message':
        'Success to remove tag "{}" from application'.format(tag_name)
    })
def modify_one_group(group_id):
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    ctx.current_user = DccaUser.get_by_id(uid)

    empty_check(group_id, error_message='The "group_id" cannot be empty.')

    check_json(request)
    name = get_json(request).get('name')
    input_valid_check(name, error_message='Invalid characters in name.')

    group = DccaDeviceGroup.get_by_id(group_id, uid)

    empty_check(group, error_message='The "group" is not accessable.')

    desc = get_json(request).get('description')

    if not name and not desc:
        return jsonify({
            'status': 'fail',
            'message': 'Empty parameters, not modified'
        })

    if name:
        group.name = name

    if desc:
        group.desc = desc
    elif desc == '':
        group.desc = ''

    group.updated_at = datetime.utcnow()

    try:
        session.add(group)
        session.commit()
    except Exception:
        raise DCCAException('Fail to update group')

    results = OrderedDict()
    results['status'] = 'success'
    results['message'] = 'Success to update group'
    results['group'] = group.as_dict(schema=DeviceGroupSchema)

    return jsonify(results)
Exemple #24
0
def create_model_view():
    """
    Create a model
    """
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    model = get_json(request).get('model')
    _type = get_json(request).get('type')
    platform = get_json(request).get('platform')
    vendor = get_json(request).get('vendor')

    if not check_is_oxm(request.cursor, user_id=uid):
        return jsonify({
            'status': 'fail',
            'message': 'Only OXM can create model'
        })

    if check_model_exist(request.cursor, model, _type, platform, vendor):
        return jsonify({
            'status': 'fail',
            'message': 'Model already exist, pick another one.'
        })

    if exceed_model_max_limit(request.cursor, user_id=uid):
        return jsonify({
            'status': 'fail',
            'message': 'Exceed the max limit model can create'
        })

    try:
        model_id = create_model(request.cursor, model, _type, platform, vendor, user_id=uid)
        request.conn.commit()

        return jsonify({
            'status': 'success',
            'message': 'Success to create model',
            'model_id': model_id
        })
    except Exception as e:
        error_msg = 'Exception, fail to create model.'
        if IS_DEBUG:
            raise DCCAException(error_msg + ' =>' + str(e))
        else:
            raise DCCAException(error_msg)
def apply_for_special_account():
    check_json(request)
    first_name = get_json(request).get('first_name')
    last_name = get_json(request).get('last_name')
    company_name = get_json(request).get('company_name')
    telephone = get_json(request).get('telephone')
    email = get_json(request).get('email')
    job_title = get_json(request).get('job_title')
    account_type_id = get_json(request).get('account_type_id')

    if not (first_name and last_name and company_name and email
            and account_type_id):
        return jsonify({'status': 'fail', 'message': 'Items cannot be empty'})

    if check_email_exists(request.cursor, email):
        return jsonify({'status': 'fail', 'message': 'Email already exists'})

    _data = query_account_types(request.cursor)
    if int(account_type_id) not in [at['id'] for at in _data['account_types']]:
        return jsonify({'status': 'fail', 'message': 'Invalid account type'})

    try:
        request.cursor.execute(create_accounts_sql,
                               (company_name, telephone, email, job_title,
                                account_type_id, first_name, last_name))
        a_id = request.cursor.fetchone()[0]
        request.conn.commit()
    except Exception:
        raise DCCAException('Exception when apply for account')

    return jsonify({
        'status': 'success',
        'message': 'Success to apply for accounts',
        'id': a_id
    })
def change_user_status():
    user_id = get_json(request).get("user_id")
    status = get_json(request).get("status")

    if status:
        if status == 'active':
            status = ACTIVE
        else:
            status = INACTIVE
        try:
            request.cursor.execute(update_user_status, (status, user_id))
            request.conn.commit()
        except Exception:
            raise DCCAException('Operate failed')

        return jsonify({
            'status': 'success',
            'message': 'Operate successfully'
        })
Exemple #27
0
def delete_model():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    model_id = get_json(request).get('model_id')

    if not check_model_owner(request.cursor, model_id, user_id=uid):
        return jsonify({
            'status': 'fail',
            'message': 'You are not the owner, refuse to access. Or model not exist'
        })

    if binding_to_devices(request.cursor, model_id):
        device_names = bind_to_device_ids(request.cursor, model_id)

        return jsonify({
            'status': 'fail',
            'message': 'This model has been binded to other devices, remove them first.the currently bound device is {}'.format(
                device_names)
        })

    if binding_to_solutions(request.cursor, model_id):
        solution_names = query_solution_name(request.cursor, model_id, user_id=uid)

        return jsonify({
            'status': 'fail',
            'message': 'This model has been binded to other solutions, permamently remove them first.The solution for this model binding is {}'.format(
                solution_names)
        })

    # Not my wish that model binds to dcca_ass_host_model
    if binding_to_ass_host_model(request.cursor, model_id):
        device_ids = bind_to_device_ids(request.cursor, model_id)
        device_names = []

        for device_id in device_ids:
            device_names.append(query_device_name(request.cursor, device_id, user_id=uid))
        return jsonify({
            'status': 'fail',
            'message': 'This model has been binded to some devices, permamently remove them before remove.The device currently binding this model is {}'.format(
                device_ids)
        })

    try:
        request.cursor.execute(delete_model_by_id_sql, (model_id,))
        request.conn.commit()
        return jsonify({
            'status': 'success',
            'message': 'Success to delete model. ID: {}'.format(model_id)
        })
    except Exception:
        raise DCCAException('Error happened when delete model #3')
def update_user_self():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    display_name = get_json(request).get('display_name') or ""
    image = get_json(request).get('image')

    try:
        request.cursor.execute(update_user_by_id_nullable_sql,
                               (display_name, image, uid))
        request.conn.commit()

        return jsonify({
            'status': 'success',
            'message': 'Success to update user\'s information.'
        })
    except Exception:
        raise DCCAException('Exception when update user\'s account')
def batch_delete_device_group():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    ctx.current_user = DccaUser.get_by_id(uid)

    check_json(request)
    group_ids = get_json(request).get('group_ids')

    empty_check(group_ids, error_message='The "group_ids" cannot be empty.')

    remove_fail_list = []
    remove_list = []
    results = OrderedDict()
    results['groups'] = OrderedDict()
    results['groups']['success'] = []
    results['groups']['fail'] = []

    for group_id in group_ids:
        group = DccaDeviceGroup.get_by_id(group_id, uid)
        if group:
            try:
                remove_list.append(group)
                group.remove()
                session.commit()
            except Exception as e:
                remove_fail_dict = {'id': group_id, 'message': e}
                remove_fail_list.append(remove_fail_dict)
                raise DCCAException('Fail to remove device group')
        else:
            message = 'Fail to remove device group'
            remove_fail_dict = {'id': group_id, 'message': message}
            remove_fail_list.append(remove_fail_dict)

    if len(remove_list) == 0:
        results['status'] = "fail"
        results['message'] = "Fail to remove device group"
        for group_fail in remove_fail_list:
            results['groups']['fail'].append(group_fail)
        results['groups']['fail_total'] = len(remove_fail_list)
    else:
        for group in remove_list:
            results['status'] = "success"
            results['message'] = "Success to remove group"
            results['groups']['success'].append(
                group.as_dict(schema=DeviceGroupBindSchema))
        results['groups']['success_total'] = len(remove_list)
        for group_fail in remove_fail_list:
            results['groups']['fail'].append(group_fail)
        results['groups']['fail_total'] = len(remove_fail_list)

    return jsonify(results)
def change_password():
    uid, err = get_oemid(request=request)
    if err is not None:
        return jsonify(UNAUTH_RESULT)

    check_json(request)
    old_password = get_json(request).get('old_password')
    new_password = get_json(request).get('new_password')
    user_id, _ = verify_user(request.cursor, uid, old_password)

    if user_id:
        update_password(request.conn, request.cursor, uid, new_password)
        return jsonify({
            'status': 'success',
            'message': 'Success to change password'
        })
    else:
        return jsonify({
            'status': 'fail',
            'message': 'Invalid username or password'
        })