Skip to content

Instantly share code, notes, and snippets.

@bryanheinz
Created October 10, 2019 21:16
Show Gist options
  • Save bryanheinz/dd150176cb2e6c39f8174c32091d7431 to your computer and use it in GitHub Desktop.
Save bryanheinz/dd150176cb2e6c39f8174c32091d7431 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# https://docs.gitlab.com/ee/api/README.html
import requests
from sys import argv
from pprint import pprint
switches = argv
private_token = "" # gitlab private token
base_url = ""
# Organizations
# Add orgs here, the format is a {dictionary: {dictionary: name, id}}
# the script will take this orgs website 'key' and match it to a new user's email
# this tells the script to assign that person to that company's group.
# you have to manually create a company's group in Gitlab and get their group ID.
# running `gitlab.py -g GROUP` will get a group's ID
orgs = {
'allsafe.com': {
'name': 'Allsafe', # whatever the organization name is.
'id': 1 # group ID from using gitlab.py -g <group>
},
}
def switch(item):
try:
index = switches.index(item) + 1
except ValueError:
print("\nMissing arguments, exiting...\n")
exit(1)
return(switches[index])
def create_external_user(email, username, name, org, website):
# Create External User
print("")
print("New user:\t{0}".format(name))
print("Email:\t\t{0}".format(email))
print("Username:\t{0}".format(username))
print("Organization:\t{0}".format(org))
print("Website:\t{0}".format(website))
print("")
print("Please confirm the above information before proceeding.")
try:
to_cont = raw_input("Press return to create the user or control+c to quit> ")
except KeyboardInterrupt:
print("")
print("No users were created, exiting...")
exit(0)
if to_cont != "":
print("No users were created, exiting...")
exit(0)
try:
response = requests.post(
url="https://{0}/api/v4/users".format(base_url),
params={
"email": email,
"reset_password": "true",
"username": username,
"name": name,
"admin": "false",
"external": "true",
"projects_limited": "50",
"organization": org,
"website_url": website,
},
headers={
"PRIVATE-TOKEN": private_token,
},
)
response_code = response.status_code
response_data = response.json()
if response_code != 201:
print("Error creating user:")
pprint(response_data)
print("Exiting...\n")
exit(1)
return(response_data['id']) # returns the new users user ID
except requests.exceptions.RequestException:
print('HTTP Request failed')
def modify_user():
# Create External User Duplicate
try:
response = requests.post(
url="https://{0}/api/v4/users/".format(base_url),
params={
"organization": "Thinking Juice",
},
headers={
"PRIVATE-TOKEN": private_token,
},
)
print('Response HTTP Status Code: {status_code}'.format(
status_code=response.status_code))
print('Response HTTP Response Body: {content}'.format(
content=response.content))
except requests.exceptions.RequestException:
print('HTTP Request failed')
def delete_user(uid):
# Delete User
try:
response = requests.delete(
url="https://{0}/api/v4/users/{1}".format(base_url, uid),
headers={
"PRIVATE-TOKEN": private_token,
},
)
print('Response HTTP Status Code: {status_code}'.format(
status_code=response.status_code))
print('Response HTTP Response Body: {content}'.format(
content=response.content))
except requests.exceptions.RequestException:
print('HTTP Request failed')
def list_users():
# List Users
try:
response = requests.get(
url="https://{0}/api/v4/users/".format(base_url),
headers={
"PRIVATE-TOKEN": private_token,
},
)
response_data = response.json()
for _ in response_data:
print(_['username'])
except requests.exceptions.RequestException:
print('HTTP Request failed')
def list_user(name):
# List Users
try:
response = requests.get(
url="https://{0}/api/v4/users/".format(base_url),
headers={
"PRIVATE-TOKEN": private_token,
},
)
response_data = response.json()
for _ in response_data:
if name in _['username']: # find the username
pprint(_)
break
except requests.exceptions.RequestException:
print('HTTP Request failed')
def list_group(group):
# List Groups
try:
response = requests.get(
url="https://{0}/api/v4/groups/".format(base_url),
headers={
"PRIVATE-TOKEN": private_token,
},
)
response_data = response.json()
for _ in response_data:
if group.lower() in _['name'].lower(): # find the username
print("")
print("URL:\t\t{0}".format(_['web_url']))
print("Description:\t{0}".format(_['description']))
print("Name:\t\t{0}".format(_['name']))
print("ID:\t\t{0}".format(_['id']))
print("")
except requests.exceptions.RequestException:
print('HTTP Request failed')
def list_groups():
# List all groups
try:
response = requests.get(
url="https://{0}/api/v4/groups/".format(base_url),
headers={
"PRIVATE-TOKEN": private_token,
},
)
response_data = response.json()
for _ in response_data:
print("")
print("URL:\t\t{0}".format(_['web_url']))
print("Description:\t{0}".format(_['description']))
print("Name:\t\t{0}".format(_['name']))
print("ID:\t\t{0}".format(_['id']))
print("")
except requests.exceptions.RequestException:
print('HTTP Request failed')
def add_user_to_group(gid, uid):
# Add User to Group
# gid == Group ID
# uid == User ID
try:
response = requests.post(
url="https://{0}/api/v4/groups/{1}/members".format(base_url, gid),
params={
"user_id": uid,
"access_level": 40,
},
headers={
"PRIVATE-TOKEN": private_token,
},
)
if response.status_code != 201:
print("\nFailed to add the new user to the group, please verify.")
except requests.exceptions.RequestException:
print('HTTP Request failed')
def list_projects():
# List Projects
try:
response = requests.get(
url="https://{0}/api/v4/projects/".format(base_url),
headers={
"PRIVATE-TOKEN": private_token,
},
)
response_data = response.json()
for _ in response_data:
if "scripts" in _['name']: # find the username
pprint(_['id'])
pprint(_['name'])
except requests.exceptions.RequestException:
print('HTTP Request failed')
def org_match(email):
website = email.split('@')[1]
try:
org = orgs[website]['name']
except KeyError:
print("")
print("Org not found. Please add the organization to this script.")
print("\t1) Add the group to GitLab")
print("\t2) Run gitlab.py -g <group> to get the group information.")
print("\t3) Add the group data to the orgs dictionary at the top of this script.")
print("")
print("Exiting...")
print("")
exit(1)
gid = orgs[website]['id']
return(website, org, gid)
def generate_username(name):
split_name = name.split(' ')
username = split_name[0]
username = username + split_name[1][0]
return(username.lower())
def help():
print("")
print("GitLab script help:")
print("Usage: gitlab.py --create -e elliot@example.com -n \"Elliot Alderson\"")
print("\t--create\t\tcreates a new user account.")
print("\t-e <email>\t\t(required)")
print("\t-n <\"full name\">\tmust be in quotes (required)")
print("Usage: gitlab.py -g allsafe")
print("\t-g <group>\t\tprint group information.")
print("\t-u <username>\t\tprint user information.")
print("\t-U\t\t\tprints all usersnames.")
print("\t-G\t\t\tprints all groups.")
print("")
if '--help' in switches or '-h' in switches:
help()
exit(0)
if '--create' in switches:
email = switch('-e')
name = switch('-n')
website, org, gid = org_match(email)
username = generate_username(name)
uid = create_external_user(email, username, name, org, website)
add_user_to_group(gid, uid)
if '-g' in switches:
group = switch('-g')
list_group(group)
exit(0)
if '-u' in switches:
user = switch('-u')
list_user(user)
exit(0)
if '-U' in switches:
list_users()
exit(0)
if '-G' in switches:
list_groups()
exit(0)
# create_user()
# delete_user(15)
# modify_user()
# list_users()
# list_user('elliot')
# list_group('company_name')
# list_projects()
# add_user_to_group(gid, uid)
# Group and project access levels (access_level)
# default access level is set to 40. It must be 40+ to push to the master branch.
# 10 => Guest access
# 20 => Reporter access
# 30 => Developer access
# 40 => Master access
# 50 => Owner access # Only valid for groups
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment