Graphs and tables for your Spotify account.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.3 KiB

  1. import string
  2. import random
  3. import requests
  4. import secrets
  5. from .models import User
  6. from .forms import HistoryUploadForm
  7. def get_user_context(user_obj):
  8. """Get context for rendering with User's ID and secret.
  9. :user_obj: User object to make context for.
  10. :returns: context to pass back to HTML file.
  11. """
  12. return { 'user_id': user_obj.id, 'user_secret': user_obj.secret, }
  13. # generate_random_string {{{ #
  14. def generate_random_string(length):
  15. """Generates a random string of a certain length
  16. Args:
  17. length: the desired length of the randomized string
  18. Returns:
  19. A random string
  20. """
  21. all_chars = string.ascii_letters + string.digits
  22. rand_str = "".join(random.choice(all_chars) for _ in range(length))
  23. return rand_str
  24. # }}} generate_random_string #
  25. # create_user {{{ #
  26. def create_user(refresh_token, access_token, access_expires_in):
  27. """Create a User object based on information returned from Step 2 (callback
  28. function) of auth flow.
  29. :refresh_token: Used to renew access tokens.
  30. :access_token: Used in Spotify API calls.
  31. :access_expires_in: How long the access token last in seconds.
  32. :returns: The newly created User object.
  33. """
  34. profile_response = requests.get('https://api.spotify.com/v1/me',
  35. headers={'Authorization': "Bearer " + access_token}).json()
  36. user_id = profile_response['id']
  37. try:
  38. user_obj = User.objects.get(id=user_id)
  39. except User.DoesNotExist:
  40. # Python docs recommends 32 bytes of randomness against brute
  41. # force attacks
  42. user_obj = User.objects.create(
  43. id=user_id,
  44. secret=secrets.token_urlsafe(32),
  45. refresh_token=refresh_token,
  46. access_token=access_token,
  47. access_expires_in=access_expires_in,
  48. )
  49. return user_obj
  50. # }}} create_user #
  51. def get_scan_context(request):
  52. """Get context for rendering scan page.
  53. :request:
  54. :returns: Context with upload form and user info.
  55. """
  56. context = { 'user_id': request.session['user_id'],
  57. 'user_secret': request.session['user_secret'], }
  58. # set hidden user field to current user
  59. context['form'] = HistoryUploadForm(initial=
  60. { 'user': User.objects.get(id=request.session['user_id']) })
  61. return context