Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions blackduck/HubRestApi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1004,6 +1004,11 @@ def _find_user_group_url(self, assignable_user_groups, user_group_name):
if user_group['name'] == user_group_name:
return user_group['usergroup']

def _find_user_url(self, assignable_user, user_name):
for user in assignable_user['items']:
if user['name'] == user_name:
return user['user']

def _project_role_urls(self, project_role_names):
all_project_roles = self.get_project_roles()
project_role_urls = list()
Expand Down Expand Up @@ -1066,8 +1071,61 @@ def assign_user_group_to_project(self, project_name, user_group_name, project_ro
else:
logging.warning("Did not find a project by the name {}".format(project_name))

def assign_user_to_project(self, user_name, project_name, project_roles_l):
pass
def assign_user_to_project(self, user_name, project_name, project_roles, limit=1000):
# Assign users to projects
project = self.get_project_by_name(project_name)

if project:
project_url = project['_meta']['href']
assignable_users_link = self.get_link(project, 'assignable-users')
paramstring = self.get_limit_paramstring(limit)
url = assignable_users_link + paramstring
logging.debug("GET {}".format(url))
if assignable_users_link:
assignable_users_response = self.execute_get(url)
assignable_users = assignable_users_response.json()

# TODO: What to do if the user is already assigned to the project, and therefore
# does not appear in the list of 'assignable' user? Should we search the (assigned) user
# and re-apply the project-roles to the assignment?

user_url = self._find_user_url(assignable_users, user_name)
if user_url:
headers = self.get_headers()

# need project role urls to build the POST payload
project_roles_urls = self._project_role_urls(project_roles)

# The POST endpoint changes based on whether we found any project-roles to assign
# Also, due to what appears to be a defect, the Content-Type changes
if project_roles_urls:
url = user_url + "/roles"
# one dict per project role assignment
post_data = [{'role': r, 'scope': project_url} for r in project_roles_urls]
# I found I had to use this Content-Type (application/json resulted in 412)
# ref: https://jira.dc1.lan/browse/HUB-18417
headers['Content-Type'] = 'application/vnd.blackducksoftware.internal-1+json'
else:
url = project_url + "/users"
# Assigning a user with no project-roles
post_data = {"user": user_url}
headers['Content-Type'] = 'application/json'

response = requests.post(
url,
headers=headers,
data=json.dumps(post_data),
verify=not self.config['insecure'])
return response
else:
assignable_username = [u['name'] for u in assignable_users['items']]
logging.warning(
"The user {} was not found in the assignable user ({}) for this project {}. Is the user already assigned to this project?".format(
user_name, assignable_username, project_name))
else:
logging.warning("This project {} has no assignable users".format(project_name))
else:
logging.warning("Did not find a project by the name {}".format(project_name))

def assign_project_application_id(self, project_name, application_id, overwrite=False):
logging.debug("Assigning application_id {} to project_name {}, overwrite={}".format(
Expand Down
62 changes: 62 additions & 0 deletions examples/assign_user_to_project.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'''
Created on April 26, 2019

@author: amacdonald

Assign a user to a project, providing the project-specific roles the user group should have (on the project)

Largely taken from assign_user_group_to_project, credit to gsnyder

'''

import argparse
import logging
import sys

from blackduck.HubRestApi import HubInstance


project_roles = [
"BOM Manager",
"Policy Violation Reviewer",
"Project Code Scanner",
"Project Manager",
"Security Manager",
]

project_roles_str = ",".join(project_roles)

parser = argparse.ArgumentParser("Assign a user to a project along with a list of project roles (optional)")
parser.add_argument("user", help="The name of a user to assign to the project")
parser.add_argument("project", help="The name of the project you want to assign the user to")
parser.add_argument(
"--project_roles", help="A file with the project-specific roles ({}) that will be granted to the user, one per line".format(
project_roles_str))
parser.add_argument("--roles_list", nargs="+", help="The list of roles user should have.")

args = parser.parse_args()

logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', stream=sys.stdout, level=logging.DEBUG)

hub = HubInstance()

if args.project_roles:
project_roles_l = list()
with open(args.project_roles) as f:
project_roles_l = [role.strip() for role in f.readlines()]
elif args.roles_list:
project_roles_l = args.roles_list
print('-----------------------')
print(project_roles_l)
for role in args.roles_list:
role = project_roles_l
else:
project_roles_l = []

response = hub.assign_user_to_project(args.user, args.project, project_roles_l)

if response and response.status_code == 201:
logging.info("Successfully assigned user {} to project {} with project-roles {}".format(
args.user, args.project, project_roles_l))
else:
logging.warning("Failed to assign user {} to project {}".format(args.user, args.project))
62 changes: 62 additions & 0 deletions examples/assign_users_from_CSV.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'''
Created on May 1, 2019

@author: amacdonald

Assign users to a project, providing the project-specific roles the user group should have (on the project) from a CSV file


'''

import csv
import logging
import argparse
import sys

from blackduck.HubRestApi import HubInstance

hub = HubInstance()


project_roles = [
"BOM Manager",
"Policy Violation Reviewer",
"Project Code Scanner",
"Project Manager",
"Security Manager",
]

project_roles_str = ",".join(project_roles)

parser = argparse.ArgumentParser("Add users to project(s) with assigned roles (optional) from CSV file")
parser.add_argument("CSV", help="Location of the CSV file to import")
# "CSV File requires three columns titled 'User,' 'Project,' and 'Roles.'",
# "In the 'Roles' column, separate the roles to assign with a ',' and no spaces")

args = parser.parse_args()

logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', stream=sys.stdout, level=logging.DEBUG)

if args.CSV:
with open(args.CSV, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
project = (row['Project'])
user = (row['User'])
roles = (row['Roles'])
roles_l = []
roles = roles.split(',')
if roles:
for x in range(len(roles)):
project_roles_l = roles

else:
project_roles_l = []

response = hub.assign_user_to_project(user, project, project_roles_l)

if response and response.status_code == 201:
logging.info("Successfully assigned user {} to project {} with project-roles {}".format(user, project, project_roles_l))
else:
logging.warning("Failed to assign user {} to project {}".format(user, project))
print('----------------------')