How to use the jupyterhub.orm.APIToken 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 jupyterhub / jupyterhub / jupyterhub / handlers / base.py View on Github external
def get_current_user_token(self):
        """get_current_user from Authorization header token"""
        token = self.get_auth_token()
        if token is None:
            return None
        orm_token = orm.APIToken.find(self.db, token)
        if orm_token is None:
            return None

        # record token activity
        now = datetime.utcnow()
        orm_token.last_activity = now
        if orm_token.user:
            orm_token.user.last_activity = now
        self.db.commit()

        if orm_token.service:
            return orm_token.service

        return self._user_from_orm(orm_token.user)
github jupyterhub / jupyterhub / jupyterhub / app.py View on Github external
for token, name in token_dict.items():
            if kind == 'user':
                name = self.authenticator.normalize_username(name)
                if not (
                    await maybe_future(self.authenticator.check_whitelist(name, None))
                ):
                    raise ValueError("Token name %r is not in whitelist" % name)
                if not self.authenticator.validate_username(name):
                    raise ValueError("Token name %r is not valid" % name)
            if kind == 'service':
                if not any(service["name"] == name for service in self.services):
                    self.log.warning(
                        "Warning: service '%s' not in services, creating implicitly. It is recommended to register services using services list."
                        % name
                    )
            orm_token = orm.APIToken.find(db, token)
            if orm_token is None:
                obj = Class.find(db, name)
                created = False
                if obj is None:
                    created = True
                    self.log.debug("Adding %s %s to database", kind, name)
                    obj = Class(name=name)
                    db.add(obj)
                    db.commit()
                self.log.info("Adding API token for %s: %s", kind, name)
                try:
                    # set generated=False to ensure that user-provided tokens
                    # get extra hashing (don't trust entropy of user-provided tokens)
                    obj.new_api_token(
                        token,
                        note="from config",
github jupyterhub / jupyterhub / jupyterhub / user.py View on Github external
self.log.debug("Stopping %s", spawner._log_name)

        try:
            api_token = spawner.api_token
            status = await spawner.poll()
            if status is None:
                await spawner.stop()
            spawner.clear_state()
            spawner.orm_spawner.state = spawner.get_state()
            self.last_activity = spawner.orm_spawner.last_activity = datetime.utcnow()
            # remove server entry from db
            spawner.server = None
            if not spawner.will_resume:
                # find and remove the API token and oauth client if the spawner isn't
                # going to re-use it next time
                orm_token = orm.APIToken.find(self.db, api_token)
                if orm_token:
                    self.db.delete(orm_token)
                # remove oauth client as well
                # handle upgrades from 0.8, where client id will be `user-USERNAME`,
                # not just `jupyterhub-user-USERNAME`
                client_ids = (
                    spawner.oauth_client_id,
                    spawner.oauth_client_id.split('-', 1)[1],
                )
                for oauth_client in self.db.query(orm.OAuthClient).filter(
                    orm.OAuthClient.identifier.in_(client_ids)
                ):
                    self.log.debug("Deleting oauth client %s", oauth_client.identifier)
                    self.db.delete(oauth_client)
            self.db.commit()
            self.log.debug("Finished stopping %s", spawner._log_name)
github jupyterhub / jupyterhub / jupyterhub / app.py View on Github external
if kind == 'user':
            Class = orm.User
        elif kind == 'service':
            Class = orm.Service
        else:
            raise ValueError("kind must be user or service, not %r" % kind)

        db = self.db
        for token, name in token_dict.items():
            if kind == 'user':
                name = self.authenticator.normalize_username(name)
                if not (yield gen.maybe_future(self.authenticator.check_whitelist(name))):
                    raise ValueError("Token name %r is not in whitelist" % name)
                if not self.authenticator.validate_username(name):
                    raise ValueError("Token name %r is not valid" % name)
            orm_token = orm.APIToken.find(db, token)
            if orm_token is None:
                obj = Class.find(db, name)
                created = False
                if obj is None:
                    created = True
                    self.log.debug("Adding %s %r to database", kind, name)
                    obj = Class(name=name)
                    db.add(obj)
                    db.commit()
                self.log.info("Adding API token for %s: %s", kind, name)
                try:
                    obj.new_api_token(token)
                except Exception:
                    if created:
                        # don't allow bad tokens to create users
                        db.delete(obj)
github jupyterhub / jupyterhub / jupyterhub / apihandlers / auth.py View on Github external
def get(self, token):
        orm_token = orm.APIToken.find(self.db, token)
        if orm_token is None:
            orm_token = orm.OAuthAccessToken.find(self.db, token)
        if orm_token is None:
            raise web.HTTPError(404)

        # record activity whenever we see a token
        now = orm_token.last_activity = datetime.utcnow()
        if orm_token.user:
            orm_token.user.last_activity = now
            model = self.user_model(self.users[orm_token.user])
        elif orm_token.service:
            model = self.service_model(orm_token.service)
        else:
            self.log.warning("%s has no user or service. Deleting..." % orm_token)
            self.db.delete(orm_token)
            self.db.commit()
github jupyterhub / jupyterhub / jupyterhub / apihandlers / users.py View on Github external
def find_token_by_id(self, user, token_id):
        """Find a token object by token-id key

        Raises 404 if not found for any reason
        (e.g. wrong owner, invalid key format, etc.)
        """
        not_found = "No such token %s for user %s" % (token_id, user.name)
        prefix, id = token_id[0], token_id[1:]
        if prefix == 'a':
            Token = orm.APIToken
        elif prefix == 'o':
            Token = orm.OAuthAccessToken
        else:
            raise web.HTTPError(404, not_found)
        try:
            id = int(id)
        except ValueError:
            raise web.HTTPError(404, not_found)

        orm_token = self.db.query(Token).filter(Token.id == id).first()
        if orm_token is None or orm_token.user is not user.orm_user:
            raise web.HTTPError(404, "Token not found %s", orm_token)
        return orm_token
github jupyterhub / jupyterhub / jupyterhub / oauth / orm.py View on Github external
refresh_token = 'refresh_token'


class OAuthAccessToken(Base):
    __tablename__ = 'oauth_access_tokens'
    id = Column(Integer, primary_key=True, autoincrement=True)

    client_id = Column(Unicode(1023))
    grant_type = Column(Enum(GrantType), nullable=False)
    expires_at = Column(Integer)
    refresh_token = Column(Unicode(36))
    refresh_expires_at = Column(Integer)
    user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'))
    user = relationship(User)
    api_token_id = Column(Integer, ForeignKey('api_tokens.id', ondelete='CASCADE'))
    api_token = relationship(APIToken, backref='oauth_token')


class OAuthCode(Base):
    __tablename__ = 'oauth_codes'
    id = Column(Integer, primary_key=True, autoincrement=True)
    client_id = Column(Unicode(1023))
    code = Column(Unicode(36))
    expires_at = Column(Integer)
    redirect_uri = Column(Unicode(1023))
    user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'))


class OAuthClient(Base):
    __tablename__ = 'oauth_clients'
    id = Column(Integer, primary_key=True, autoincrement=True)
    identifier = Column(Unicode(1023), unique=True)
github jupyterhub / jupyterhub / jupyterhub / app.py View on Github external
async def init_api_tokens(self):
        """Load predefined API tokens (for services) into database"""
        await self._add_tokens(self.service_tokens, kind='service')
        await self._add_tokens(self.api_tokens, kind='user')
        purge_expired_tokens = partial(orm.APIToken.purge_expired, self.db)
        purge_expired_tokens()
        # purge expired tokens hourly
        # we don't need to be prompt about this
        # because expired tokens cannot be used anyway
        pc = PeriodicCallback(
            purge_expired_tokens, 1e3 * self.purge_expired_tokens_interval
        )
        pc.start()
github jupyterhub / jupyterhub / jupyterhub / apihandlers / base.py View on Github external
def token_model(self, token):
        """Get the JSON model for an APIToken"""
        expires_at = None
        if isinstance(token, orm.APIToken):
            kind = 'api_token'
            extra = {'note': token.note}
            expires_at = token.expires_at
        elif isinstance(token, orm.OAuthAccessToken):
            kind = 'oauth'
            extra = {'oauth_client': token.client.description or token.client.client_id}
            if token.expires_at:
                expires_at = datetime.fromtimestamp(token.expires_at)
        else:
            raise TypeError(
                "token must be an APIToken or OAuthAccessToken, not %s" % type(token)
            )

        if token.user:
            owner_key = 'user'
            owner = token.user.name