Skip to content

Commit

Permalink
Automatically refresh authentication token, fixes podio#36.
Browse files Browse the repository at this point in the history
  • Loading branch information
Fredrik Kock committed Jul 22, 2015
1 parent 673fa8c commit d584374
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion pypodio2/transport.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from httplib2 import Http

try:
Expand All @@ -24,6 +25,7 @@ class OAuthToken(object):
"""
def __init__(self, resp):
self.expires_in = resp['expires_in']
self.expires_at = datetime.now() + timedelta(seconds=self.expires_in)
self.access_token = resp['access_token']
self.refresh_token = resp['refresh_token']

Expand All @@ -33,20 +35,39 @@ def to_headers(self):

class OAuthAuthorization(object):
"""Generates headers for Podio OAuth2 Authorization"""
def refresh_token(self):
'''Refresh token'''
body = {
'grant_type': 'refresh_token',
'client_id': self.key,
'client_secret': self.secret,
'refresh_token': self.token.refresh_token,
}
h = Http(disable_ssl_certificate_validation=True)
headers = {'content-type': 'application/x-www-form-urlencoded'}
response, data = h.request(self.domain + self.token_url, "POST",
urlencode(body), headers=headers)
self.token = OAuthToken(_handle_response(response, data))

def __init__(self, login, password, key, secret, domain):
self.key = key
self.secret = secret
self.domain = domain
self.token_url = "/oauth/token"
body = {'grant_type': 'password',
'client_id': key,
'client_secret': secret,
'username': login,
'password': password}
h = Http(disable_ssl_certificate_validation=True)
headers = {'content-type': 'application/x-www-form-urlencoded'}
response, data = h.request(domain + "/oauth/token", "POST",
response, data = h.request(self.domain + self.token_url, "POST",
urlencode(body), headers=headers)
self.token = OAuthToken(_handle_response(response, data))

def __call__(self):
if token.expires_at <= datetime.now():
self.refresh_token()
return self.token.to_headers()


Expand Down

0 comments on commit d584374

Please sign in to comment.