Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a wrapper to perform easy authentication #24

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,11 @@ The `refresh_callback` is a fuction that takes a token dict and saves it somewhe
{'token_type': 'bearer', 'refresh_token': <refresh>, 'access_token': <token>, 'expires_in': 86400, 'expires_at': 1546485086.3277025}
```

Getting the access token and the refresh token in one go by using the client id and the secret of the app created:
```# make authenticated API calls
auth_wrapper = AuthenticationWrapper(client_id, client_secret)
auth_wrapper.browser_authorize()
acc_t = auth_wrapper.oura_client.session.token['access_token']
ref_t = auth_wrapper.oura_client.session.token['refresh_token']
```
Live your life.
3 changes: 2 additions & 1 deletion oura/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@
It's a description for __init__.py, innit.

"""
from .client import OuraClient, OuraOAuth2Client
from .client import OuraClient, OuraOAuth2Client
from .authentication_wrapper import AuthenticationWrapper
75 changes: 75 additions & 0 deletions oura/authentication_wrapper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import sys
import cherrypy
import threading
import traceback
import webbrowser
from urllib.parse import urlparse

from oura import OuraOAuth2Client

from oauthlib.oauth2 import MissingTokenError, MismatchingStateError

"""
wrapper class to return the access token and the refresh token upon authenticating the
user to access data
"""


class AuthenticationWrapper:

def __init__(self, client_id, client_secret, redirect_uri='http://127.0.0.1:8080/'):
self.success_html = """
<h1>You are now authorized to access the Oura API!</h1>
<br/><h3>You can close this window</h3>"""
self.failure_html = """<h1>ERROR: %s</h1><br/><h3>You can close this window</h3>%s"""

self.oura_client = OuraOAuth2Client(client_id, client_secret)
self.redirect_uri = redirect_uri

def browser_authorize(self):
"""
Open a browser to the authorization url and spool up a CherryPy
server to accept the response
"""
url, _ = self.oura_client.authorize_endpoint()
# Open the web browser in a new thread for command-line browser support
threading.Timer(1, webbrowser.open, args=(url,)).start()

# Same with redirect_uri hostname and port.
urlparams = urlparse(self.redirect_uri)
cherrypy.config.update({'server.socket_host': urlparams.hostname,
'server.socket_port': urlparams.port})

cherrypy.quickstart(self)

@cherrypy.expose
def index(self, state, code=None, error=None):
"""
Receive a Oura response containing a verification code. Use the code to fetch the access_token.
"""
error = None
if code:
try:
self.oura_client.fetch_access_token(code)
except MissingTokenError:
error = self._fmt_failure(
'Missing access token parameter.</br>Please check that '
'you are using the correct client_secret')
except MismatchingStateError:
error = self._fmt_failure('CSRF Warning! Mismatching state')
else:
error = self._fmt_failure('Unknown error while authenticating')

# Use a thread to shutdown cherrypy so we can return HTML first
self._shutdown_cherrypy()
return error if error else self.success_html

def _fmt_failure(self, message):
tb = traceback.format_tb(sys.exc_info()[2])
tb_html = '<pre>%s</pre>' % ('\n'.join(tb)) if tb else ''
return self.failure_html % (message, tb_html)

def _shutdown_cherrypy(self):
""" Shutdown cherrypy in one second, if it's running """
if cherrypy.engine.state == cherrypy.engine.states.STARTED:
threading.Timer(1, cherrypy.engine.exit).start()
14 changes: 14 additions & 0 deletions samples/sample_auth_wrapper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from oura import AuthenticationWrapper

"""
reference: https://cloud.ouraring.com/docs/
"""

client_id='client id of the oura application'
client_secret='client secret of the oura application'

auth_wrapper = AuthenticationWrapper(client_id, client_secret)
auth_wrapper.browser_authorize()

acc_t = auth_wrapper.oura_client.session.token['access_token']
ref_t = auth_wrapper.oura_client.session.token['refresh_token']
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

REQUIRED = [
'requests-oauthlib'
'cherrypy'
]

EXTRAS = {
Expand Down