Example #1
0
def _get_credentials(organization):
    pat_token_present = False
    if PAT_ENV_VARIABLE_NAME in os.environ or get_credential(
            organization) is not None:
        logger.debug("PAT is present which can be used against this instance")
        pat_token_present = True

    try:
        token_from_az_login = get_token_from_az_logins(organization,
                                                       pat_token_present)
        if token_from_az_login:
            credentials = BasicAuthentication('', token_from_az_login)
            return credentials
    except BaseException as ex:
        logger.debug("az login is not present")
        logger.debug(ex, exc_info=True)

    if PAT_ENV_VARIABLE_NAME in os.environ:
        pat = os.environ[PAT_ENV_VARIABLE_NAME]
        logger.info("received PAT from environment variable")
    else:
        pat = get_credential(organization)
    if pat is not None:
        logger.info("Creating connection with personal access token.")
        credentials = BasicAuthentication('', pat)
        # credentials can be incorrect but they are present then it means user has already done az devops login to set
        # so let the user get a 401
        return credentials

    raise get_authentication_error(
        'Before you can run Azure DevOps commands, you need to run the login command'
        '(az login if using AAD/MSA identity else az devops login if using PAT token) to '
        'setup credentials.')
Example #2
0
    def test_basic_auth(self):

        basic = BasicAuthentication("username", "password")
        session = basic.signed_session()

        req = session.auth(self.request)
        self.assertTrue('Authorization' in req.headers)
        self.assertTrue(req.headers['Authorization'].startswith('Basic '))
Example #3
0
    def test_basic_auth(self):

        basic = BasicAuthentication("username", "password")
        session = basic.signed_session()

        req = session.auth(self.request)
        self.assertTrue('Authorization' in req.headers)
        self.assertTrue(req.headers['Authorization'].startswith('Basic '))
Example #4
0
 def credentials(self):
     if self.token:
         return BasicAuthentication("", self.token)
     else:
         warnings.warn(
             "No token available.  No modifications will be possible!")
         return Authentication()
    def __init__(self, config_file='config.json'):
        config_dict = None
        config_paths = [
            os.getcwd() + r"/devops_tasks/" + config_file, config_file
        ]
        self.clr = colorstr.bcolors()
        self.url = 'https://dev.azure.com/'
        self.work_item_dict = {}

        for config_path in config_paths:
            try:
                config_dict = json.load(open(config_path))
                if config_dict:
                    break
            except:
                pass

        if not config_dict:
            print(
                f"\n{self.clr.FAIL}[ERROR]{self.clr.ENDC} Empty or non-existent config file in either of paths:"
            )
            print(f"{config_paths}")
            return

        self.credentials = BasicAuthentication(
            "", config_dict["personal_access_token"])
        org_dict = config_dict["org_dict"]
        states = config_dict["states"]
        self.get_work_items(org_dict, states)
Example #6
0
def GetADOClient():
    credentials = BasicAuthentication('', personal_access_token)
    connection = Connection(base_url=organization_url, creds=credentials)
    # Get a client (the "core" client provides access to projects, teams, etc)
    core_client = connection.clients.get_core_client()
    wit_client = connection.clients.get_work_item_tracking_client()
    return wit_client
Example #7
0
    def authenticate(self, user, password):
        if user is None:  # The user is already in DB, just need the password
            prev_user = self._localdb.get_username(self._remote.url)
            if prev_user is None:
                raise ConanException("User for remote '%s' is not defined" %
                                     self._remote.name)
            else:
                user = prev_user

        # Create a connection to the org
        organization_url, _ = self._get_organization_url_and_feed(self._remote)
        credentials = BasicAuthentication(user, password)
        connection = Connection(base_url=organization_url, creds=credentials)

        # Authenticate the connection
        try:
            connection.authenticate()
        except Exception as ex:
            raise AuthenticationException(ex)

        # Generate token
        token_raw_bytes = password.encode()
        token_bytes = base64.b64encode(token_raw_bytes)

        # Store result in DB
        remote_name, prev_user, user = update_localdb(
            self._local_db, user, token_bytes.decode(),
            self._sxor(user, password), self._remote)

        return remote_name, prev_user, user
Example #8
0
def upload_to_wiki(url, project, token, filename, wikiname):
    from azure.devops.connection import Connection
    from azure.devops.v5_1.wiki import WikiPageCreateOrUpdateParameters
    from msrest.authentication import BasicAuthentication
    # Fill in with your personal access token and org URL
    personal_access_token = token
    # organization_url = 'https://dev.azure.com/YOURORG'
    organization_url = url

    # Create a connection to the org
    credentials = BasicAuthentication('', personal_access_token)
    connection = Connection(base_url=organization_url, creds=credentials)

    # Get a client (the "core" client provides access to projects, teams, etc)
    core_client = connection.clients.get_core_client()
    '''cmd = 'pandoc -f docx -t gfm ' + filename + '.docx -o foo.markdown'
    os.system(cmd)'''
    pypandoc.convert_file(filename + '.docx',
                          to='markdown_github',
                          outputfile="foo.markdown")
    data = ''
    with open('foo.markdown', 'r') as file:
        data = file.read()

    client = connection.clients.get_wiki_client()
    project_name = project
    wikiPageCreateOrUpdateParameters = WikiPageCreateOrUpdateParameters()
    wikiPageCreateOrUpdateParameters.content = data
    a = client.create_or_update_page(
        project=project,
        path='/' + wikiname,
        wiki_identifier='SS365 ADO Wiki Templates',
        version=None,
        parameters=wikiPageCreateOrUpdateParameters)
    showinfo("Success", "File successfully pushed to wiki!")
Example #9
0
    def get_credentials(self):
        if self.access_token:
            return BasicTokenAuthentication(
                {'access_token': self.access_token})

        token = get_env("VSTS_PAT")
        return BasicAuthentication("ignored", token)
Example #10
0
def connect_azdo(personal_access_token, organization):
    # Create a connection to the org
    credentials = BasicAuthentication('', personal_access_token)
    connection = Connection(base_url=organization_url, creds=credentials)

    # Get a client (the "core" client provides access to projects, teams, etc)
    return connection.clients.get_core_client()
Example #11
0
def init_ado() -> WorkItemTrackingClient:
    credentials = BasicAuthentication('', azure_devops_pat)
    connection = Connection(base_url=azure_devops_url, creds=credentials)
    work_item_tracking_client = connection.clients.get_work_item_tracking_client(
    )

    return work_item_tracking_client
Example #12
0
 def _create_connection(self):
     _credentials = BasicAuthentication(
         '', self._base64_decoder(self._azure_devops_pat))
     _connection_string = self._azure_base_url + self._azure_devops_organization
     _connection = Connection(base_url=_connection_string,
                              creds=_credentials)
     return _connection
Example #13
0
def credential_set(token=None, team_instance=None):
    """Set the credential (PAT) to use for a particular account
    :param token: PAT token for the VSTS account or your TFS project collection.  If not supplied, you will be prompted
                  for your token.
    :type token: str
    :param team_instance: The URI for the VSTS account (https://<account>.visualstudio.com) or your TFS project
                          collection.
    :type team_instance: str
    """
    disable_command_version_checking()
    if token is None:
        try:
            token = prompt_pass('Token: ', confirm=False, help_string="The token (PAT) to authenticate with.")
        except NoTTYException:
            raise CLIError('The token argument needs to be set when run in a non-interactive mode.')

    if team_instance is not None:
        team_instance = get_base_url(team_instance)
        logger.info("Creating connection with personal access token.")
        credentials = BasicAuthentication('', token)
        connection = _get_vss_connection(team_instance, credentials)
        location_client = connection.get_client('vsts.location.v4_1.location_client.LocationClient')
        try:
            location_client.get_connection_data()
        except Exception as ex2:
            logger.debug(ex2, exc_info=True)
            raise ValueError("Failed to authenticate using the supplied token.")
    set_credential(team_instance=team_instance, token=token)
Example #14
0
def connect(pat, organization, project):
    global _connection, _project
    organization_url = 'https://dev.azure.com/{ORGANIZATION_NAME}'.format(ORGANIZATION_NAME=organization)
    credentials = BasicAuthentication('', pat)
    _connection = Connection(base_url=organization_url, creds=credentials)
    _connection._config.verify=False
    _project = project
Example #15
0
    def get_authed_connection(self):
        """Get an authenticated Connection for Azure DevOps.

        Returns:
            class: Azure DevOps authenticated connected.
        """
        credentials = BasicAuthentication("", self.personal_access_token)
        return Connection(self.org_url, credentials)
Example #16
0
def connect(token: str, url: str):
    """Create new connection."""
    try:
        return Connection(base_url=url,
                          creds=BasicAuthentication('', token))
    except ValueError as e:
        print('Export env: `organization_url`, `personal_access_token`.')
        raise e
Example #17
0
    def _auth(self, org, token):
        if org is None or token is None:
            raise ValueError("incorrect parameters were passed")

        credentials = BasicAuthentication('', token)
        connection = Connection(base_url=f'https://dev.azure.com/{org}',
                                creds=credentials)

        return connection
    def __init__(self, vsts_pat):
        """Form a VSTS Branch is deleted condition

        :param vsts_pat: VSTS Pat that has Code Reading permission
        """
        self.credentials = BasicAuthentication('', vsts_pat)
        self.vsts_base_url_key = "vsts_base_url"
        self.vsts_repository_id_key = "vsts_repository_id"
        self.branch_key = "branch"
Example #19
0
class AzureDevOpsClientFactory(object):
    _connection_factory = Connection(
        base_url=AzureDevOpsConfig.ORGANIZATION_URL,
        creds=BasicAuthentication('', AzureDevOpsConfig.PERSONAL_ACCESS_TOKEN))

    @staticmethod
    def get_git_client():
        return AzureDevOpsClientFactory._connection_factory.clients.get_git_client(
        )
Example #20
0
    def __init__(self, token):
        """The __init__ function loads the credentials and does the authentication
        with the AzureDevOpsInteractor. The credentials are token based and are defined
        by AZDO_TOKEN environment varriable.
        """

        credentials = BasicAuthentication("", token)
        connection = Connection("https://jet2tfs.visualstudio.com",
                                creds=credentials)
        self._azdo = connection.clients.get_git_client()
def get_python_pipelines():
    python_piplines = {}
    pipeline_client = PipelinesClient(base_url='https://dev.azure.com/azure-sdk',
                                      creds=BasicAuthentication(os.getenv('PIPELINE_TOKEN'), ''))
    pipelines = pipeline_client.list_pipelines(project='internal')
    for pipeline in pipelines:
        if re.findall('^python - \w*$', pipeline.name):
            key = pipeline.name.replace('python - ', '')
            python_piplines[key] = pipeline.id
    return python_piplines
Example #22
0
def get_client(organization, personal_access_token):
    organization_url = 'https://dev.azure.com/' + organization

    # Create a connection to the org
    credentials = BasicAuthentication('', personal_access_token)
    connection = Connection(base_url=organization_url, creds=credentials)

    # Get the build client
    build_client = connection.clients_v6_0.get_build_client()
    return build_client
Example #23
0
def create_tfs_connection(url, token):
    """
    Creates the TFS Connection Context
    """
    if token is None:
        token = os.environ.get('TFS_API_TOKEN', None)

    tfs_credentials = BasicAuthentication('', token)
    tfs_connection = VssConnection(base_url=url, creds=tfs_credentials)
    return tfs_connection
Example #24
0
def pipemain():

    # Create a connection to the org
    connection = Connection(base_url=ORG_URL,
                            creds=BasicAuthentication('', PAT))

    # Get the build status
    build_client = connection.clients.get_build_client()
    buildDef = build_client.get_definition(PROJECT,
                                           BUILD_PIPELINE_ID,
                                           include_latest_builds=True)

    if buildDef.latest_completed_build.id == buildDef.latest_build.id:
        print("Build " + buildDef.latest_build.definition.name + " " +
              buildDef.latest_build.build_number + " " +
              buildDef.latest_completed_build.result)
    else:
        # A build is in progress
        print("Build " + buildDef.latest_build.definition.name + " " +
              buildDef.latest_build.build_number + " " +
              buildDef.latest_completed_build.result + " (" +
              buildDef.latest_build.status + ")")

    # Get Release Client
    rm_client = connection.clients.get_release_client()

    # See what environments we have and the status of their latest deployments
    release = rm_client.get_release_definition(PROJECT, RELEASE_ID)
    for e in release.environments:
        deployments = rm_client.get_deployments(PROJECT,
                                                definition_id=RELEASE_ID,
                                                definition_environment_id=e.id,
                                                top=1,
                                                deployment_status="all")
        print(
            str(e.id) + " - " + e.name + ": " + deployments[0].release.name +
            " - " + deployments[0].deployment_status)

    # Look up pending approvals
    approvals = rm_client.get_approvals(project=PROJECT,
                                        type_filter="preDeploy")

    for a in approvals:
        print(a.release.name + " awaiting approval to " +
              a.release_environment.name)

    if len(approvals) > 0:
        # Approve one of them
        approval = approvals[0]
        approval.status = "approved"
        approval.comments = "Approved by DasDeployer"
        releaseApproval = rm_client.update_release_approval(
            approval, PROJECT, approval.id)
        print("Approved " + releaseApproval.release.name + " to " +
              releaseApproval.release_environment.name)
Example #25
0
    def __init__(self, organisation, password):
        self._organization_url = f'https://dev.azure.com/{organisation}'

        self._requests_auth = HTTPBasicAuth('', password)
        credentials = BasicAuthentication('', password)
        connection = Connection(base_url=self._organization_url,
                                creds=credentials)

        self._organisation = organisation
        self._core_client = connection.clients.get_core_client()
        self._git_client = connection.clients.get_git_client()
Example #26
0
def build_wheels_azure(version):
    token = getpass.getpass("Azure personal access token: ")
    credentials = BasicAuthentication("", token)
    connection = Connection(base_url="https://dev.azure.com/pyca",
                            creds=credentials)
    build_client = connection.clients.get_build_client()
    [definition] = build_client.get_definitions("pynacl", "wheel-builder")
    build_description = Build(definition=definition, )
    build = build_client.queue_build(project="pynacl", build=build_description)
    wait_for_build_completed_azure(build_client, build.id)
    return download_artifacts_azure(build_client, build.id)
Example #27
0
 def __init__(self, username, az_pat):
     self.username = username
     self.az_pat = az_pat
     self.organization_url = load_global_params_config()[
         'common_var']['url']
     self.organization = load_global_params_config()['common_var']['org']
     self.project = load_global_params_config()['common_var']['project']
     self.credentials = BasicAuthentication(self.username, self.az_pat)
     self.connection = Connection(
         base_url=self.organization_url, creds=self.credentials)
     self.release = self.connection.clients_v6_0.get_release_client()
Example #28
0
    def _connect(self):
        """
        Logins to the Azure DevOps API and sets the release_client.

        """
        credentials = BasicAuthentication("", self.access_cfg.access_token)
        connection = Connection(
            base_url=f"https://dev.azure.com/{self.access_cfg.organisation}/",
            creds=credentials)

        self.release_client = connection.clients_v5_1.get_release_client()
def build_context(p_azdevops_uri, p_auth_token, p_project):
    context = SimpleNamespace()

    context.project_of_interest = p_project
    logger.info("Creating azcli connection ...")
    context.connection = Connection(base_url=p_azdevops_uri,
                                    creds=BasicAuthentication(
                                        'PAT', p_auth_token),
                                    user_agent='azgitdiff/' + __VERSION__)

    return context
Example #30
0
 def __init__(self, uri: str, personal_access_token: str) -> None:
     print(
         f'azure_devops_interface constructor called with uri={uri} and PAT={personal_access_token}'
     )
     self._uri = uri
     self._personal_access_token = personal_access_token
     self._credentials = BasicAuthentication('',
                                             self._personal_access_token)
     self._connection = Connection(base_url=self._uri,
                                   creds=self._credentials)
     self._azure_devops_client = \
         self._connection.clients_v6_0.get_work_item_tracking_client()
Example #31
0
 def __init__(self, username, az_pat):
     """
     https://github.com/microsoft/azure-devops-python-api
     """
     self.username = username
     self.az_pat = az_pat
     self.organization_url = load_global_params_config()['common_var']['url']
     self.organization = load_global_params_config()['common_var']['org']
     self.project = load_global_params_config()['common_var']['project']
     self.credentials = BasicAuthentication(self.username, self.az_pat)
     self.connection = Connection(base_url=self.organization_url, creds=self.credentials)
     self.pipeline = self.connection.clients_v6_0.get_pipelines_client()