def project_manage_users(): """Manage users of a project. In this initial implementation, we handle addition and removal of a user to the admin group of a project. No changes are done on the project itself. """ projects_collection = current_app.data.driver.db['projects'] users_collection = current_app.data.driver.db['users'] # TODO: check if user is admin of the project before anything if request.method == 'GET': project_id = request.args['project_id'] project = projects_collection.find_one({'_id': ObjectId(project_id)}) admin_group_id = project['permissions']['groups'][0]['group'] users = users_collection.find( {'groups': {'$in': [admin_group_id]}}, {'username': 1, 'email': 1, 'full_name': 1}) return jsonify({'_status': 'OK', '_items': list(users)}) # The request is not a form, since it comes from the API sdk data = json.loads(request.data) project_id = ObjectId(data['project_id']) target_user_id = ObjectId(data['user_id']) action = data['action'] current_user_id = g.current_user['user_id'] project = projects_collection.find_one({'_id': project_id}) # Check if the current_user is owner of the project, or removing themselves. remove_self = target_user_id == current_user_id and action == 'remove' if project['user'] != current_user_id and not remove_self: return abort_with_error(403) admin_group = get_admin_group(project) # Get the user and add the admin group to it if action == 'add': operation = '$addToSet' log.info('project_manage_users: Adding user %s to admin group of project %s', target_user_id, project_id) elif action == 'remove': log.info('project_manage_users: Removing user %s from admin group of project %s', target_user_id, project_id) operation = '$pull' else: log.warning('project_manage_users: Unsupported action %r called by user %s', action, current_user_id) raise wz_exceptions.UnprocessableEntity() users_collection.update({'_id': target_user_id}, {operation: {'groups': admin_group['_id']}}) user = users_collection.find_one({'_id': target_user_id}, {'username': 1, 'email': 1, 'full_name': 1}) user['_status'] = 'OK' return jsonify(user)
def api_templates(context=None): # Не пора бы нам от этой ерунды избавиться? # Неа, нам нужно подключение к разным БД (http://stackoverflow.com/questions/7923966/flask-sqlalchemy-with-dynamic-database-connections) # А в Гиппократе всё работает. Там те же две БД. if not context: return jsonify(None) templates = Rbprinttemplate.query.filter( Rbprinttemplate.context == context) return jsonify([{ 'id': t.id, 'code': t.code, 'name': t.name, 'meta': t.meta_data, } for t in templates])
def latest_comments(): latest = latest_nodes({'node_type': 'comment', 'properties.status': 'published'}, {'project': 1, 'parent': 1, 'user': 1, 'properties.content': 1, 'node_type': 1, 'properties.status': 1, 'properties.is_reply': 1}, has_public_project, 6) # Embed the comments' parents. nodes = current_app.data.driver.db['nodes'] parents = {} for comment in latest: parent_id = comment['parent'] if parent_id in parents: comment['parent'] = parents[parent_id] continue parent = nodes.find_one(parent_id) parents[parent_id] = parent comment['parent'] = parent embed_project(latest) embed_user(latest) return jsonify({'_items': latest})
def latest_assets(): latest = latest_nodes({'node_type': 'asset', 'properties.status': 'published'}, {'name': 1, 'project': 1, 'user': 1, 'node_type': 1, 'picture': 1, 'properties.status': 1, 'properties.content_type': 1, 'permissions.world': 1}, has_public_project, 12) embed_user(latest) return jsonify({'_items': latest})
def _make_error_response(self): self.make_response(code=400, headers={'Content-Type': 'application/json'}, data=jsonify({ 'ok': False, 'error_code': 400, 'description': 'Bad Request: some details' }))
def create_project(overrides=None): """Creates a new project.""" if request.mimetype == 'application/json': project_name = request.json['name'] else: project_name = request.form['project_name'] user_id = g.current_user['user_id'] project = _create_new_project(project_name, user_id, overrides) # Return the project in the response. return jsonify(project, status=201, headers={'Location': '/projects/%s' % project['_id']})
def project_quotas(project_id): """Returns information about the project's limits.""" # Check that the user has GET permissions on the project itself. project = mongo.find_one_or_404('projects', project_id) check_permissions('projects', project, 'GET') file_size_used = project_total_file_size(project_id) info = { 'file_size_quota': None, # TODO: implement this later. 'file_size_used': file_size_used, } return jsonify(info)
def _make_normal_response(self, text: str): self.make_response(code=200, headers={'Content-Type': 'application/json'}, data=jsonify({ 'ok': True, 'result': { 'message_id': 1, 'date': 1, 'text': text, 'chat': { 'id': 1, 'type': 'private' } } }))
def make_response(self, headers: dict = None, data: bytes = None, json=None, code: int = 200): if json is not None and data is None: data = jsonify(json) self.send_response(code) if headers is None: headers = {} if data is not None: headers['Content-Length'] = len(data) for header, value in headers.items(): self.send_header(header, value) self.end_headers() if data is not None: self.wfile.write(data)
def texture_libraries(): # Use Eve method so that we get filtering on permissions for free. # This gives all the projects that contain the required node types. request.args = MultiDict(request.args) # allow changes; it's an ImmutableMultiDict by default. request.args.setlist(eve_config.QUERY_PROJECTION, [TL_PROJECTION]) request.args.setlist(eve_config.QUERY_SORT, [TL_SORT]) # Construct eve-like response. projects = list(keep_fetching_texture_libraries(has_texture_node)) result = {'_items': projects, '_meta': { 'max_results': len(projects), 'page': 1, 'total': len(projects), }} return utils.jsonify(result)
def texture_libraries(): # Use Eve method so that we get filtering on permissions for free. # This gives all the projects that contain the required node types. request.args = MultiDict( request.args) # allow changes; it's an ImmutableMultiDict by default. request.args.setlist(eve_config.QUERY_PROJECTION, [TL_PROJECTION]) request.args.setlist(eve_config.QUERY_SORT, [TL_SORT]) # Construct eve-like response. projects = list(keep_fetching_texture_libraries(has_texture_node)) result = { '_items': projects, '_meta': { 'max_results': len(projects), 'page': 1, 'total': len(projects), } } return utils.jsonify(result)
def handle_render_template_error(err): name = u'Ошибка формирования шаблона печати для документа "%s". Свяжитесь с администратором.' % err.data[ 'template_name'] err_msg = err.message detailed_msg = u'\n'.join([ u'%s' % { RenderTemplateException.Type.syntax: u'Ошибка в синтаксисе шаблона, строка %s' % err.data.get('lineno'), RenderTemplateException.Type.other: u'Ошибка на сервере печати' }[err.data['type']] ]) return jsonify( { 'name': name, 'data': { 'err_msg': err_msg, 'detailed_msg': detailed_msg, 'trace': err.data.get('trace') } }, 500, 'error')
def project_manage_users(): """Manage users of a project. In this initial implementation, we handle addition and removal of a user to the admin group of a project. No changes are done on the project itself. """ projects_collection = current_app.data.driver.db['projects'] users_collection = current_app.data.driver.db['users'] # TODO: check if user is admin of the project before anything if request.method == 'GET': project_id = request.args['project_id'] project = projects_collection.find_one({'_id': ObjectId(project_id)}) admin_group_id = project['permissions']['groups'][0]['group'] users = users_collection.find({'groups': { '$in': [admin_group_id] }}, { 'username': 1, 'email': 1, 'full_name': 1 }) return jsonify({'_status': 'OK', '_items': list(users)}) # The request is not a form, since it comes from the API sdk data = json.loads(request.data) project_id = ObjectId(data['project_id']) target_user_id = ObjectId(data['user_id']) action = data['action'] current_user_id = g.current_user['user_id'] project = projects_collection.find_one({'_id': project_id}) # Check if the current_user is owner of the project, or removing themselves. remove_self = target_user_id == current_user_id and action == 'remove' if project['user'] != current_user_id and not remove_self: return abort_with_error(403) admin_group = get_admin_group(project) # Get the user and add the admin group to it if action == 'add': operation = '$addToSet' log.info( 'project_manage_users: Adding user %s to admin group of project %s', target_user_id, project_id) elif action == 'remove': log.info( 'project_manage_users: Removing user %s from admin group of project %s', target_user_id, project_id) operation = '$pull' else: log.warning( 'project_manage_users: Unsupported action %r called by user %s', action, current_user_id) raise wz_exceptions.UnprocessableEntity() users_collection.update({'_id': target_user_id}, {operation: { 'groups': admin_group['_id'] }}) user = users_collection.find_one({'_id': target_user_id}, { 'username': 1, 'email': 1, 'full_name': 1 }) user['_status'] = 'OK' return jsonify(user)
def my_info(): eve_resp, _, _, status, _ = get('users', {'_id': g.current_user['user_id']}) resp = jsonify(eve_resp['_items'][0], status=status) return resp