Created
November 2, 2014 14:41
-
-
Save johnwesonga/f76e93bccf5296351a81 to your computer and use it in GitHub Desktop.
Google OAuth2 using Tornado Web Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# encoding: utf-8 | |
""" | |
server.py | |
Created by John Wesonga on 2011-12-12. | |
Copyright (c) 2011 __MyCompanyName__. All rights reserved. | |
""" | |
import tornado.auth | |
from tornado import httpclient | |
import tornado.escape | |
import tornado.httputil | |
import tornado.ioloop | |
import tornado.web | |
import tornado.httpserver | |
import uimodules | |
# import oauth2 | |
import urllib | |
import logging | |
import os | |
import settings | |
from tornado.options import define, options | |
define("port", default=8888, help="run on the given port", type=int) | |
class Application(tornado.web.Application): | |
def __init__(self): | |
handlers = [ | |
(r"/", MainHandler), | |
(r"/auth/login", AuthHandler), | |
(r"/auth/logout", LogoutHandler), | |
(r"/profile", ProfileHandler), | |
] | |
settings = {"static_path": os.path.join(os.path.dirname(__file__), "static"), | |
"cookie_secret": "32oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o", | |
"login_url": "/auth/login", | |
"google_permissions": "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/calendar", | |
"debug": True, | |
"template_path": "templates/", | |
"xsrf_cookies": True, | |
"ui_modules": uimodules, | |
} | |
tornado.web.Application.__init__(self, handlers, **settings) | |
class BaseHandler(tornado.web.RequestHandler): | |
def get_current_user(self): | |
user_json = self.get_secure_cookie("user") | |
if not user_json: return None | |
return tornado.escape.json_decode(user_json) | |
class MainHandler(BaseHandler): | |
def get(self): | |
self.render("index.html") | |
class ProfileHandler(BaseHandler): | |
@tornado.web.authenticated | |
def get(self): | |
http_client = httpclient.HTTPClient() | |
try: | |
response = http_client.fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + | |
self.current_user["access_token"]) | |
logging.info(response.body) | |
profile_info = response.body | |
except httpclient.HTTPError as e: | |
logging.error(e) | |
self.render('profile.html', | |
profile=tornado.escape.json_decode(profile_info)) | |
http_client.close() | |
class AuthHandler(BaseHandler, tornado.auth.GoogleOAuth2Mixin): | |
@tornado.gen.coroutine | |
def get(self): | |
if self.get_argument('code', False): | |
user = yield self.get_authenticated_user(redirect_uri='http://localhost:8888/auth/login', | |
code=self.get_argument('code'), | |
callback = self._on_auth) | |
else: | |
yield self.authorize_redirect( | |
redirect_uri='http://localhost:8888/auth/login', | |
client_id=settings.config['google_oauth']['key'], | |
scope=['profile', 'email'], | |
response_type='code', | |
extra_params={'approval_prompt': 'auto'}, | |
) | |
def _on_auth(self, user_info): | |
self.set_secure_cookie("user", tornado.escape.json_encode(user_info)) | |
self.redirect('/profile') | |
class LogoutHandler(BaseHandler): | |
def get(self): | |
logging.info("cookie " + self.get_secure_cookie("user")) | |
self.clear_cookie("user") | |
self.redirect("/") | |
def main(): | |
tornado.options.parse_command_line() | |
http_server = tornado.httpserver.HTTPServer(Application()) | |
http_server.listen(options.port) | |
tornado.ioloop.IOLoop.instance().start() | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment