Exemple #1
0
def get_claims():
    try:
        authorization = request.headers.get('Authorization', None)
        if not authorization:
            return 0

        parts = authorization.split()
        if len(parts) < 2 or parts[0] != 'Bearer':
            return 0

        token = parts[1]
        claims = jws.verify(token)
        url_rule = str(request.url_rule)
        if config.api.get('force_check_binding'):
            found = _force_check_menu_apis(url_rule)
            if not found:
                return -1

        if claims is False:
            return 0

        if claims.get('is_admin'):
            return claims

        method = request.method.lower()
        if url_rule in routes.get('Default'):
            return claims

        username = claims.get('username')
        user_id = claims.get('user_id')
        user = User()
        if not user_id:
            user_info = User.find_one({'username': username})
            user_id = str(user_info['_id'])

        menus, roles = user.get_permissions(user_id)
        if not menus:
            return -1

        is_allow = -1
        for menu in menus:
            apis = menu.get('apis')
            actions = menu.get('actions')
            if not apis:
                continue

            if url_rule in apis and method in actions:
                is_allow = 1
                break

        return claims if is_allow == 1 else is_allow
    except JWTError:
        return False
Exemple #2
0
def add_user():
    payload = request.get_json()
    if not payload:
        return jsonify({
            'message': 'invalid params',
            'code': 104000
        }), 400

    current_user = login_user.get('username')
    is_admin = login_user.get('is_admin')
    username = payload.get('username')
    nickname = payload.get('nickname')
    email = payload.get('email')
    phone = payload.get('phone')
    role_ids = payload.get('role_ids')
    team_id = payload.get('team_id')
    address = payload.get('address')
    password = payload.get('password')
    if not username or not email:
        return jsonify({
            'message': 'miss required params',
            'code': 104001,
        }), 400

    if not is_admin:
        if team_id:
            team = Team.find_by_id(team_id)
            if not team or current_user not in team.get('master'):
                return jsonify({
                    'message': 'permission deny',
                    'code': 104031
                }), 403
        else:
            return jsonify({
                'message': 'permission deny',
                'code': 104032,
            }), 403

    where = {
        '$or': [
            {'username': username},
            {'email': email},
        ]
    }
    existed = User.find_one(where)
    if existed:
        return jsonify({
            'message': 'username or email existed',
            'code': 104030
        }), 400

    password = password or gen_password()
    encrypt_pwd = generate_password_hash(password)
    user_info = {
        'username': username,
        'nickname': nickname,
        'password': encrypt_pwd,
        'email': email,
        'phone': phone,
        'active': 0,
        'address': address,
        'created_at': time.time(),
        'add_by': login_user.get('username'),
    }
    result = User.insert_one(user_info)
    user_id = str(result.inserted_id)
    if role_ids:
        role_ids = role_ids if type(role_ids) == list else [role_ids]
        roles = Role.find_by_ids(role_ids)
        if roles:
            for item in roles:
                data = {
                    'role_id': str(item['_id']),
                    'user_id': user_id,
                    'add_by': login_user.get('username'),
                    'created_at': time.time(),
                }
                db.collection('user_roles').insert_one(data)
    if team_id:
        Team().add_member(team_id=team_id, members=[user_id], owner_id=login_user.get('user_id'))

    notify = SMTP()
    text = '''
    <p>Dear user:</p>
    <p>Your eclogue account is active~!</p>
    <p>username: {}</p>
    <p>password: {} </p>
    '''
    text = text.format(username, password)
    notify.send(text, to=email, subject='', subtype='html')

    return jsonify({
        'message': 'ok',
        'code': 0,
        'data': password
    })
Exemple #3
0
def update_user(_id):
    payload = request.get_json()
    record = User.find_by_id(_id)
    if not record:
        return jsonify({
            'message': 'record not found',
            'code': 104040
        }), 404

    if not payload:
        return jsonify({
            'message': 'illegal params',
            'code': 104000
        }), 400

    current_user_id = login_user.get('user_id')
    is_admin = login_user.get('is_admin')
    username = payload.get('username')
    nickname = payload.get('nickname')
    email = payload.get('email')
    phone = payload.get('phone')
    role_ids = payload.get('role')
    team_id = payload.get('team_id')
    address = payload.get('address')
    # current_team_id = payload.get('currentTeamId')
    # current_role_ids = payload.get('currentRoleIds')
    if not is_admin:
        return jsonify({
            'message': 'bad permission',
            'code': 104130
        }), 403

    update = {}
    if username and record['username'] != username:
        update['username'] = username
        check = User.find_one({'username': username})
        if check:
            return jsonify({
                'message': 'username existed',
                'code': 104001
            }), 400

    if email and record.get('email') != email:
        update['email'] = email
        check = User.find_one({'email': email})
        if check:
            return jsonify({
                'message': 'email existed',
                'code': 104001
            }), 400

    if phone and record.get('phone') != phone:
        update['phone'] = phone
        check = User.find_one({'phone': phone})
        if check:
            return jsonify({
                'message': 'phone existed',
                'code': 104001
            }), 400

    if nickname:
        update['nickname'] = nickname

    if address:
        update['address'] = address

    if team_id:
        change = {
            '$set': {
                'team_id': team_id,
                'user_id': _id,
                'updated_at': time.time(),
            }
        }
        condition = {
            'user_id': _id,
        }
        db.collection('team_members').update_one(condition, update=change, upsert=True)

    if role_ids:
        result = User().bind_roles(_id, role_ids, add_by=login_user.get('username'))

    User.update_one({'_id': record['_id']}, {'$set': update})

    return jsonify({
        'message': 'ok',
        'code': 0,
    })
Exemple #4
0
def run_playbook_task(_id, request_id, username, history_id, **kwargs):
    db = Mongo()
    record = Job.find_by_id(ObjectId(_id))
    task_record = TaskModel.find_one({'request_id': request_id})
    if not task_record:
        return False

    start_at = time()
    state = 'progressing'
    result = ''
    task_id = task_record.get('_id')
    job_id = task_record.get('job_id')
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stderr = sys.stdout = temp_stdout = Reporter(str(task_id))
    try:
        if history_id:
            history = db.collection('build_history').find_one(
                {'_id': ObjectId(history_id)})
            record = history['job_info']
            kwargs = task_record.get('kwargs')

        template = record.get('template')
        body = {
            'template': record.get('template'),
            'extra': record.get('extra')
        }

        payload = load_ansible_playbook(body)
        if payload.get('message') is not 'ok':
            raise Exception('load ansible options error: ' +
                            payload.get('message'))

        app_id = template.get('app')
        if app_id:
            app_info = Application.find_by_id(ObjectId(app_id))
            if not app_info:
                raise Exception('app not found: {}'.format(app_id))

            app_type = app_info.get('type')
            app_params = app_info.get('params')
            if kwargs:
                app_params.update(kwargs)

            integration = Integration(app_type, app_params)
            integration.install()

        data = payload.get('data')
        options = data.get('options')
        private_key = data.get('private_key')
        wk = Workspace()
        roles = data.get('roles')
        if history_id:
            bookspace = wk.build_book(history_id)
        else:
            bookname = data.get('book_name')
            bookspace = wk.load_book_from_db(name=bookname,
                                             roles=roles,
                                             build_id=task_id)

        if not bookspace or not os.path.isdir(bookspace):
            raise Exception('install playbook failed, book name: {}'.format(
                data.get('book_name')))

        entry = os.path.join(bookspace, data.get('entry'))

        with NamedTemporaryFile('w+t', delete=False) as fd:
            if private_key:
                key_text = get_credential_content_by_id(
                    private_key, 'private_key')
                if not key_text:
                    raise Exception('invalid private_key')

                fd.write(key_text)
                fd.seek(0)
                options['private-key'] = fd.name

            options['tags'] = ['uptime']
            options['verbosity'] = 2
            inventory = data.get('inventory')
            logger.info('ansible-playbook run load inventory: \n{}'.format(
                yaml.safe_dump(inventory)))
            play = PlayBookRunner(data.get('inventory'),
                                  options,
                                  job_id=job_id)
            play.run(entry)
            result = play.get_result()
            builds = db.collection('build_history').count({'job_id': _id})
            state = 'finish'
            # @todo
            if builds > cache_result_numer:
                last_one = db.collection('build_history').find_one(
                    {'job_id': _id}, sort=[('_id', 1)])
                if last_one:
                    db.fs().delete(last_one.get('file_id'))
                    db.collection('build_history').delete_one(
                        {'_id': last_one['_id']})

            with TemporaryDirectory() as dir_name:
                bookname = data.get('book_name')
                zip_file = os.path.join(dir_name, bookname)
                zip_file = make_zip(bookspace, zip_file)
                with open(zip_file, mode='rb') as stream:
                    filename = bookname + '.zip'
                    file_id = db.save_file(filename=filename, fileobj=stream)
                    store_info = {
                        'task_id': str(task_id),
                        'file_id': str(file_id),
                        'job_id': str(_id),
                        'job_info': record,
                        'filename': filename,
                        'created_at': time(),
                        'kwargs': kwargs,
                    }
                    db.collection('build_history').insert_one(store_info)
                    shutil.rmtree(bookspace)

    except Exception as e:
        result = str(e)
        extra = {'task_id': task_id}
        logger.error('run task with exception: {}'.format(str(e)), extra=extra)
        state = 'error'
        extra_options = record.get('extra')
        user = User.find_one({'username': username})
        if user:
            user_id = str(user['_id'])
            notification = extra_options.get('notification')
            message = '[error]run job: {}, message: {}'.format(
                record.get('name'), str(e))
            sys.stdout.write(message)
            if notification and type(notification) == list:
                Notify().dispatch(user_id=user_id,
                                  msg_type='task',
                                  content=message,
                                  channel=notification)

    finally:
        content = temp_stdout.getvalue()
        temp_stdout.close(True)
        sys.stdout = old_stdout
        sys.stderr = old_stderr
        finish_at = time()
        update = {
            '$set': {
                'start_at': start_at,
                'finish_at': finish_at,
                'state': state,
                'duration': finish_at - start_at,
                'result': result,
            }
        }
        TaskModel.update_one({'_id': task_id}, update=update)
        trace = {
            'task_id': str(task_id),
            'request_id': request_id,
            'username': username,
            'content': str(content),
            'created_at': time(),
        }
        db.collection('task_logs').insert_one(trace)