Skip to content

Commit 8cc4460

Browse files
committed
Merge pull request #20 from moogar0880/pin-auth
Adds Trakt PIN Auth
2 parents ca471d1 + 7ca63cd commit 8cc4460

4 files changed

Lines changed: 131 additions & 20 deletions

File tree

HISTORY.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
Release History
22
^^^^^^^^^^^^^^^
3+
2.1.0 (2015-07-19)
4+
++++++++++++++++++
5+
6+
* Add Trakt PIN Authentication (#15)
7+
8+
2.0.3 (2015-07-12)
9+
++++++++++++++++++
10+
11+
* Fix BASE_URL to point at correct v2 API (#19)
12+
313
2.0.2 (2015-04-18)
414
++++++++++++++++++
515

docs/getstarted.rst

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,40 @@ key you can interactively run PyTrakt's `init` function like detailed below:
1010
Example Usage
1111
^^^^^^^^^^^^^
1212
The simplest way to generate an API key is to let `trakt.init` walk you through
13-
the process of generating one from scratch, like so
13+
the process of generating one from scratch. Currently PyTrakt supports both OAuth
14+
and PIN auth methods (the default is PIN).
15+
16+
PIN Auth
17+
^^^^^^^^
18+
You can authenticate to trakt via PIN Auth like so,
19+
20+
::
21+
22+
>>> from trakt import init
23+
>>> init()
24+
If you do not have a Trakt.tv PIN, please visit the following url and log in to generate one.
25+
https://trakt.tv/pin/1334
26+
Please enter your PIN:
27+
>>> # Once you've pasted your PIN, you'll be completely authenticated and
28+
>>> # ready to use PyTrakt
29+
30+
If you already have a Trakt PIN generated, you can provide it to the `init` function
31+
32+
::
33+
34+
>>> from trakt import init
35+
>>> init('MY_PIN')
36+
37+
And you're all set
38+
39+
OAuth Auth
40+
^^^^^^^^^^
41+
You can also initialize using OAuth authentication like so,
42+
1443
::
1544

1645
>>> from trakt import init
46+
>>> trakt.AUTH_METHOD = trakt.OAUTH_AUTH # Set the auth method to OAuth
1747
>>> init('myusername')
1848
If you do not have a client ID and secret. Please visit the following url to create them.
1949
http://trakt.tv/oauth/applications

trakt/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@
44
except ImportError:
55
pass
66

7-
version_info = (2, 0, 3)
7+
version_info = (2, 1, 0)
88
__author__ = 'Jon Nappi'
99
__version__ = '.'.join([str(i) for i in version_info])

trakt/core.py

Lines changed: 89 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,31 +38,97 @@
3838
#: Your personal Trakt.tv API Key
3939
api_key = None
4040

41+
#: Flag used to enable Trakt PIN authentication
42+
PIN_AUTH = 'PIN'
4143

42-
def init(username, client_id=None, client_secret=None, store=False):
44+
#: Flag used to enable Trakt OAuth authentication
45+
OAUTH_AUTH = 'OAUTH'
46+
47+
#: The currently enabled authentication method. Default is ``PIN_AUTH``
48+
AUTH_METHOD = PIN_AUTH
49+
50+
#: PyTrakt PIN url for PIN Authentication
51+
PIN_URL = 'https://trakt.tv/pin/1334'
52+
53+
54+
def _store(**kwargs):
55+
"""Helper function used to store Trakt configurations at ``CONFIG_PATH``
56+
57+
:param kwargs: Keyword args to store at ``CONFIG_PATH``
58+
"""
59+
with open(CONFIG_PATH, 'w') as config_file:
60+
json.dump(kwargs, config_file)
61+
62+
63+
def _get_client_info():
64+
"""Helper function to poll the user for Client ID and Client Secret
65+
strings
66+
67+
:return: A 2-tuple of client_id, client_secret
68+
"""
69+
print('If you do not have a client ID and secret. Please visit the '
70+
'following url to create them.')
71+
print('http://trakt.tv/oauth/applications')
72+
client_id = input('Please enter your client id: ')
73+
client_secret = input('Please enter your client secret: ')
74+
return client_id, client_secret
75+
76+
77+
def pin_auth(pin=None, client_id=None, client_secret=None, store=False):
78+
"""Generate an access_token from a Trakt API PIN code.
79+
80+
:param pin: Optional Trakt API PIN code. If one is not specified, you will
81+
be prompted to go generate one
82+
:param store: Boolean flag used to determine if your trakt api auth data
83+
should be stored locally on the system. Default is :const:`False` for
84+
the security conscious
85+
:return: Your OAuth access token
86+
"""
87+
global api_key, HEADERS, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI
88+
CLIENT_ID, CLIENT_SECRET = client_id, client_secret
89+
if client_id is None and client_secret is None:
90+
CLIENT_ID, CLIENT_SECRET = _get_client_info()
91+
if pin is None:
92+
print('If you do not have a Trakt.tv PIN, please visit the following '
93+
'url and log in to generate one.')
94+
print(PIN_URL)
95+
pin = input('Please enter your PIN: ')
96+
args = {'code': pin,
97+
'redirect_uri': REDIRECT_URI,
98+
'grant_type': 'authorization_code',
99+
'client_id': CLIENT_ID,
100+
'client_secret': CLIENT_SECRET}
101+
102+
response = requests.post(''.join([BASE_URL, '/oauth/token']), data=args)
103+
api_key = response.json().get('access_token', None)
104+
HEADERS['trakt-api-key'] = CLIENT_ID
105+
106+
if store:
107+
_store(CLIENT_ID=CLIENT_ID, CLIENT_SECRET=CLIENT_SECRET,
108+
api_key=api_key)
109+
return api_key
110+
111+
112+
def oauth_auth(username, client_id=None, client_secret=None, store=False):
43113
"""Generate an access_token to allow your application to authenticate via
44114
OAuth
45115
46116
:param username: Your trakt.tv username
47117
:param client_id: Your Trakt OAuth Application's Client ID
48118
:param client_secret: Your Trakt OAuth Application's Client Secret
49119
:param store: Boolean flag used to determine if your trakt api auth data
50-
should be stored locally on the system. Default is :const:`False` for the
51-
security conscious
120+
should be stored locally on the system. Default is :const:`False` for
121+
the security conscious
52122
:return: Your OAuth access token
53123
"""
54-
global CLIENT_ID, CLIENT_SECRET, api_key
124+
global BASE_URL, CLIENT_ID, CLIENT_SECRET, api_key
55125
if client_id is None and client_secret is None:
56-
print('If you do not have a client ID and secret. Please visit the '
57-
'following url to create them.')
58-
print('http://trakt.tv/oauth/applications')
59-
client_id = input('Please enter your client id: ')
60-
client_secret = input('Please enter your client secret: ')
126+
client_id, client_secret = _get_client_info()
61127
CLIENT_ID, CLIENT_SECRET = client_id, client_secret
62128
HEADERS['trakt-api-key'] = CLIENT_ID
63129

64-
authorization_base_url = 'https://api-v2launch.trakt.tv/oauth/authorize'
65-
token_url = 'https://api-v2launch.trakt.tv/oauth/token'
130+
authorization_base_url = ''.join([BASE_URL, '/oauth/authorize'])
131+
token_url = ''.join([BASE_URL, '/oauth/token'])
66132

67133
# OAuth endpoints given in the API documentation
68134
oauth = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI, state=None)
@@ -80,14 +146,19 @@ def init(username, client_id=None, client_secret=None, store=False):
80146
api_key = oauth.token['access_token']
81147

82148
if store:
83-
data = {'CLIENT_ID': CLIENT_ID, 'CLIENT_SECRET': CLIENT_SECRET,
84-
'api_key': api_key}
85-
with open(CONFIG_PATH, 'w') as config_file:
86-
json.dump(data, config_file)
87-
149+
_store(CLIENT_ID=CLIENT_ID, CLIENT_SECRET=CLIENT_SECRET,
150+
api_key=api_key)
88151
return oauth.token['access_token']
89152

90153

154+
def init(*args, **kwargs):
155+
"""Run the auth function specified by *AUTH_METHOD*"""
156+
if AUTH_METHOD == PIN_AUTH:
157+
return pin_auth(*args, **kwargs)
158+
else:
159+
return oauth_auth(*args, **kwargs)
160+
161+
91162
Airs = namedtuple('Airs', ['day', 'time', 'timezone'])
92163
Alias = namedtuple('Alias', ['title', 'country'])
93164
Genre = namedtuple('Genre', ['name', 'slug'])
@@ -112,8 +183,8 @@ def inner(*args, **kwargs):
112183
with open(CONFIG_PATH) as config_file:
113184
config_data = json.load(config_file)
114185

115-
CLIENT_ID = config_data['CLIENT_ID']
116-
CLIENT_SECRET = config_data['CLIENT_SECRET']
186+
CLIENT_ID = config_data.get('CLIENT_ID', None)
187+
CLIENT_SECRET = config_data.get('CLIENT_SECRET', None)
117188
api_key = config_data['api_key']
118189

119190
HEADERS['trakt-api-key'] = CLIENT_ID

0 commit comments

Comments
 (0)