    async def _add_tokens(self, token_dict, kind):
        """Add tokens for users or services to the database"""
        if kind == 'user':
            Class = orm.User
        elif kind == 'service':
            Class = orm.Service
        else:
            raise ValueError(f"kind must be user or service, not {kind!r}")

        db = self.db
        for token, name in token_dict.items():
            if kind == 'user':
                name = self.authenticator.normalize_username(name)
                if not self.authenticator.validate_username(name):
                    raise ValueError(f"Token user name {name!r} is not valid")
            if kind == 'service':
                if not any(service_name == name for service_name in self._service_map):
                    self.log.warning(
                        f"service {name} not in services, creating implicitly. It is recommended to register services using services list."
                    )
            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",
                        generated=self.trust_user_provided_tokens,
                    )
                except Exception:
                    if created:
                        # don't allow bad tokens to create users
                        db.delete(obj)
                        db.commit()
                    raise
            else:
                self.log.debug("Not duplicating token %s", orm_token)
        db.commit()
Add tokens for users or services to the database
jupyterhub/app.py