Browse Source

Move non-request functions in login/views to utils

master
Kevin Mok 6 years ago
parent
commit
77141849ac
  1. 1
      graphs/templates/graphs/user_history.html
  2. 8
      graphs/views.py
  3. 2
      login/templates/login/index.html
  4. 59
      login/utils.py
  5. 57
      login/views.py

1
graphs/templates/graphs/user_history.html

@ -10,6 +10,7 @@
</head> </head>
<body> <body>
<h1>{{ user_id }}'s Listening History</h1> <h1>{{ user_id }}'s Listening History</h1>
<a class="btn btn-primary disabled" href="" role="button">Export CSV</a>
{% render_table user_history_table %} {% render_table user_history_table %}
</body> </body>
</html> </html>

8
graphs/views.py

@ -12,7 +12,7 @@ from datetime import datetime
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
from .utils import * from .utils import *
from django_tables2 import RequestConfig
from django_tables2 import RequestConfig, SingleTableView
from api.models import History from api.models import History
# }}} imports # # }}} imports #
@ -61,3 +61,9 @@ def display_history_table(request, user_secret):
return render(request, "graphs/user_history.html", context) return render(request, "graphs/user_history.html", context)
class HistoryList(SingleTableView):
"""Create table with list of song history."""
model = History
table_class = HistoryTable
# table_data =

2
login/templates/login/index.html

@ -20,7 +20,7 @@
<div class="container"> <div class="container">
<div id="login"> <div id="login">
<h1>spotify-lib-vis</h1> <h1>spotify-lib-vis</h1>
<a href="{% url 'login:spotify_login' %}" class="btn btn-primary">Login</a>
<a href="{% url 'login:spotify_login' %}" class="btn btn-primary" role="button">Login</a>
<a href="{% url 'login:admin_graphs' %}" class="btn btn-primary">Admin Graphs</a> <a href="{% url 'login:admin_graphs' %}" class="btn btn-primary">Admin Graphs</a>
</div> </div>
</div> </div>

59
login/utils.py

@ -1,3 +1,7 @@
import string
import random
import requests
from .models import User from .models import User
def get_user_context(user_obj): def get_user_context(user_obj):
@ -8,3 +12,58 @@ def get_user_context(user_obj):
""" """
return { 'user_id': user_obj.id, 'user_secret': user_obj.secret, } return { 'user_id': user_obj.id, 'user_secret': user_obj.secret, }
# generate_random_string {{{ #
def generate_random_string(length):
"""Generates a random string of a certain length
Args:
length: the desired length of the randomized string
Returns:
A random string
"""
all_chars = string.ascii_letters + string.digits
rand_str = "".join(random.choice(all_chars) for _ in range(length))
return rand_str
# }}} generate_random_string #
# create_user {{{ #
def create_user(refresh_token, access_token, access_expires_in):
"""Create a User object based on information returned from Step 2 (callback
function) of auth flow.
:refresh_token: Used to renew access tokens.
:access_token: Used in Spotify API calls.
:access_expires_in: How long the access token last in seconds.
:returns: The newly created User object.
"""
profile_response = requests.get('https://api.spotify.com/v1/me',
headers={'Authorization': "Bearer " + access_token}).json()
user_id = profile_response['id']
try:
user_obj = User.objects.get(id=user_id)
except User.DoesNotExist:
# Python docs recommends 32 bytes of randomness against brute
# force attacks
user_obj = User.objects.create(
id=user_id,
secret=secrets.token_urlsafe(32),
refresh_token=refresh_token,
access_token=access_token,
access_expires_in=access_expires_in,
)
return user_obj
# }}} create_user #

57
login/views.py

@ -1,13 +1,10 @@
# imports {{{ # # imports {{{ #
import math import math
import random
import requests
import os import os
import urllib import urllib
import secrets import secrets
import pprint import pprint
import string
from datetime import datetime from datetime import datetime
from django.shortcuts import render, redirect from django.shortcuts import render, redirect
@ -21,28 +18,8 @@ TIME_FORMAT = '%Y-%m-%d-%H-%M-%S'
TRACKS_TO_QUERY = 200 TRACKS_TO_QUERY = 200
AUTH_SCOPE = ['user-library-read', 'user-read-recently-played',] AUTH_SCOPE = ['user-library-read', 'user-read-recently-played',]
# generate_random_string {{{ #
def generate_random_string(length):
"""Generates a random string of a certain length
Args:
length: the desired length of the randomized string
Returns:
A random string
"""
all_chars = string.ascii_letters + string.digits
rand_str = "".join(random.choice(all_chars) for _ in range(length))
return rand_str
# }}} generate_random_string #
# index {{{ # # index {{{ #
# Create your views here.
def index(request): def index(request):
return render(request, 'login/index.html') return render(request, 'login/index.html')
@ -73,6 +50,8 @@ def spotify_login(request):
# }}} spotify_login # # }}} spotify_login #
# callback {{{ #
def callback(request): def callback(request):
""" Step 2 in authorization flow: Have your application request refresh and """ Step 2 in authorization flow: Have your application request refresh and
access tokens; Spotify returns access and refresh tokens. access tokens; Spotify returns access and refresh tokens.
@ -97,38 +76,8 @@ def callback(request):
token_response['expires_in']) token_response['expires_in'])
return render(request, 'login/scan.html', get_user_context(user_obj)) return render(request, 'login/scan.html', get_user_context(user_obj))
# return redirect('user/' + user_obj.secret)
def create_user(refresh_token, access_token, access_expires_in):
"""Create a User object based on information returned from Step 2 (callback
function) of auth flow.
:refresh_token: Used to renew access tokens.
:access_token: Used in Spotify API calls.
:access_expires_in: How long the access token last in seconds.
:returns: The newly created User object.
"""
profile_response = requests.get('https://api.spotify.com/v1/me',
headers={'Authorization': "Bearer " + access_token}).json()
user_id = profile_response['id']
try:
user_obj = User.objects.get(id=user_id)
except User.DoesNotExist:
# Python docs recommends 32 bytes of randomness against brute
# force attacks
user_obj = User.objects.create(
id=user_id,
secret=secrets.token_urlsafe(32),
refresh_token=refresh_token,
access_token=access_token,
access_expires_in=access_expires_in,
)
return user_obj
# }}} callback #
# admin_graphs {{{ # # admin_graphs {{{ #

Loading…
Cancel
Save