Python tornado.auth() Examples

The following are 21 code examples of tornado.auth(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado , or try the search function .
Example #1
Source File: facebook.py    From tornado-zh with MIT License 6 votes vote down vote up
def __init__(self):
        handlers = [
            (r"/", MainHandler),
            (r"/auth/login", AuthLoginHandler),
            (r"/auth/logout", AuthLogoutHandler),
        ]
        settings = dict(
            cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
            login_url="/auth/login",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            facebook_api_key=options.facebook_api_key,
            facebook_secret=options.facebook_secret,
            ui_modules={"Post": PostModule},
            debug=True,
            autoescape=None,
        )
        tornado.web.Application.__init__(self, handlers, **settings) 
Example #2
Source File: chatdemo.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        handlers = [
            (r"/", MainHandler),
            (r"/auth/login", AuthLoginHandler),
            (r"/auth/logout", AuthLogoutHandler),
            (r"/a/message/new", MessageNewHandler),
            (r"/a/message/updates", MessageUpdatesHandler),
        ]
        settings = dict(
            cookie_secret="43oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
            login_url="/auth/login",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            autoescape="xhtml_escape",
        )
        tornado.web.Application.__init__(self, handlers, **settings) 
Example #3
Source File: authentication.py    From django-gateone with GNU General Public License v3.0 6 votes vote down vote up
def user_login(self, user):
        """
        This is an override of BaseAuthHandler since anonymous auth is special.
        Generates a unique session ID for this user and saves it in a browser
        cookie.  This is to ensure that anonymous users can't access each
        other's sessions.
        """
        logging.debug("NullAuthHandler.user_login(%s)" % user['upn'])
        # Make a directory to store this user's settings/files/logs/etc
        user_dir = os.path.join(self.settings['user_dir'], user['upn'])
        if not os.path.exists(user_dir):
            logging.info(_("Creating user directory: %s" % user_dir))
            mkdir_p(user_dir)
            os.chmod(user_dir, 0o700)
        session_info = {
            'session': generate_session_id()
        }
        session_info.update(user)
        #print session_info
        self.set_secure_cookie(
            "gateone_user", tornado.escape.json_encode(session_info)) 
Example #4
Source File: authentication.py    From django-gateone with GNU General Public License v3.0 6 votes vote down vote up
def get(self):
        """
        Deletes the 'gateone_user' cookie and handles some other situations for
        backwards compatibility.
        """
        # Get rid of the cookie no matter what (API auth doesn't use cookies)
        user = self.current_user
        self.clear_cookie('gateone_user')
        check = self.get_argument("check", None)
        if check:
            # This lets any origin check if the user has been authenticated
            # (necessary to prevent "not allowed ..." XHR errors)
            self.set_header('Access-Control-Allow-Origin', '*')
            logout = self.get_argument("logout", None)
            if logout:
                self.user_logout(user['upn'])
                return
        logging.debug('APIAuthHandler: user is NOT authenticated')
        self.write('unauthenticated')
        self.finish() 
Example #5
Source File: blog.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def _on_auth(self, user):
        if not user:
            raise tornado.web.HTTPError(500, "Google auth failed")
        author = self.db.get("SELECT * FROM authors WHERE email = %s",
                             user["email"])
        if not author:
            # Auto-create first author
            any_author = self.db.get("SELECT * FROM authors LIMIT 1")
            if not any_author:
                author_id = self.db.execute(
                    "INSERT INTO authors (email,name) VALUES (%s,%s)",
                    user["email"], user["name"])
            else:
                self.redirect("/")
                return
        else:
            author_id = author["id"]
        self.set_secure_cookie("user", str(author_id))
        self.redirect(self.get_argument("next", "/")) 
Example #6
Source File: facebook.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        handlers = [
            (r"/", MainHandler),
            (r"/auth/login", AuthLoginHandler),
            (r"/auth/logout", AuthLogoutHandler),
        ]
        settings = dict(
            cookie_secret="12oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
            login_url="/auth/login",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            facebook_api_key=options.facebook_api_key,
            facebook_secret=options.facebook_secret,
            ui_modules={"Post": PostModule},
            debug=True,
            autoescape=None,
        )
        tornado.web.Application.__init__(self, handlers, **settings) 
Example #7
Source File: tools.py    From mltshp with Mozilla Public License 2.0 5 votes vote down vote up
def _on_auth(self, user):
        if not user:
            raise tornado.web.HTTPError(500, "Twitter auth failed")

        #is there an existing external account?
        current_user = self.get_current_user()
        authenticated_user = User.get("id=%s", current_user['id'])
        existing = Externalservice.by_user(authenticated_user, Externalservice.TWITTER)
        if existing:
            existing.service_id = user['access_token']['user_id']
            existing.service_secret = user['access_token']['secret']
            existing.service_key = user['access_token']['key']
            existing.screen_name = user['access_token']['screen_name']
            existing.save()
        else:
            external_service = Externalservice(
                                    user_id=authenticated_user.id,
                                    service_id=user['access_token']['user_id'],
                                    screen_name=user['access_token']['screen_name'],
                                    type=Externalservice.TWITTER,
                                    service_key=user['access_token']['key'],
                                    service_secret=user['access_token']['secret'])
            external_service.save()
        # if not, insert credentials for this user
        # if there is, update that account
        return self.render("tools/twitter-connected.html") 
Example #8
Source File: oauth.py    From fishroom with GNU General Public License v3.0 5 votes vote down vote up
def _on_access_token(future, response):
        if response.error:
            future.set_exception(tornado.auth.AuthError('GitHub auth error: %s' % str(response)))
            return

        args = tornado.escape.parse_qs_bytes(tornado.escape.native_str(response.body))
        future.set_result(bool(args.get('access_token'))) 
Example #9
Source File: chatdemo.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def _on_auth(self, user):
        if not user:
            raise tornado.web.HTTPError(500, "Google auth failed")
        self.set_secure_cookie("user", tornado.escape.json_encode(user))
        self.redirect("/") 
Example #10
Source File: authdemo.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def _on_auth(self, user):
        if not user:
            raise tornado.web.HTTPError(500, "Google auth failed")
        self.set_secure_cookie("user", tornado.escape.json_encode(user))
        self.redirect("/") 
Example #11
Source File: authdemo.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def get(self):
        name = tornado.escape.xhtml_escape(self.current_user["name"])
        self.write("Hello, " + name)
        self.write("<br><br><a href=\"/auth/logout\">Log out</a>") 
Example #12
Source File: authdemo.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        handlers = [
            (r"/", MainHandler),
            (r"/auth/login", AuthHandler),
            (r"/auth/logout", LogoutHandler),
        ]
        settings = dict(
            cookie_secret="32oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
            login_url="/auth/login",
        )
        tornado.web.Application.__init__(self, handlers, **settings) 
Example #13
Source File: facebook.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def get(self):
        my_url = (self.request.protocol + "://" + self.request.host +
                  "/auth/login?next=" +
                  tornado.escape.url_escape(self.get_argument("next", "/")))
        if self.get_argument("code", False):
            self.get_authenticated_user(
                redirect_uri=my_url,
                client_id=self.settings["facebook_api_key"],
                client_secret=self.settings["facebook_secret"],
                code=self.get_argument("code"),
                callback=self._on_auth)
            return
        self.authorize_redirect(redirect_uri=my_url,
                                client_id=self.settings["facebook_api_key"],
                                extra_params={"scope": "read_stream"}) 
Example #14
Source File: facebook.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def _on_stream(self, stream):
        if stream is None:
            # Session may have expired
            self.redirect("/auth/login")
            return
        self.render("stream.html", stream=stream) 
Example #15
Source File: blog.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        handlers = [
            (r"/", HomeHandler),
            (r"/archive", ArchiveHandler),
            (r"/feed", FeedHandler),
            (r"/entry/([^/]+)", EntryHandler),
            (r"/compose", ComposeHandler),
            (r"/auth/login", AuthLoginHandler),
            (r"/auth/logout", AuthLogoutHandler),
        ]
        settings = dict(
            blog_title=u"Tornado Blog",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            ui_modules={"Entry": EntryModule},
            xsrf_cookies=True,
            cookie_secret="11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
            login_url="/auth/login",
            autoescape=None,
        )
        tornado.web.Application.__init__(self, handlers, **settings)

        # Have one global connection to the blog DB across all handlers
        self.db = tornado.database.Connection(
            host=options.mysql_host, database=options.mysql_database,
            user=options.mysql_user, password=options.mysql_password) 
Example #16
Source File: authentication.py    From django-gateone with GNU General Public License v3.0 5 votes vote down vote up
def _on_auth(self, user):
            if not user:
                raise tornado.web.HTTPError(500, _("Kerberos auth failed"))
            logging.debug(_("KerberosAuthHandler user: %s" % user))
            user = {'upn': user}
            # This takes care of the user's settings dir and their session info
            self.user_login(user)
            # TODO: Add some LDAP or local DB lookups here to add more detail to user objects
            next_url = self.get_argument("next", None)
            if next_url:
                self.redirect(next_url)
            else:
                self.redirect(self.settings['url_prefix']) 
Example #17
Source File: authentication.py    From django-gateone with GNU General Public License v3.0 5 votes vote down vote up
def _on_auth(self, user):
        """
        Just a continuation of the get() method (the final step where it
        actually sets the cookie).
        """
        logging.debug("GoogleAuthHandler.on_auth(%s)" % user)
        if not user:
            raise tornado.web.HTTPError(500, _("Google auth failed"))
        # NOTE: Google auth 'user' will be a dict like so:
        # user = {'given_name': 'Joe',
        #    'verified_email': True,
        #    'hd': 'example.com',
        #    'gender': 'male',
        #    'email': 'joe.schmoe@example.com',
        #    'name': 'Joe Schmoe',
        #    'picture': 'https://lh6.googleusercontent.com/path/to/some.jpg',
        #    'id': '999999999999999999999',
        #    'family_name': 'Schmoe',
        #    'link': 'https://plus.google.com/999999999999999999999'}
        user['upn'] = user['email'] # Use the email for the upn
        self.user_login(user)
        next_url = self.get_argument("next", None)
        if next_url:
            self.redirect(next_url)
        else:
            self.redirect(self.settings['url_prefix']) 
Example #18
Source File: facebook.py    From tornado-zh with MIT License 5 votes vote down vote up
def _on_auth(self, user):
        if not user:
            raise tornado.web.HTTPError(500, "Facebook auth failed")
        self.set_secure_cookie("fbdemo_user", tornado.escape.json_encode(user))
        self.redirect(self.get_argument("next", "/")) 
Example #19
Source File: facebook.py    From tornado-zh with MIT License 5 votes vote down vote up
def get(self):
        my_url = (self.request.protocol + "://" + self.request.host +
                  "/auth/login?next=" +
                  tornado.escape.url_escape(self.get_argument("next", "/")))
        if self.get_argument("code", False):
            self.get_authenticated_user(
                redirect_uri=my_url,
                client_id=self.settings["facebook_api_key"],
                client_secret=self.settings["facebook_secret"],
                code=self.get_argument("code"),
                callback=self._on_auth)
            return
        self.authorize_redirect(redirect_uri=my_url,
                                client_id=self.settings["facebook_api_key"],
                                extra_params={"scope": "read_stream"}) 
Example #20
Source File: facebook.py    From tornado-zh with MIT License 5 votes vote down vote up
def _on_stream(self, stream):
        if stream is None:
            # Session may have expired
            self.redirect("/auth/login")
            return
        self.render("stream.html", stream=stream) 
Example #21
Source File: authentication.py    From django-gateone with GNU General Public License v3.0 4 votes vote down vote up
def get(self):
        """
        Sets the 'user' cookie with an appropriate *upn* and *session* and any
        other values that might be attached to the user object given to us by
        Google.
        """
        self.base_url = "{protocol}://{host}:{port}{url_prefix}".format(
            protocol=self.request.protocol,
            host=self.request.host,
            port=self.settings['port'],
            url_prefix=self.settings['url_prefix'])
        uri_port = ':{0}/'.format(self.settings['port'])
        if uri_port in self.base_url:
            # Get rid of the port (will be added automatically)
            self.base_url = self.base_url.replace(uri_port, '/', 1)
        redirect_uri = "{base_url}auth".format(base_url=self.base_url)
        check = self.get_argument("check", None)
        if check:
            self.set_header('Access-Control-Allow-Origin', '*')
            user = self.get_current_user()
            if user:
                logging.debug('GoogleAuthHandler: user is authenticated')
                self.write('authenticated')
            else:
                logging.debug('GoogleAuthHandler: user is NOT authenticated')
                self.write('unauthenticated')
            self.finish()
            return
        logout_url = "https://accounts.google.com/Logout"
        logout = self.get_argument("logout", None)
        if logout:
            user = self.get_current_user()['upn']
            self.clear_cookie('gateone_user')
            self.user_logout(user, logout_url)
            return
        if self.get_argument('code', False):
            user = yield self.get_authenticated_user(
                redirect_uri=redirect_uri,
                code=self.get_argument('code'))
            if not user:
                self.clear_all_cookies()
                raise tornado.web.HTTPError(500, 'Google auth failed')
            access_token = str(user['access_token'])
            http_client = self.get_auth_http_client()
            response =  yield http_client.fetch(
                'https://www.googleapis.com/oauth2/v1/userinfo?access_token='
                +access_token)
            if not response:
                self.clear_all_cookies()
                raise tornado.web.HTTPError(500, 'Google auth failed')
            user = json.loads(response.body.decode('utf-8'))
            self._on_auth(user)
        else:
            yield self.authorize_redirect(
                redirect_uri=redirect_uri,
                client_id=self.settings['google_oauth']['key'],
                scope=['email'],
                response_type='code',
                extra_params={'approval_prompt': 'auto'})