Ejemplo n.º 1
0
def _add_graph(request, graph={}):
    """
	Graph Parameters
	----------
	name : string
		Name of group. Required
	owner_email : string
		Email of the Owner of the graph. Required
	tags: list of strings
		List of tags to be attached with the graph. Optional


	Parameters
	----------
	graph : dict
		Dictionary containing the data of the graph being added.
	request : object
		HTTP POST Request.

	Returns
	-------
	graph : object
		Newly created graph object.

	Raises
	------
	BadRequest - Cannot create graph for user other than the requesting user.

	Notes
	------

	"""

    # Validate add graph API request
    user_role = authorization.user_role(request)
    if user_role == authorization.UserRole.LOGGED_IN:
        if get_request_user(request) != graph.get('owner_email', None):
            raise BadRequest(
                request,
                error_code=ErrorCodes.Validation.CannotCreateGraphForOtherUser,
                args=graph.get('owner_email', None))
    elif user_role == authorization.UserRole.LOGGED_OFF and graph.get(
            'owner_email', None) is not None:
        raise BadRequest(
            request,
            error_code=ErrorCodes.Validation.CannotCreateGraphForOtherUser,
            args=graph.get('owner_email', None))

    return utils.serializer(
        graphs.add_graph(request,
                         name=graph.get('name', None),
                         is_public=graph.get('is_public', None),
                         graph_json=graph.get('graph_json', None),
                         style_json=graph.get('style_json', None),
                         tags=graph.get('tags', None),
                         owner_email=graph.get('owner_email', None)))
Ejemplo n.º 2
0
def _graph_groups_api(request, graph_id, group_id=None):
    """
	Handles any request (GET/POST) sent to graphs/<graph_id>/groups or graphs/<graph_id>/groups/<group_id>.

	Parameters
	----------
	request - HTTP Request
	graph_id : string
		Unique ID of the graph.

	Returns
	-------

	Raises
	------
	MethodNotAllowed: If a user tries to send requests other than GET, POST, PUT or UPDATE.
	BadRequest: If HTTP_ACCEPT header is not set to application/json.
	BadRequest: If graph_id is missing.

	"""
    if request.META.get('HTTP_ACCEPT', None) == 'application/json':
        if graph_id is None:
            raise BadRequest(request,
                             error_code=ErrorCodes.Validation.GraphIDMissing)

        if request.method == "GET" and group_id is None:
            return HttpResponse(json.dumps(
                _get_graph_groups(request, graph_id, query=request.GET)),
                                content_type="application/json")
        elif request.method == "POST" and group_id is None:
            return HttpResponse(json.dumps(
                _add_graph_group(request,
                                 graph_id,
                                 group=json.loads(request.body))),
                                content_type="application/json",
                                status=201)
        elif request.method == "DELETE" and group_id is not None:
            _delete_graph_group(request, graph_id, group_id)
            return HttpResponse(json.dumps({
                "message":
                "Successfully deleted graph with id=%s from group with id=%s" %
                (graph_id, group_id)
            }),
                                content_type="application/json",
                                status=200)
        else:
            raise MethodNotAllowed(
                request
            )  # Handle other type of request methods like OPTIONS etc.
    else:
        raise BadRequest(request)
def register(request, username=None, password=None):
    if db.get_user(request.db_session, username):
        raise BadRequest(request,
                         error_code=ErrorCodes.Validation.UserAlreadyExists,
                         args=username)

    return add_user(request, email=username, password=password)
Ejemplo n.º 4
0
def _group_graphs_api(request, group_id, graph_id=None):
	"""
	Handles any request (GET/POST) sent to groups/<group_id>/graphs or groups/<group_id>/graphs/<graph_id>.

	Parameters
	----------
	request - HTTP Request
	group_id : string
		Unique ID of the group.

	Returns
	-------

	"""
	if request.META.get('HTTP_ACCEPT', None) == 'application/json':
		if request.method == "GET" and graph_id is None:
			return HttpResponse(json.dumps(_get_group_graphs(request, group_id)),
								content_type="application/json")
		elif request.method == "POST" and graph_id is None:
			return HttpResponse(json.dumps(_add_group_graph(request, group_id)), content_type="application/json",
								status=201)
		elif request.method == "DELETE" and graph_id is not None:
			_delete_group_graph(request, group_id, graph_id)
			return HttpResponse(json.dumps({
				"message": "Successfully deleted graph with id=%s from group with id=%s" % (graph_id, group_id)
			}), content_type="application/json", status=200)
		else:
			raise MethodNotAllowed(request)  # Handle other type of request methods like OPTIONS etc.
	else:
		raise BadRequest(request)
Ejemplo n.º 5
0
def _group_members_api(request, group_id, member_id=None):
	"""
	Handles any request (GET/POST) sent to groups/<group_id>/members or groups/<group_id>/members/<member_id>.

	Parameters
	----------
	request - HTTP Request

	Returns
	-------

	"""
	if request.META.get('HTTP_ACCEPT', None) == 'application/json':
		if group_id is None:
			raise Exception("Group ID is required.")

		if request.method == "GET" and member_id is None:
			return HttpResponse(json.dumps(_get_group_members(request, group_id)),
								content_type="application/json")
		elif request.method == "POST" and member_id is None:
			return HttpResponse(json.dumps(_add_group_member(request, group_id)), content_type="application/json",
								status=201)
		elif request.method == "DELETE" and member_id is not None:
			_delete_group_member(request, group_id, member_id)
			return HttpResponse(json.dumps({
				"message": "Successfully deleted member with id=%s from group with id=%s" % (member_id, group_id)
			}), content_type="application/json", status=200)
		else:
			raise MethodNotAllowed(request)  # Handle other type of request methods like OPTIONS etc.
	else:
		raise BadRequest(request)
Ejemplo n.º 6
0
def _groups_api(request, group_id=None):
	"""
	Handles any request (GET/POST) sent to /groups or groups/<group_id>

	Parameters
	----------
	request - HTTP Request

	Returns
	-------

	"""
	if request.META.get('HTTP_ACCEPT', None) == 'application/json':
		if request.method == "GET" and group_id is None:
			return HttpResponse(json.dumps(_get_groups(request, query=request.GET)), content_type="application/json")
		elif request.method == "GET" and group_id is not None:
			return HttpResponse(json.dumps(_get_group(request, group_id)), content_type="application/json",
								status=200)
		elif request.method == "POST" and group_id is None:
			return HttpResponse(json.dumps(_add_group(request, group=request.POST)), content_type="application/json",
								status=201)
		elif request.method == "PUT" and group_id is not None:
			return HttpResponse(json.dumps(_update_group(request, group_id, group=QueryDict(request.body))),
								content_type="application/json",
								status=200)
		elif request.method == "DELETE" and group_id is not None:
			_delete_group(request, group_id)
			return HttpResponse(json.dumps({
				"message": "Successfully deleted group with id=%s" % group_id
			}), content_type="application/json", status=200)
		else:
			raise MethodNotAllowed(request)  # Handle other type of request methods like OPTIONS etc.
	else:
		raise BadRequest(request)
Ejemplo n.º 7
0
def add_layout(request, owner_email=None, name=None, graph_id=None, is_shared=None, style_json=None,
               positions_json=None):
	if name is None or owner_email is None or graph_id is None:
		raise Exception("Required Parameter is missing!")
	try:
		return db.add_layout(request.db_session, owner_email=owner_email, name=name, graph_id=graph_id,
		                     is_shared=is_shared, style_json=dumps(style_json), positions_json=dumps(positions_json))
	except IntegrityError as e:
		raise BadRequest(request, error_code=ErrorCodes.Validation.LayoutNameAlreadyExists, args=name)
Ejemplo n.º 8
0
def _graphs_api(request, graph_id=None):
    """
	Handles any request sent to following urls:
		/graphs
		/graphs/<graph_id>

	Parameters
	----------
	request - HTTP Request

	Returns
	-------
	response : JSON Response

	Raises
	------
	MethodNotAllowed: If a user tries to send requests other than GET, POST, PUT or UPDATE.
	BadRequest: If HTTP_ACCEPT header is not set to application/json.

	"""
    if request.META.get('HTTP_ACCEPT', None) == 'application/json':
        if request.method == "GET" and graph_id is None:
            return HttpResponse(json.dumps(
                _get_graphs(request, query=request.GET)),
                                content_type="application/json")
        elif request.method == "GET" and graph_id is not None:
            return HttpResponse(json.dumps(_get_graph(request, graph_id)),
                                content_type="application/json",
                                status=200)
        elif request.method == "POST" and graph_id is None:
            return HttpResponse(json.dumps(
                _add_graph(request, graph=json.loads(request.body))),
                                content_type="application/json",
                                status=201)
        elif request.method == "PUT" and graph_id is not None:
            return HttpResponse(json.dumps(
                _update_graph(request,
                              graph_id,
                              graph=json.loads(request.body))),
                                content_type="application/json",
                                status=200)
        elif request.method == "DELETE" and graph_id is not None:
            _delete_graph(request, graph_id)
            return HttpResponse(json.dumps({
                "message":
                "Successfully deleted graph with id=%s" % graph_id
            }),
                                content_type="application/json",
                                status=200)
        else:
            raise MethodNotAllowed(
                request
            )  # Handle other type of request methods like OPTIONS etc.
    else:
        raise BadRequest(request)
Ejemplo n.º 9
0
def _graph_layouts_api(request, graph_id, layout_id=None):
    """
	Handles any request (GET/POST) sent to /layouts or /layouts/<layout_id>.

	Parameters
	----------
	request - HTTP Request
	graph_id : string
		Unique ID of the graph.
	layout_id: string
		Unique ID of the layout.

	Returns
	-------

	"""
    if request.META.get('HTTP_ACCEPT', None) == 'application/json':
        if request.method == "GET" and layout_id is None:
            return HttpResponse(json.dumps(
                _get_layouts(request, graph_id, query=request.GET)),
                                content_type="application/json")
        elif request.method == "GET" and layout_id is not None:
            return HttpResponse(json.dumps(
                _get_layout(request, graph_id, layout_id)),
                                content_type="application/json")
        elif request.method == "POST" and layout_id is None:
            return HttpResponse(json.dumps(
                _add_layout(request, graph_id,
                            layout=json.loads(request.body))),
                                content_type="application/json",
                                status=201)
        elif request.method == "PUT" and layout_id is not None:
            return HttpResponse(json.dumps(
                _update_layout(request,
                               graph_id,
                               layout_id,
                               layout=json.loads(request.body))),
                                content_type="application/json",
                                status=200)
        elif request.method == "DELETE" and layout_id is not None:
            _delete_layout(request, graph_id, layout_id)
            return HttpResponse(json.dumps({
                "message":
                "Successfully deleted layout with id=%s" % (layout_id)
            }),
                                content_type="application/json",
                                status=200)
        else:
            raise MethodNotAllowed(
                request
            )  # Handle other type of request methods like OPTIONS etc.
    else:
        raise BadRequest(request)
Ejemplo n.º 10
0
def _add_layout(request, graph_id, layout={}):
    """
	Layout Parameters
	----------
	name : string
		Name of the layout. Required
	owner_email : string
		Email of the Owner of the graph. Required
	graph_id : string
		Unique ID of the graph for the layout. Required


	Parameters
	----------
	layout : dict
		Dictionary containing the data of the layout being added.
	request : object
		HTTP POST Request.

	Returns
	-------
	layout : object
		Newly created layout object.

	Raises
	------

	Notes
	------

	"""
    authorization.validate(request, permission='GRAPH_READ', graph_id=graph_id)

    # Validate add graph API request
    user_role = authorization.user_role(request)
    if user_role == authorization.UserRole.LOGGED_IN:
        if get_request_user(request) != layout.get('owner_email', None):
            raise BadRequest(request,
                             error_code=ErrorCodes.Validation.
                             CannotCreateLayoutForOtherUser,
                             args=layout.get('owner_email', None))

    return utils.serializer(
        graphs.add_layout(
            request,
            owner_email=layout.get('owner_email', None),
            name=layout.get('name', None),
            graph_id=layout.get('graph_id', None),
            is_shared=layout.get('is_shared', None),
            positions_json=layout.get('positions_json', None),
            style_json=layout.get('style_json', None),
        ))
Ejemplo n.º 11
0
def _add_group(request, group={}):
    """
	Group Parameters
	----------
	name : string
		Name of group. Required
	description : string
		Description of the group. Optional
	owner_email : string
		Email of the Owner of the groups. Required


	Parameters
	----------
	group : dict
		Dictionary containing the data of the group being added.
	request : object
		HTTP POST Request.

	Returns
	-------
	group : object
		Newly created group object.

	Raises
	------

	Notes
	------

	"""

    # Validate add graph API request
    user_role = authorization.user_role(request)
    if user_role == authorization.UserRole.LOGGED_IN:
        if get_request_user(request) != group.get('owner_email', None):
            raise BadRequest(
                request,
                error_code=ErrorCodes.Validation.CannotCreateGroupForOtherUser,
                args=group.get('owner_email', None))

    return utils.serializer(
        users.add_group(request,
                        name=request.POST.get('name', None),
                        description=group.get('description', None),
                        owner_email=group.get('owner_email', None)))
Ejemplo n.º 12
0
def _users_api(request):
	"""
	Handles any request (GET/POST) sent to /users.

	Parameters
	----------
	request - HTTP Request

	Returns
	-------

	"""
	if 'application/json' in request.META.get('HTTP_ACCEPT', None):
		if request.method == "GET":
			return HttpResponse(json.dumps(_get_users(request, query=request.GET)), content_type="application/json")
		else:
			raise MethodNotAllowed(request)  # Handle other type of request methods like OPTIONS etc.
	else:
		raise BadRequest(request)
def add_group_member(request, group_id, member_id=None, member_email=None):
    if member_id is not None:
        user = db.get_user_by_id(request.db_session, id=member_id)
    elif member_email is not None:
        user = db.get_user(request.db_session, email=member_email)
    else:
        raise Exception("Required Parameter is missing!")
    if user is not None:
        if db.get_group_to_user(request.db_session, group_id, user.id):
            raise BadRequest(
                request,
                error_code=ErrorCodes.Validation.UserAlreadyExists,
                args=user.email)

        return db.add_group_to_user(request.db_session,
                                    group_id=group_id,
                                    user_id=user.id)
    else:
        raise Exception("User does not exit.")
Ejemplo n.º 14
0
def _get_layouts(request, graph_id, query=dict()):
    """
	Query Parameters
	----------
	owner_email : string
		Email of the Owner of the groups.
	limit : integer
		Number of entities to return. Default value is 20.
	offset : integer
		Offset the list of returned entities by this number. Default value is 0.
	name : string
		Search for groups with given name. In order to search for layouts with given name as a substring, wrap the name with percentage symbol. For example, %xyz% will search for all layouts with xyz in their name.
	order : string
		Defines the column sort order, can only be 'asc' or 'desc'.
	sort : string
		Defines which column will be sorted.

	Parameters
	----------
	query : dict
		Dictionary of query parameters.
	request : object
		HTTP GET Request.

	Returns
	-------
	total : integer
		Number of groups matching the request.
	groups : List of Layouts.
		List of Layout Objects with given limit and offset.

	Raises
	------

	Notes
	------
	"""
    authorization.validate(request, permission='GRAPH_READ', graph_id=graph_id)

    querydict = QueryDict('', mutable=True)
    querydict.update(query)
    query = querydict

    # Validate search layouts API request
    user_role = authorization.user_role(request)
    if user_role == authorization.UserRole.LOGGED_IN:
        if get_request_user(request) != query.get('owner_email', None) \
          and (query.get('is_shared', None) is None or int(query.get('is_shared', 0)) != 1):
            raise BadRequest(
                request,
                error_code=ErrorCodes.Validation.NotAllowedLayoutAccess,
                args=get_request_user(request))

    total, layouts = graphs.search_layouts(
        request,
        owner_email=query.get('owner_email', None),
        name=query.get('name', None),
        is_shared=query.get('is_shared', None),
        graph_id=graph_id,
        limit=query.get('limit', 20),
        offset=query.get('offset', 0),
        order=query.get('order', 'desc'),
        sort=query.get('sort', 'name'))

    return {
        'total': total,
        'layouts': [utils.serializer(layout) for layout in layouts]
    }
Ejemplo n.º 15
0
def _get_graph_groups(request, graph_id, query={}):
    """

	Query Parameters
	----------
	owner_email : string
		Email of the Owner of the groups.
	member_email: string
		Email of the member of the groups.
	limit : integer
		Number of entities to return. Default value is 20.
	offset : integer
		Offset the list of returned entities by this number. Default value is 0.
	name : string
		Search for groups with given name. In order to search for groups with given name as a substring, wrap the name with percentage symbol. For example, %xyz% will search for all groups with xyz in their name.
	description : string
		Search for groups with given description. In order to search for groups with given description as a substring, wrap the description with percentage symbol. For example, %xyz% will search for all groups with xyz in their description.
	order : string
		Defines the column sort order, can only be 'asc' or 'desc'.
	sort : string
		Defines which column will be sorted.


	Parameters
	----------
	request : object
		HTTP GET Request.
	graph_id : string
		Unique ID of the graph.

	Returns
	-------
	total : integer
		Number of groups matching the request.
	groups : List of Groups.
		List of Group Objects with given limit and offset.

	Raises
	------
	BadRequest: If the user is not admin and tries to access groups where user is neither owner or member.

	Notes
	------

	"""
    authorization.validate(request, permission='GRAPH_READ', graph_id=graph_id)

    # Validate search graph groups API request
    user_role = authorization.user_role(request)
    if user_role == authorization.UserRole.LOGGED_IN:
        if query.get('is_public', None) is not True:
            if get_request_user(request) != query.get('member_email', None) \
              and get_request_user(request) != query.get('owner_email', None):
                raise BadRequest(
                    request,
                    error_code=ErrorCodes.Validation.NotAllowedGroupAccess,
                    args=get_request_user(request))

    total, groups = users.search_groups(
        request,
        graph_ids=[graph_id],
        owner_email=query.get('owner_email', None),
        member_email=query.get('member_email', None),
        name=query.get('name', None),
        description=query.get('description', None),
        limit=query.get('limit', 20),
        offset=query.get('offset', 0),
        order=query.get('order', 'desc'),
        sort=query.get('sort', 'name'))

    return {
        'total': total,
        'groups': [utils.serializer(group) for group in groups]
    }
Ejemplo n.º 16
0
def graphs_advanced_search_ajax_api(request):
    """
	Handles any request sent to following urls:
		/ajax/graphs

	Parameters
	----------
	request - HTTP Request

	Returns
	-------
	response : JSON Response

	"""
    if request.META.get('HTTP_ACCEPT', None) == 'application/json':
        if request.method == "POST":
            querydict = QueryDict('', mutable=True)
            querydict.update(request.GET)
            queryparams = querydict

            # Validate search graphs API request
            user_role = authorization.user_role(request)
            if user_role == authorization.UserRole.LOGGED_IN:
                if queryparams.get('owner_email', None) is None \
                  and queryparams.get('member_email', None) is None \
                  and queryparams.get('is_public', None) != '1':
                    raise BadRequest(
                        request,
                        error_code=ErrorCodes.Validation.IsPublicNotSet)
                if queryparams.get('is_public', None) != '1':
                    if get_request_user(request) != queryparams.get('member_email', None) \
                      and get_request_user(request) != queryparams.get('owner_email', None):
                        raise BadRequest(request,
                                         error_code=ErrorCodes.Validation.
                                         NotAllowedGraphAccess,
                                         args=queryparams.get(
                                             'owner_email', None))

            total, graphs_list = graphs.search_graphs1(
                request,
                owner_email=queryparams.get('owner_email', None),
                member_email=queryparams.get('member_email', None),
                names=list(filter(None, queryparams.getlist('names[]', []))),
                is_public=queryparams.get('is_public', None),
                nodes=list(filter(None, queryparams.getlist('nodes[]', []))),
                edges=list(filter(None, queryparams.getlist('edges[]', []))),
                tags=list(filter(None, queryparams.getlist('tags[]', []))),
                limit=queryparams.get('limit', 20),
                offset=queryparams.get('offset', 0),
                order=queryparams.get('order', 'desc'),
                sort=queryparams.get('sort', 'name'),
                query=json.loads(request.body))

            return HttpResponse(json.dumps({
                'total':
                total,
                'graphs': [
                    utils.serializer(graph, summary=True)
                    for graph in graphs_list
                ]
            }),
                                content_type="application/json",
                                status=200)
        else:
            raise MethodNotAllowed(
                request
            )  # Handle other type of request methods like GET, OPTIONS etc.
    else:
        raise BadRequest(request)
Ejemplo n.º 17
0
def _get_graphs(request, query=dict()):
    """
	Query Parameters
	----------
	owner_email : string
		Email of the Owner of the graphs. Required if member_email is not provided, user is not admin and is_public is not set to True.
	member_email : string
		Email of the User with which the graphs are shared. Required if owner_email is not provided, user is not admin and is_public is not set to True.
	limit : integer
		Number of entities to return. Default value is 20.
	offset : integer
		Offset the list of returned entities by this number. Default value is 0.
	is_public: integer
		Search for graphs with given visibility. In order to search for public graphs set is_public to 1. Required if member_email & owner_email are not provided.
		In order to search for private graphs set is_public to 0. In order to search for all graphs set is_public to None.
	names : list of strings
		Search for graphs with given list of names. In order to search for graphs with given name as a substring, wrap the name with percentage symbol. For example, %xyz% will search for all graphs with xyz in their name.
	nodes : list of strings
		Search for graphs with given given list of node names. In order to search for graphs with given node name as a substring, wrap the name with percentage symbol. For example, %xyz% will search for all graphs with xyz in their node name.
	edges : list of strings
		Search for graphs with the edge between given given list of node names separated by colon. In order to search for graphs with given edge as a substring, wrap the name of the nodes with percentage symbol. For example, %xyz%:%abc% will search for all graphs with edge between nodes with 'xyz' and 'abc' in their node names.
	tags : list of strings
		Search for graphs with the given given list of tag names. In order to search for graphs with given tag as a substring, wrap the name of the tag with percentage symbol. For example, %xyz% will search for all graphs with 'xyz' in their tag names.
	order : string
		Defines the column sort order, can only be 'asc' or 'desc'.
	sort : string
		Defines which column will be sorted.

	Parameters
	----------
	query : dict
		Dictionary of query parameters.
	request : object
		HTTP GET Request.
	owner_email : string
		Email of the Owner of the groups.

	Returns
	-------
	total : integer
		Number of groups matching the request.
	groups : List of Groups.
		List of Group Objects with given limit and offset.

	Raises
	------
	BadRequest - `is_public` is required to be set to True when `owner_email` and `member_email` are not provided.

	BadRequest - `User is not authorized to access private graphs created by given owner. This means either the graph belongs to a different owner
	or graph is not shared with the user.

	Notes
	------
	"""

    querydict = QueryDict('', mutable=True)
    querydict.update(query)
    query = querydict

    # Validate search graphs API request
    user_role = authorization.user_role(request)
    if user_role == authorization.UserRole.LOGGED_IN:
        if query.get('owner_email', None) is None \
          and query.get('member_email', None) is None \
          and query.get('is_public', None) != '1':
            raise BadRequest(request,
                             error_code=ErrorCodes.Validation.IsPublicNotSet)
        if query.get('is_public', None) != '1':
            if get_request_user(request) != query.get('member_email', None) \
              and get_request_user(request) != query.get('owner_email', None):
                raise BadRequest(
                    request,
                    error_code=ErrorCodes.Validation.NotAllowedGraphAccess,
                    args=query.get('owner_email', None))

    total, graphs_list = graphs.search_graphs(
        request,
        owner_email=query.get('owner_email', None),
        member_email=query.get('member_email', None),
        names=list(filter(None, query.getlist('names[]', []))),
        is_public=query.get('is_public', None),
        nodes=list(filter(None, query.getlist('nodes[]', []))),
        edges=list(filter(None, query.getlist('edges[]', []))),
        tags=list(filter(None, query.getlist('tags[]', []))),
        limit=query.get('limit', 20),
        offset=query.get('offset', 0),
        order=query.get('order', 'desc'),
        sort=query.get('sort', 'name'))

    return {
        'total': total,
        'graphs':
        [utils.serializer(graph, summary=True) for graph in graphs_list]
    }