Unable to authenticate admin and check user existence using python

  • What Grafana version and what operating system are you using?
    10.4.3

  • What are you trying to achieve?
    Check the user existence in Grafana using login/email in python scripting

  • How are you trying to achieve it?
    def authenticate_admin(admin_username, admin_password, grafana_url):
    login_url = f"{grafana_url}/login"
    data = {‘user’: admin_username, ‘password’: admin_password}
    response = requests.post(login_url, data=data)
    if response.status_code == 200:
    return response.cookies.get(‘grafana_sess’)
    else:
    print(“Failed to authenticate admin.”)
    return None

def check_user_existence(username, grafana_url, admin_username, admin_password):
session_cookie = authenticate_admin(admin_username, admin_password, grafana_url)
if session_cookie:
headers = {‘Cookie’: ‘grafana_sess=’ + session_cookie}
users_url = f"{grafana_url}/api/users/search"
response = requests.get(users_url, headers=headers, params={‘query’: username})
if response.status_code == 200:
users = response.json()
for user in users:
if user[‘login’] == username or user[‘email’].startswith(username):
return True
return False

  • What happened?
    Failed to authenticate admin.

  • What did you expect to happen?
    admin login pass, followed by print user existence in Grafana.

  • Can you copy/paste the configuration(s) that you are having problems with?
    def authenticate_admin(admin_username, admin_password, grafana_url):
    login_url = f"{grafana_url}/login"
    data = {‘user’: admin_username, ‘password’: admin_password}
    response = requests.post(login_url, data=data)
    if response.status_code == 200:
    return response.cookies.get(‘grafana_sess’)
    else:
    print(“Failed to authenticate admin.”)
    return None

def check_user_existence(username, grafana_url, admin_username, admin_password):
session_cookie = authenticate_admin(admin_username, admin_password, grafana_url)
if session_cookie:
headers = {‘Cookie’: ‘grafana_sess=’ + session_cookie}
users_url = f"{grafana_url}/api/users/search"
response = requests.get(users_url, headers=headers, params={‘query’: username})
if response.status_code == 200:
users = response.json()
for user in users:
if user[‘login’] == username or user[‘email’].startswith(username):
return True
return False
def main():
grafana_url = “http://localhost:3000
admin_username = “admin”
admin_password = “************”

# Example usage to check user existence
username = "ABC"
if check_user_existence(username, grafana_url, admin_username, admin_password):
    print(f"User with username '{username}' exists in Grafana.")
else:
    print(f"User with username '{username}' does not exist in Grafana.")

if name == “main”:
main()

  • Did you receive any errors in the Grafana UI or in related logs? If so, please tell us exactly what they were.

  • Did you follow any online instructions? If so, what is the URL?

Hi @sraghavendra1512.

I think it’s better for you to not use a cookie based auth for Grafana’s API, it’s better to create a Service Account and use the Service Account Token that returns a Bearer tokent to be used easier on the Authorization Header of your request.

Yes @isaqueprofeta you’re right, I used service account token, it works, now there is new challenge, not sure if I can add it here, See I need to grant Editor permission to a team on a folder using service account token, But the script is failing to recognize folder itself? Script below:
import requests
import subprocess
import json

GRAFANA_URL = “http://localhost:3000
GRAFANA_API_KEY = “******************************************”

def run_curl_command(command):
result = subprocess.run(command, shell=True, capture_output=True, text=True)
if result.returncode == 0:
return result.stdout.strip()
else:
print(“Error running curl command:”, result.stderr)
return None

def get_folder_id(folder_name):
curl_command = f"curl -X GET -H ‘Authorization: Bearer {GRAFANA_API_KEY}’ -H ‘Content-Type: application/json’ ‘{GRAFANA_URL}/api/search?type=dash-folder&query={folder_name}’"
response = run_curl_command(curl_command)
print(“Folder search response:”, response)
if response:
folders = json.loads(response)
if folders:
return folders[0][“id”]
return None

def get_team_id(team_name):
curl_command = f"curl -X GET -H ‘Authorization: Bearer {GRAFANA_API_KEY}’ -H ‘Content-Type: application/json’ ‘{GRAFANA_URL}/api/teams/search?name={team_name}’"
response = run_curl_command(curl_command)
print(“Team search response:”, response)
if response:
teams = json.loads(response)[“teams”]
if teams:
return teams[0][“id”]
return None

FOLDER_NAME = “omg_apple”
TEAM_NAME = “omg_apple”

folder_id = get_folder_id(FOLDER_NAME)
team_id = get_team_id(TEAM_NAME)

if folder_id and team_id:
print(“Folder ID:”, folder_id)
print(“Team ID:”, team_id)

request_body = {
    "permission": "Editor",
    "userOrTeamId": team_id,
}


url = f"{GRAFANA_URL}/api/folders/{folder_id}/permissions"
print("URL for granting permission:", url)


response = requests.post(
    url,
    headers={"Authorization": f"Bearer {GRAFANA_API_KEY}"},
    json=request_body,
)


if response.status_code == 200:
    print("Permission granted successfully!")
else:
    print("Failed to grant permission:", response.status_code)

else:
print(“Failed to retrieve folder ID or team ID.”)

Output: Failed to grant permission: 404
Please help.

I tried with curl command:
curl -X POST http://localhost:3000/api/folders/181/permissions
-H “Authorization: Bearer SERVICE_ACCOUNT_TOKEN”
-H “Content-Type: application/json”
-d '{
“teamId”: 181,
“role”: “Editor”
}
output: {“message”:“folder not found”,“status”:“not-found”}
But the folder is present, I rechecked in Grafana UI, folder is present with folder Id: 181 but when we are trying with post method to change the permissions using the above command it gives error stating folder not found. Not sure why it is ending with error? What is the correct API endpoint? Please suggest how to rectify this and use in python script.

@sraghavendra1512 glad you get out of where you has stuck at first.

Two things.

First one, review your teamId: are you sure that both, team and folder got the same ID?

Second one, please pay more attention to the JSON format on the docs… Sometimes the API of GET VS POST are pretty different. In your case, there’s no “role” parameter. You’ll need to specify the “permission” parameter with an index. Since it’s for Editor, the parameter “permission” would get the number 2 that’s for Edit.

More information review it here: Folder Permissions HTTP API | Grafana documentation

Hope it helps.

Dear Raghavendra and Isaque,

if you are looking into accessing Grafana from Python, you may want to give the grafana-client package a chance.

If you are running into any issues with respect to your use cases, please let us know on the issue tracker, so we can improve the library according to your needs.

With kind regards,
Andreas.

NB: @usman.ahmad: Coming from [OSS tool] Write Grafana pre-build dashboards in Python - #2 by usman.ahmad, you may also want to add an item to the Howto section about it, linking to "grafana-client" - A client library for accessing the Grafana HTTP API, written in Python?

NB2: We’ve also just asked you in a PM to remove the “closed” status on this post, so we could continue adding release notes about significant updates, similar to Use "grafana-wtf" to search through all entities of a Grafana instance - #6 by amotl. grafana-client 4.0.0 has been released a few days ago, and we would like to share corresponding news with the community. Thanks!

1 Like