Skip to content

Instantly share code, notes, and snippets.

@icelander
Created March 9, 2022 05:28
Show Gist options
  • Save icelander/b05ad0326e8d4df55307bad95e1e18a2 to your computer and use it in GitHub Desktop.
Save icelander/b05ad0326e8d4df55307bad95e1e18a2 to your computer and use it in GitHub Desktop.
Creating a user and then authenticating as that user using the Python standard library
#!/usr/bin/env python
from urllib.request import urlopen, Request
from urllib.parse import quote
from urllib.error import URLError
import json
ADMIN_TOKEN = "6n7faf61b4o8ukcornejciyx7e"
BASE_URL = "https://mattermost.example.com/api/v4" # <= No slash!
def login(username, password):
url = "{}/users/login".format(BASE_URL)
data = {
'login_id': username,
'password': password
}
req = Request(
url,
json.dumps(data).encode('ascii'),
{"Content-Type": "application/json"}
)
try:
response = urlopen(req)
token = response.headers['Token']
json_response = json.load(response)
return token, json_response
except URLError as e:
return False
else:
return False
def http_get(url, token):
full_url = "{}{}".format(BASE_URL, url)
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(token)
}
req = Request(full_url)
req.headers = headers
try:
response = urlopen(req)
json_response = json.load(response)
return json_response
except URLError as e:
print(e)
return False
else:
return False
def http_post(url, data, token):
full_url = "{}{}".format(BASE_URL, url)
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(token)
}
req = Request(
full_url,
json.dumps(data).encode('ascii'),
headers
)
try:
response = urlopen(req)
json_response = json.load(response)
return json_response
except URLError as e:
return {'status': e.code}
def main():
user = {
"email": "[email protected]",
"username": "e-user",
"password": "37w8dyxeaojfmxjzihrc5k4gwh"
}
print("Checking to see if user {} exists".format(user['email']))
url = "/users/email/{}".format(user["email"])
found_user = http_get(url, ADMIN_TOKEN)
if found_user == False:
url = "/users"
print("Creating user {}".format(user['email']))
http_post(url, user, ADMIN_TOKEN)
else:
print("User exists!")
print("Authenticating as {} with password {}".format(user['username'], user['password']))
user_token, user = login(user['username'], user['password'])
print("Got token {}".format(user_token))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment