views.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import os
  2. from urllib2 import urlopen
  3. from django.contrib.auth.models import User
  4. from django.http import HttpResponse
  5. from django.shortcuts import render_to_response, get_object_or_404
  6. from django.views.generic.detail import DetailView
  7. from django.conf import settings
  8. from coin.vpn.models import VPNSubscription
  9. class VPNView(DetailView):
  10. def get_object(self):
  11. return get_object_or_404(VPNSubscription, pk=self.args[0],
  12. administrative_subscription__member__user=self.request.user)
  13. class VPNGeneratePasswordView(VPNView):
  14. """This generates a random password, saves it in hashed form, and returns
  15. it to the user in cleartext.
  16. """
  17. def get_context_data(self, **kwargs):
  18. context = super(VPNGeneratePasswordView, self).get_context_data(**kwargs)
  19. # Generate a new random password and save it
  20. password = User.objects.make_random_password()
  21. self.object.password = password
  22. # This will hash the password automatically
  23. self.object.full_clean()
  24. self.object.save()
  25. context['password'] = password
  26. return context
  27. def get_graph(request, vpn_id, period="daily"):
  28. """ This get the graph for the associated vpn_id and time period
  29. """
  30. vpn = get_object_or_404(VPNSubscription, pk=vpn_id,
  31. administrative_subscription__member__user=request.user.id)
  32. time_periods = { 'daily': '-24hours', 'weekly': '-8days', 'monthly': '-32days', 'yearly': '-13months', }
  33. if period not in time_periods:
  34. period = 'daily'
  35. graph_url = os.path.join(settings.GRAPHITE_SERVER,
  36. "render/?width=586&height=308&from=%(period)s&" \
  37. "target=alias%%28scaleToSeconds%%28vpn1.%(login)s.downrxbytes%%2C1%%29%%2C%%20%%22Download%%22%%29&" \
  38. "target=alias%%28scaleToSeconds%%28vpn1.%(login)s.uptxbytes%%2C1%%29%%2C%%20%%22Upload%%22%%29&" \
  39. "title=VPN%%20Usage%%20%(login)s" % \
  40. { 'period': time_periods[period], 'login': vpn.login })
  41. return HttpResponse(urlopen(graph_url), mimetype="image/png")