views.py 2.3 KB

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