Example #1
0
 def test_getProfileByUsername(self):
     request = HttpRequest()
     request.user = User.objects.create_user('testuser',
                                             '*****@*****.**',
                                             'testuserpassword')
     util.getProfile(request, False)
     self.assertEqual(str(util.getProfileByUsername('testuser')),
                      'Profile for testuser')
     self.assertEqual(util.getProfileByUsername('nonexistentuser'), None)
Example #2
0
def renderMyGraphView(request, username, graphName):
    profile = getProfileByUsername(username)
    if not profile:
        return errorPage("No such user '%s'" % username)
    try:
        graph = profile.mygraph_set.get(name=graphName)
    except ObjectDoesNotExist:
        return errorPage("User %s doesn't have a MyGraph named '%s'" %
                         (username, graphName))

    request_params = dict(request.REQUEST.items())
    if request_params:
        url_parts = urlsplit(graph.url)
        query_string = url_parts[3]
        if query_string:
            url_params = parse_qs(query_string)
            for param, value in url_params.items():
                if isinstance(value, list):
                    url_params[param] = value[0]
            url_params.update(request_params)
            query_string = urlencode(url_params)
        url = urlunsplit(url_parts[:3] + (query_string, ) + url_parts[4:])
    else:
        url = graph.url
    return HttpResponseRedirect(url)
Example #3
0
def renderMyGraphView(request,username,graphName):
  profile = getProfileByUsername(username)
  if not profile:
    return errorPage("No such user '%s'" % username)
  try:
    graph = profile.mygraph_set.get(name=graphName)
  except ObjectDoesNotExist:
    return errorPage("User %s doesn't have a MyGraph named '%s'" % (username,graphName))

  request_params = dict(request.REQUEST.items())
  if request_params:
    url_parts = urlsplit(graph.url)
    query_string = url_parts[3]
    if query_string:
      url_params = parse_qs(query_string)
      # Remove lists so that we can do an update() on the dict
      for param, value in url_params.items():
        if isinstance(value, list) and param != 'target':
          url_params[param] = value[-1]
      url_params.update(request_params)
      # Handle 'target' being a list - we want duplicate &target params out of it
      url_param_pairs = []
      for key,val in url_params.items():
        if isinstance(val, list):
          for v in val:
            url_param_pairs.append( (key,v) )
        else:
          url_param_pairs.append( (key,val) )

      query_string = urlencode(url_param_pairs)
    url = urlunsplit(url_parts[:3] + (query_string,) + url_parts[4:])
  else:
    url = graph.url
  return HttpResponseRedirect(url)
Example #4
0
def renderMyGraphView(request, username, graphName):
    profile = getProfileByUsername(username)
    if not profile:
        return errorPage("No such user '%s'" % username)
    try:
        graph = profile.mygraph_set.get(name=graphName)
    except ObjectDoesNotExist:
        return errorPage("User %s doesn't have a MyGraph named '%s'" %
                         (username, graphName))

    request_params = dict(request.REQUEST.items())
    if request_params:
        url_parts = urlsplit(graph.url)
        query_string = url_parts[3]
        if query_string:
            url_params = parse_qs(query_string)
            # Remove lists so that we can do an update() on the dict
            for param, value in url_params.items():
                if isinstance(value, list) and param != 'target':
                    url_params[param] = value[-1]
            url_params.update(request_params)
            # Handle 'target' being a list - we want duplicate &target params out of it
            url_param_pairs = []
            for key, val in url_params.items():
                if isinstance(val, list):
                    for v in val:
                        url_param_pairs.append((key, v))
                else:
                    url_param_pairs.append((key, val))

            query_string = urlencode(url_param_pairs)
        url = urlunsplit(url_parts[:3] + (query_string, ) + url_parts[4:])
    else:
        url = graph.url
    return HttpResponseRedirect(url)
Example #5
0
def userGraphLookup(request):
  "View for User Graphs navigation"
  username = request.GET['path']
  nodes = []

  branchNode = {
    'allowChildren' : 1,
    'expandable' : 1,
    'leaf' : 0,
  }
  leafNode = {
    'allowChildren' : 0,
    'expandable' : 0,
    'leaf' : 1,
  }

  try:

    tenant = get_tenant(request)

    if not username:
      profiles = Profile.objects.exclude(user__username='******')

      for profile in profiles:
        if profile.mygraph_set.all().filter(tenant=tenant).count():
          node = {
            'text' : str(profile.user.username),
            'id' : str(profile.user.username)
          }

          node.update(branchNode)
          nodes.append(node)

    else:
      profile = getProfileByUsername(username)
      assert profile, "No profile for username '%s'" % username

      for graph in profile.mygraph_set.all().filter(tenant=tenant).order_by('name'):
        node = {
          'text' : str(graph.name),
          'id' : str(graph.name),
          'graphUrl' : str(graph.url)
        }
        node.update(leafNode)
        nodes.append(node)

  except:
    log.exception("browser.views.userLookup(): could not complete request for %s" % username)

  if not nodes:
    no_graphs = { 'text' : "No saved graphs", 'id' : 'no-click' }
    no_graphs.update(leafNode)
    nodes.append(no_graphs)

  return json_response(nodes, request)
Example #6
0
def userGraphLookup(request):
    "View for User Graphs navigation"
    username = request.GET['path']
    nodes = []

    branchNode = {
        'allowChildren': 1,
        'expandable': 1,
        'leaf': 0,
    }
    leafNode = {
        'allowChildren': 0,
        'expandable': 0,
        'leaf': 1,
    }

    try:

        if not username:
            profiles = Profile.objects.exclude(user__username='******')

            for profile in profiles:
                if profile.mygraph_set.count():
                    node = {
                        'text': str(profile.user.username),
                        'id': str(profile.user.username)
                    }

                    node.update(branchNode)
                    nodes.append(node)

        else:
            profile = getProfileByUsername(username)
            assert profile, "No profile for username '%s'" % username

            for graph in profile.mygraph_set.all().order_by('name'):
                node = {
                    'text': str(graph.name),
                    'id': str(graph.name),
                    'graphUrl': str(graph.url)
                }
                node.update(leafNode)
                nodes.append(node)

    except:
        log.exception(
            "browser.views.userLookup(): could not complete request for %s" %
            username)

    if not nodes:
        no_graphs = {'text': "No saved graphs", 'id': 'no-click'}
        no_graphs.update(leafNode)
        nodes.append(no_graphs)

    return json_response(nodes, request)
Example #7
0
def renderMyGraphView(request,username,graphName):
  profile = getProfileByUsername(username)
  assert profile, "No such user '%s'" % username
  try:
    graph = profile.mygraph_set.get(name=graphName)
  except ObjectDoesNotExist:
    assert False, "User %s doesn't have a MyGraph named '%s'" % (username,graphName)
  (proto,host,path,query,frag) = urlsplit( graph.url )
  if query: path += '?' + query
  conn = HTTPConnectionWithTimeout( host )
  conn.request('GET', path)
  resp = conn.getresponse()
  assert resp.status == 200, "Failed to retrieve image from URL %s" % graph.url
  imageData = resp.read()
  return buildResponse(imageData)
Example #8
0
def renderMyGraphView(request, username, graphName):
    profile = getProfileByUsername(username)
    assert profile, "No such user '%s'" % username
    try:
        graph = profile.mygraph_set.get(name=graphName)
    except ObjectDoesNotExist:
        assert False, "User %s doesn't have a MyGraph named '%s'" % (username,
                                                                     graphName)
    (proto, host, path, query, frag) = urlsplit(graph.url)
    if query: path += '?' + query
    conn = HTTPConnectionWithTimeout(host)
    conn.request('GET', path)
    resp = conn.getresponse()
    assert resp.status == 200, "Failed to retrieve image from URL %s" % graph.url
    imageData = resp.read()
    return buildResponse(imageData)
Example #9
0
def _gload(request,user=None,graphName=None):
  if not user:
    profile = getProfile(request,allowDefault=False)
    if not profile: return stderr("You are not logged in so you must specify a username")
  else:
    try:
      profile = getProfileByUsername(user)
    except ObjectDoesNotExist:
      return stderr("User does not exist")
  try:
    myGraph = profile.mygraph_set.get(name=graphName)
  except ObjectDoesNotExist:
    return stderr("Graph does not exist")
  out = _create(request,myGraph.name)
  out += "changeImage(%s_win,'%s');\n" % (myGraph.name,myGraph.url)
  return out
Example #10
0
def _gload(request,user=None,graphName=None):
  if not user:
    profile = getProfile(request,allowDefault=False)
    if not profile: return stderr("You are not logged in so you must specify a username")
  else:
    try:
      profile = getProfileByUsername(user)
    except ObjectDoesNotExist:
      return stderr("User does not exist")
  try:
    myGraph = profile.mygraph_set.get(name=graphName)
  except ObjectDoesNotExist:
    return stderr("Graph does not exist")
  out = _create(request,myGraph.name)
  out += "changeImage(%s_win,'%s');\n" % (myGraph.name.replace('.', '_'), myGraph.url)
  return out
Example #11
0
def _graphs(request,user=None):
  if not user:
    profile = getProfile(request,allowDefault=False)
    if not profile: return stderr("You are not logged in so you must specify a username")
  else:
    try:
      profile = getProfileByUsername(user)
    except ObjectDoesNotExist:
      return stderr("User does not exist")
  out = ""
  if user:
    prefix = "~%s/" % user
  else:
    prefix = ""
  for graph in profile.mygraph_set.all():
    out += stdout(prefix + graph.name)
  return out
Example #12
0
def _graphs(request,user=None):
  if not user:
    profile = getProfile(request,allowDefault=False)
    if not profile: return stderr("You are not logged in so you must specify a username")
  else:
    try:
      profile = getProfileByUsername(user)
    except ObjectDoesNotExist:
      return stderr("User does not exist")
  out = ""
  if user:
    prefix = "~%s/" % user
  else:
    prefix = ""
  for graph in profile.mygraph_set.all():
    out += stdout(prefix + graph.name)
  return out
Example #13
0
def userGraphLookup(request):
    "View for User Graphs navigation"
    username = request.GET["path"]
    nodes = []

    branchNode = {"allowChildren": 1, "expandable": 1, "leaf": 0}
    leafNode = {"allowChildren": 0, "expandable": 0, "leaf": 1}

    try:

        if not username:
            profiles = Profile.objects.exclude(user__username="******")

            for profile in profiles:
                if profile.mygraph_set.count():
                    node = {"text": str(profile.user.username), "id": str(profile.user.username)}

                    node.update(branchNode)
                    nodes.append(node)

        else:
            profile = getProfileByUsername(username)
            assert profile, "No profile for username '%s'" % username

            for graph in profile.mygraph_set.all().order_by("name"):
                node = {"text": str(graph.name), "id": str(graph.name), "graphUrl": str(graph.url)}
                node.update(leafNode)
                nodes.append(node)

    except:
        log.exception("browser.views.userLookup(): could not complete request for %s" % username)

    if not nodes:
        no_graphs = {"text": "No saved graphs", "id": "no-click"}
        no_graphs.update(leafNode)
        nodes.append(no_graphs)

    return json_response(nodes, request)
Example #14
0
def renderMyGraphView(request,username,graphName):
  profile = getProfileByUsername(username)
  if not profile:
    return errorPage("No such user '%s'" % username)
  try:
    graph = profile.mygraph_set.get(name=graphName)
  except ObjectDoesNotExist:
    return errorPage("User %s doesn't have a MyGraph named '%s'" % (username,graphName))

  request_params = dict(request.REQUEST.items())
  if request_params:
    url_parts = urlsplit(graph.url)
    query_string = url_parts[3]
    if query_string:
      url_params = parse_qs(query_string)
      for param, value in url_params.items():
        if isinstance(value, list):
          url_params[param] = value[0]
      url_params.update(request_params)
      query_string = urlencode(url_params)
    url = urlunsplit(url_parts[:3] + (query_string,) + url_parts[4:])
  else:
    url = graph.url
  return HttpResponseRedirect(url)
Example #15
0
 def test_getProfileByUsername(self):
     request = HttpRequest()
     request.user = User.objects.create_user('testuser', '*****@*****.**', 'testuserpassword')
     util.getProfile(request, False)
     self.assertEqual( str(util.getProfileByUsername('testuser')), 'Profile for testuser' )
     self.assertEqual( util.getProfileByUsername('nonexistentuser'), None )
Example #16
0
def userGraphLookup(request):
    "View for User Graphs navigation"
    user = request.GET.get('user')
    path = request.GET['path']

    if user:
        username = user
        graphPath = path[len(username) + 1:]
    elif '.' in path:
        username, graphPath = path.split('.', 1)
    else:
        username, graphPath = path, None

    nodes = []

    branchNode = {
        'allowChildren': 1,
        'expandable': 1,
        'leaf': 0,
    }
    leafNode = {
        'allowChildren': 0,
        'expandable': 0,
        'leaf': 1,
    }

    try:

        if not username:
            profiles = Profile.objects.exclude(user=defaultUser)

            for profile in profiles:
                if profile.mygraph_set.count():
                    node = {
                        'text': str(profile.user.username),
                        'id': str(profile.user.username)
                    }

                    node.update(branchNode)
                    nodes.append(node)

        else:
            profile = getProfileByUsername(username)
            assert profile, "No profile for username '%s'" % username

            if graphPath:
                prefix = graphPath.rstrip('.') + '.'
            else:
                prefix = ''

            matches = [
                graph for graph in profile.mygraph_set.all().order_by('name')
                if graph.name.startswith(prefix)
            ]
            inserted = set()

            for graph in matches:
                relativePath = graph.name[len(prefix):]
                nodeName = relativePath.split('.')[0]

                if nodeName in inserted:
                    continue
                inserted.add(nodeName)

                if '.' in relativePath:  # branch
                    node = {
                        'text': str(nodeName),
                        'id': str(username + '.' + prefix + nodeName + '.'),
                    }
                    node.update(branchNode)
                else:  # leaf
                    m = md5()
                    m.update(nodeName)

                    node = {
                        'text': str(nodeName),
                        'id': str(username + '.' + prefix + m.hexdigest()),
                        'graphUrl': str(graph.url),
                    }
                    node.update(leafNode)

                nodes.append(node)

    except:
        log.exception(
            "browser.views.userLookup(): could not complete request for %s" %
            username)

    if not nodes:
        no_graphs = {'text': "No saved graphs", 'id': 'no-click'}
        no_graphs.update(leafNode)
        nodes.append(no_graphs)

    return json_response(nodes, request)
Example #17
0
def userGraphLookup(request):
  "View for User Graphs navigation"
  user = request.GET.get('user')
  path = request.GET['path']

  if user:
    username = user
    graphPath = path[len(username)+1:]
  elif '.' in path:
    username, graphPath = path.split('.', 1)
  else:
    username, graphPath = path, None

  nodes = []

  branchNode = {
    'allowChildren' : 1,
    'expandable' : 1,
    'leaf' : 0,
  }
  leafNode = {
    'allowChildren' : 0,
    'expandable' : 0,
    'leaf' : 1,
  }

  try:

    if not username:
      profiles = Profile.objects.exclude(user__username='******')

      for profile in profiles:
        if profile.mygraph_set.count():
          node = {
            'text' : str(profile.user.username),
            'id' : str(profile.user.username)
          }

          node.update(branchNode)
          nodes.append(node)

    else:
      profile = getProfileByUsername(username)
      assert profile, "No profile for username '%s'" % username

      if graphPath:
        prefix = graphPath.rstrip('.') + '.'
      else:
        prefix = ''

      matches = [ graph for graph in profile.mygraph_set.all().order_by('name') if graph.name.startswith(prefix) ]
      inserted = set()

      for graph in matches:
        relativePath = graph.name[ len(prefix): ]
        nodeName = relativePath.split('.')[0]

        if nodeName in inserted:
          continue
        inserted.add(nodeName)

        if '.' in relativePath: # branch
          node = {
            'text' : str(nodeName),
            'id' : str(username + '.' + prefix + nodeName + '.'),
          }
          node.update(branchNode)
        else: # leaf
          m = md5()
          m.update(nodeName)

          node = {
            'text' : str(nodeName ),
            'id' : str(username + '.' + prefix + m.hexdigest()),
            'graphUrl' : str(graph.url),
          }
          node.update(leafNode)

        nodes.append(node)

  except:
    log.exception("browser.views.userLookup(): could not complete request for %s" % username)

  if not nodes:
    no_graphs = { 'text' : "No saved graphs", 'id' : 'no-click' }
    no_graphs.update(leafNode)
    nodes.append(no_graphs)

  return json_response(nodes, request)
Example #18
0
def userGraphLookup(request):
  "View for User Graphs navigation"
  user = request.GET.get('user')
  path = request.GET['path']

  if user:
    username = user
    graphPath = path[len(username)+1:]
  elif '.' in path:
    username, graphPath = path.split('.', 1)
  else:
    username, graphPath = path, None

  nodes = []

  branchNode = {
    'allowChildren' : 1,
    'expandable' : 1,
    'leaf' : 0,
  }
  leafNode = {
    'allowChildren' : 0,
    'expandable' : 0,
    'leaf' : 1,
  }

  try:

    if not username:
      profiles = Profile.objects.exclude(user__username='******').order_by('user__username')

      for profile in profiles:
        if profile.mygraph_set.count():
          node = {
            'text' : str(profile.user.username),
            'id' : str(profile.user.username)
          }

          node.update(branchNode)
          nodes.append(node)

    else:
      profile = getProfileByUsername(username)
      assert profile, "No profile for username '%s'" % username

      if graphPath:
        prefix = graphPath.rstrip('.') + '.'
      else:
        prefix = ''

      matches = [ graph for graph in profile.mygraph_set.all().order_by('name') if graph.name.startswith(prefix) ]
      inserted = set()

      for graph in matches:
        relativePath = graph.name[ len(prefix): ]
        nodeName = relativePath.split('.')[0]

        if nodeName in inserted:
          continue
        inserted.add(nodeName)

        if '.' in relativePath: # branch
          node = {
            'text' : escape(str(nodeName)),
            'id' : str(username + '.' + prefix + nodeName + '.'),
          }
          node.update(branchNode)
        else: # leaf
          m = md5()
          m.update(nodeName)

          # Sanitize target
          urlEscaped = str(graph.url)
          graphUrl = urlparse(urlEscaped)
          graphUrlParams = {}
          graphUrlParams['target'] = []
          for param in parse_qsl(graphUrl.query):
            if param[0] != 'target':
              graphUrlParams[param[0]] = param[1]
            else:
              graphUrlParams[param[0]].append(escape(param[1]))
          urlEscaped = graphUrl._replace(query=urlencode(graphUrlParams, True)).geturl()

          node = {
            'text' : escape(str(nodeName)),
            'id' : str(username + '.' + prefix + m.hexdigest()),
            'graphUrl' : urlEscaped,
          }
          node.update(leafNode)

        nodes.append(node)

  except:
    log.exception("browser.views.userLookup(): could not complete request for %s" % username)

  if not nodes:
    no_graphs = { 'text' : "No saved graphs", 'id' : 'no-click' }
    no_graphs.update(leafNode)
    nodes.append(no_graphs)

  nodes.sort(key=lambda node: node['allowChildren'], reverse = True)

  return json_response(nodes, request)
Example #19
0
def userGraphLookup(request):
    "View for User Graphs navigation"
    user = request.GET.get('user')
    path = request.GET['path']

    if user:
        username = user
        graphPath = path[len(username) + 1:]
    elif '.' in path:
        username, graphPath = path.split('.', 1)
    else:
        username, graphPath = path, None

    nodes = []

    branchNode = {
        'allowChildren': 1,
        'expandable': 1,
        'leaf': 0,
    }
    leafNode = {
        'allowChildren': 0,
        'expandable': 0,
        'leaf': 1,
    }

    try:

        if not username:
            profiles = Profile.objects.exclude(
                user__username='******').order_by('user__username')

            for profile in profiles:
                if profile.mygraph_set.count():
                    node = {
                        'text': str(profile.user.username),
                        'id': str(profile.user.username)
                    }

                    node.update(branchNode)
                    nodes.append(node)

        else:
            profile = getProfileByUsername(username)
            assert profile, "No profile for username '%s'" % username

            if graphPath:
                prefix = graphPath.rstrip('.') + '.'
            else:
                prefix = ''

            matches = [
                graph for graph in profile.mygraph_set.all().order_by('name')
                if graph.name.startswith(prefix)
            ]
            inserted = set()

            for graph in matches:
                relativePath = graph.name[len(prefix):]
                nodeName = relativePath.split('.')[0]

                if nodeName in inserted:
                    continue
                inserted.add(nodeName)

                if '.' in relativePath:  # branch
                    node = {
                        'text': escape(str(nodeName)),
                        'id': str(username + '.' + prefix + nodeName + '.'),
                    }
                    node.update(branchNode)
                else:  # leaf
                    m = md5()
                    m.update(nodeName)

                    # Sanitize target
                    urlEscaped = str(graph.url)
                    graphUrl = urlparse(urlEscaped)
                    graphUrlParams = {}
                    graphUrlParams['target'] = []
                    for param in parse_qsl(graphUrl.query):
                        if param[0] != 'target':
                            graphUrlParams[param[0]] = param[1]
                        else:
                            graphUrlParams[param[0]].append(escape(param[1]))
                    urlEscaped = graphUrl._replace(
                        query=urlencode(graphUrlParams, True)).geturl()

                    node = {
                        'text': escape(str(nodeName)),
                        'id': str(username + '.' + prefix + m.hexdigest()),
                        'graphUrl': urlEscaped,
                    }
                    node.update(leafNode)

                nodes.append(node)

    except:
        log.exception(
            "browser.views.userLookup(): could not complete request for %s" %
            username)

    if not nodes:
        no_graphs = {'text': "No saved graphs", 'id': 'no-click'}
        no_graphs.update(leafNode)
        nodes.append(no_graphs)

    nodes.sort(key=lambda node: node['allowChildren'], reverse=True)

    return json_response(nodes, request)