How to use the jupyterhub.auth.Authenticator function in jupyterhub

To help you get started, we’ve selected a few jupyterhub examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Jupyter-contrib / jupyter_nbextensions_configurator / tests / test_jupyterhub.py View on Github external
def _log_default(self):
        """wrap loggers for this application."""
        return wrap_logger_handlers(Authenticator._log_default(self))
github MetaCell / NetPyNE-UI / k8s / auth.py View on Github external
user = yield gen.maybe_future(self.process_user(raw_user, self))
        
        server_name = ''
        redirection = self.get_next_url(user)
        user.spawners[server_name].environment["NETPYNE_URL"] = ''

        if 'hub/source=' in self.request.uri:
            server_name = str(uuid.uuid4()).split('-').pop()
            redirection = f'/hub/spawn/{user.name}/{server_name}'
            user.spawners[server_name].environment["NETPYNE_URL"] = self.request.uri.split('=').pop()
        
        self.redirect(redirection)


class TmpAuthenticator(Authenticator):
    auto_login = True
    login_service = 'tmp'

    force_new_server = Bool(
        False,
        help="""
        Stop the user's server and start a new one when visiting /hub/tmplogin
        When set to True, users going to /hub/tmplogin will *always* get a
        new single-user server. When set to False, they'll be
        redirected to their current session if one exists.
        """,
        config=True
    )

    def process_user(self, user, handler):
        return user
github jupyterhub / dummyauthenticator / dummyauthenticator / dummyauthenticator.py View on Github external
from traitlets import Unicode

from jupyterhub.auth import Authenticator

from tornado import gen


class DummyAuthenticator(Authenticator):
    password = Unicode(
        None,
        allow_none=True,
        config=True,
        help="""
        Set a global password for all users wanting to log in.

        This allows users with any username to log in with the same static password.
        """
    )

    @gen.coroutine
    def authenticate(self, handler, data):
        if self.password:
            if data['password'] == self.password:
                return data['username']
github jupyterhub / jupyterhub / jupyterhub / app.py View on Github external
def _load_classes(self):
        classes = [Spawner, Authenticator, CryptKeeper]
        for name, trait in self.traits(config=True).items():
            # load entry point groups into configurable class list
            # so that they show up in config files, etc.
            if isinstance(trait, EntryPointType):
                for key, entry_point in trait.load_entry_points().items():
                    try:
                        cls = entry_point.load()
                    except Exception as e:
                        self.log.debug(
                            "Failed to load %s entrypoint %r: %r",
                            trait.entry_point_group,
                            key,
                            e,
                        )
                        continue
                    if cls not in classes and isinstance(cls, Configurable):
github everware / everware / everware / authenticator.py View on Github external
self.set_login_cookie(user)
            user.login_service = "github"
            if 'repourl' in state:
                self.log.debug("Redirect with %s", state)
                self.redirect(self.hub.server.base_url +'/home?'+urllib.parse.urlencode(state))
            else:
                self.redirect(self.hub.server.base_url + '/home')
        else:
            raise web.HTTPError(403)


class BitbucketOAuthHandler(GitHubOAuthHandler):
    pass


class GitHubOAuthenticator(Authenticator):
    
    login_service = "GitHub"
    oauth_callback_url = Unicode('', config=True)
    client_id = Unicode(os.environ.get('GITHUB_CLIENT_ID', ''),
                        config=True)
    client_secret = Unicode(os.environ.get('GITHUB_CLIENT_SECRET', ''),
                            config=True)

    def login_url(self, base_url):
        return url_path_join(base_url, 'login')
    
    def get_handlers(self, app):
        return [
            (r'/login', WelcomeHandler),
            (r'/oauth_login', GitHubLoginHandler),
            (r'/oauth_callback', GitHubOAuthHandler),
github everware / everware / everware / authenticator.py View on Github external
"Authorization": "token {}".format(access_token)
        }
        req = HTTPRequest("https://api.github.com/user",
                          method="GET",
                          headers=headers
                          )
        resp = yield http_client.fetch(req)
        resp_json = json.loads(resp.body.decode('utf8', 'replace'))
        
        username = self.normalize_username(resp_json["login"])
        if self.whitelist and username not in self.whitelist:
            username = None
        raise gen.Return((username, access_token))


class BitbucketOAuthenticator(Authenticator):

    login_service = "Bitbucket"
    oauth_callback_url = Unicode(os.environ.get('OAUTH_CALLBACK_URL', ''),
                                 config=True)
    client_id = Unicode(os.environ.get('BITBUCKET_CLIENT_ID', ''),
                        config=True)
    client_secret = Unicode(os.environ.get('BITBUCKET_CLIENT_SECRET', ''),
                            config=True)
    team_whitelist = Set(
        config=True,
        help="Automatically whitelist members of selected teams",
    )

    def login_url(self, base_url):
        return url_path_join(base_url, 'oauth_login')
github jupyterhub / oauthenticator / oauthenticator / oauth2.py View on Github external
return user

    if not hasattr(BaseHandler, 'login_user'):
        # JupyterHub 0.7 doesn't have .login_user
        login_user = _login_user_pre_08

    async def get(self):
        self.check_arguments()
        user = await self.login_user()
        if user is None:
            # todo: custom error page?
            raise web.HTTPError(403)
        self.redirect(self.get_next_url(user))


class OAuthenticator(Authenticator):
    """Base class for OAuthenticators

    Subclasses must override:

    login_service (string identifying the service provider)
    authenticate (method takes one arg - the request handler handling the oauth callback)
    """

    login_handler = OAuthLoginHandler
    callback_handler = OAuthCallbackHandler

    authorize_url = Unicode(
        config=True, help="""The authenticate url for initiating oauth"""
    )
    @default("authorize_url")
    def _authorize_url_default(self):
github jupyterhub / jupyterhub / jupyterhub / app.py View on Github external
'command': ['/path/to/cull_idle_servers.py'],
                },
                {
                    'name': 'formgrader',
                    'url': 'http://127.0.0.1:1234',
                    'api_token': 'super-secret',
                    'environment':
                }
            ]
        """,
    ).tag(config=True)
    _service_map = Dict()

    authenticator_class = EntryPointType(
        default_value=PAMAuthenticator,
        klass=Authenticator,
        entry_point_group="jupyterhub.authenticators",
        help="""Class for authenticating users.

        This should be a subclass of :class:`jupyterhub.auth.Authenticator`

        with an :meth:`authenticate` method that:

        - is a coroutine (asyncio or tornado)
        - returns username on success, None on failure
        - takes two arguments: (handler, data),
          where `handler` is the calling web.RequestHandler,
          and `data` is the POST form data from the login page.

        .. versionchanged:: 1.0
            authenticators may be registered via entry points,
            e.g. `c.JupyterHub.authenticator_class = 'pam'`
github jupyterhub / outreachy / Authenticator / authenticator.py View on Github external
from jupyterhub.auth import Authenticator
from tornado import gen
import csv


class MyAuthenticator(Authenticator):
    @gen.coroutine
    def authenticate(self, data, handler):

        csv_dict={}
        with open('authentication.csv', mode='r') as csv_file:
            csv_data = {row["title"]: row["value"] for row in csv.DictReader(csv_file, ("title", "value"))}
            csv_dict.update(csv_data)

        if data['username'] not in csv_dict:
            self.logger.warning("No such user: %s", data['username'])
            return None
        else:

            if csv_dict[name] != data['password']:
                self.logger.warning("Incorrect password for user: %s", data['username'])
                return None
github jupyterhub / nullauthenticator / nullauthenticator.py View on Github external
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

from jupyterhub.auth import Authenticator
from jupyterhub.handlers.base import BaseHandler

__version__ = '1.1.0.dev'


class NullLoginHandler(BaseHandler):
    def get(self):
        raise web.HTTPError(403, "Login is not supported")


class NullAuthenticator(Authenticator):

    # auto_login skips 'Login with...' page on Hub 0.8
    auto_login = True

    # for Hub 0.7, show 'login with...'
    login_service = 'null'

    def get_handlers(self, app):
        return [('/nologin', NullLoginHandler)]