class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): user_json = self.get_secure_cookie("authdemo_user") if not user_json: return None return tornado.escape.json_decode(user_json) class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): @tornado.gen.coroutine def get(self): if self.get_argument('code', False): user = yield self.get_authenticated_user( redirect_uri='GOOGLE_CALLBACK', code=self.get_argument('code')) # Save the user with e.g. set_secure_cookie print user # get user info http=tornado.httpclient.AsyncHTTPClient() auth_string = "%s %s" % (user['token_type'], user['access_token']) response = yield http.fetch('https://www.googleapis.com/userinfo/v2/me', headers={"Authorization": auth_string}) user = json.loads(response.body) email = user['email'] if email.endswith('@YOURDOMAIN.COM'): user_json = json.dumps(dict(email=email)) self.set_secure_cookie("authdemo_user", user_json) self.redirect('/') else: yield self.authorize_redirect( redirect_uri='GOOGLE_CALLBACK', client_id=self.settings['google_oauth']['key'], scope=['profile', 'email'], response_type='code', extra_params={'approval_prompt': 'auto'}) class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), (r"/auth/google", GoogleOAuth2LoginHandler), ] settings = dict( debug=True, template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), cookie_secret='modify_this', autoescape=None, login_url = r'/auth/google', google_oauth = {'key': 'GOOGKE_KEY', 'secret': 'GOOGKE_SECRET'} ) tornado.web.Application.__init__(self, handlers, **settings)