Page History
...
The following examples change a user’s role in various programming languages:Java | C# | Go | JavaScript | PHP | Python
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
package rest.code.examples;
import java.io.IOException;
import java.util.Random;
import org.apache.hc.client5.http.fluent.Content;
import org.apache.hc.client5.http.fluent.Request;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Create a user using the Yellowfin REST API
*/
public class UpdateUsersRole {
public static void main(String[] args) throws Exception {
String host = ""http://localhost:8080/Yellowfin"";
String restUsername = ""admin@yellowfin.com.au"";
String restPassword = ""test"";
String userToUpdate = ""user1@yellowfin.com.au"";
String token = generateToken(host, restUsername, restPassword);
String roleCode = retrieveRole(host, token);
Integer userIpId = retrieveUserIpIdForUsername(host, token, userToUpdate);
String updateUserPayload =
""{"" +
"" \""roleCode\"": \"""" + roleCode + ""\"""" +
""}"";
System.out.println(""Payload: "" + updateUserPayload);
Content c = Request.patch(host + ""/api/admin/users/"" + userIpId)
.addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong() + "", token="" + token)
.addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
.addHeader(""Content-Type"", ""application/json"")
.bodyString(updateUserPayload, null)
.execute().returnContent();
System.out.print(c.asString());
}
public static Integer retrieveUserIpIdForUsername(String host, String token, String userName) throws IOException {
Content c = Request.get(host + ""/api/rpc/users/user-details-by-username/"" + userName)
.addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong()+ "", token="" + token)
.addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
.addHeader(""Content-Type"", ""application/json"")
.execute().returnContent();
JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
JsonElement userIpJsonAttribute = jsonObject.get(""userId"");
Integer userIpId = userIpJsonAttribute.getAsInt();
return userIpId;
}
/*
* This function returns a list of roles in the Yellowfin instance and returns the first one
* in the list.
*/
public static String retrieveRole(String host, String token) throws IOException {
Content c = Request.get(host + ""/api/roles"")
.addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong()+ "", token="" + token)
.addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
.addHeader(""Content-Type"", ""application/json"")
.execute().returnContent();
JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
JsonElement rolesList = jsonObject.get(""items"");
JsonObject role = rolesList.getAsJsonArray().get(0).getAsJsonObject();
String roleCode = null;
if (role!=null) {
roleCode = role.get(""roleCode"").getAsString();
System.out.println(""RoleCode: "" + roleCode);
} else {
System.out.println(""Role not retrieved successfully"");
System.exit(-1);
}
return roleCode;
}
/*
* This function generates an access token for a user that will grant them access to
* call REST API endpoints.
*/
public static String generateToken(String host, String username, String password) throws IOException {
Content c = Request.post(host + ""/api/refresh-tokens"")
.addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong())
.addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
.addHeader(""Content-Type"", ""application/json"")
.bodyString(""{ \""userName\"": \""""+ username + ""\"",\""password\"": \""""+ password + ""\""}"", null)
.execute().returnContent();
JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
JsonElement accessToken = jsonObject.getAsJsonObject(""_embedded"").getAsJsonObject(""accessToken"").get(""securityToken"");
if (accessToken!=null) {
System.out.println(""Access Token: "" + accessToken);
} else {
System.out.println(""Token not retrieved successfully"");
System.exit(-1);
}
return accessToken.getAsString();
}
} |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace YellowfinAPIExamples
{
public class UpdateUsersRole
{
public static async Task Main(string[] args)
{
string host = ""http://localhost:8080/Yellowfin"";
string restUsername = ""admin@yellowfin.com.au"";
string restPassword = ""test"";
string userToUpdate = ""user1@yellowfin.com.au"";
string token = await GenerateToken(host, restUsername, restPassword);
string roleCode = await RetrieveRole(host, token);
int userIpId = await RetrieveUserIpIdForUsername(host, token, userToUpdate);
string updateUserPayload = $""{{ \""roleCode\"": \""{roleCode}\"" }}"";
Console.WriteLine(""Payload: "" + updateUserPayload);
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Patch, $""{host}/api/admin/users/{userIpId}"");
request.Headers.Add(""Authorization"", $""YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, nonce={new Random().NextInt64()}, token={token}"");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));
request.Content = new StringContent(updateUserPayload, System.Text.Encoding.UTF8, ""application/json"");
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
public static async Task<int> RetrieveUserIpIdForUsername(string host, string token, string userName)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, $""{host}/api/rpc/users/user-details-by-username/{userName}"");
request.Headers.Add(""Authorization"", $""YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, nonce={new Random().NextInt64()}, token={token}"");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
JObject jsonObject = JObject.Parse(responseContent);
int userIpId = jsonObject[""userId""].Value<int>();
return userIpId;
}
}
public static async Task<string> RetrieveRole(string host, string token)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, $""{host}/api/roles"");
request.Headers.Add(""Authorization"", $""YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, nonce={new Random().NextInt64()}, token={token}"");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
JObject jsonObject = JObject.Parse(responseContent);
JToken rolesList = jsonObject[""items""];
string roleCode = rolesList[0][""roleCode""].Value<string>();
Console.WriteLine(""RoleCode: "" + roleCode);
return roleCode;
}
}
public static async Task<string> GenerateToken(string host, string username, string password)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, $""{host}/api/refresh-tokens"");
request.Headers.Add(""Authorization"", $""YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, nonce={new Random().NextInt64()}"");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));
request.Content = new StringContent($""{{ \""userName\"": \""{username}\"", \""password\"": \""{password}\"" }}"", System.Text.Encoding.UTF8, ""application/json"");
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
JObject jsonObject = JObject.Parse(responseContent);
string accessToken = jsonObject[""_embedded""][""accessToken""][""securityToken""].Value<string>();
if (!string.IsNullOrEmpty(accessToken))
{
Console.WriteLine(""Access Token: "" + accessToken);
}
else
{
Console.WriteLine(""Token not retrieved successfully"");
Environment.Exit(-1);
}
return accessToken;
}
}
}
} |
Code Block | ||||
---|---|---|---|---|
| ||||
package main
import (
""bytes""
""encoding/json""
""fmt""
""io/ioutil""
""math/rand""
""net/http""
""time""
)
func main() {
host := ""http://localhost:8080/Yellowfin""
restUsername := ""admin@yellowfin.com.au""
restPassword := ""test""
userToUpdate := ""user1@yellowfin.com.au""
token, err := generateToken(host, restUsername, restPassword)
if err != nil {
fmt.Println(""Error generating token:"", err)
return
}
roleCode, err := retrieveRole(host, token)
if err != nil {
fmt.Println(""Error retrieving role:"", err)
return
}
userIpId, err := retrieveUserIpIdForUsername(host, token, userToUpdate)
if err != nil {
fmt.Println(""Error retrieving user IP ID:"", err)
return
}
updateUserPayload := fmt.Sprintf(`{ ""roleCode"": ""%s"" }`, roleCode)
fmt.Println(""Payload:"", updateUserPayload)
client := &http.Client{}
request, err := http.NewRequest(""PATCH"", fmt.Sprintf(""%s/api/admin/users/%d"", host, userIpId), bytes.NewBuffer([]byte(updateUserPayload)))
if err != nil {
fmt.Println(""Error creating request:"", err)
return
}
request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), rand.Int63(), token))
request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
request.Header.Set(""Content-Type"", ""application/json"")
response, err := client.Do(request)
if err != nil {
fmt.Println(""Error sending request:"", err)
return
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(""Error reading response body:"", err)
return
}
fmt.Println(string(responseBody))
}
func retrieveUserIpIdForUsername(host, token, userName string) (int, error) {
client := &http.Client{}
request, err := http.NewRequest(""GET"", fmt.Sprintf(""%s/api/rpc/users/user-details-by-username/%s"", host, userName), nil)
if err != nil {
return 0, err
}
request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), rand.Int63(), token))
request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
request.Header.Set(""Content-Type"", ""application/json"")
response, err := client.Do(request)
if err != nil {
return 0, err
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return 0, err
}
var jsonResponse map[string]interface{}
err = json.Unmarshal(responseBody, &jsonResponse)
if err != nil {
return 0, err
}
userIpId, ok := jsonResponse[""userId""].(float64)
if !ok {
return 0, fmt.Errorf(""error parsing userId from response"")
}
return int(userIpId), nil
}
func retrieveRole(host, token string) (string, error) {
client := &http.Client{}
request, err := http.NewRequest(""GET"", fmt.Sprintf(""%s/api/roles"", host), nil)
if err != nil {
return """", err
}
request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), rand.Int63(), token))
request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
request.Header.Set(""Content-Type"", ""application/json"")
response, err := client.Do(request)
if err != nil {
return """", err
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return """", err
}
var jsonResponse map[string]interface{}
err = json.Unmarshal(responseBody, &jsonResponse)
if err != nil {
return """", err
}
items, ok := jsonResponse[""items""].([]interface{})
if !ok || len(items) == 0 {
return """", fmt.Errorf(""error parsing roles from response"")
}
role, ok := items[0].(map[string]interface{})
if !ok {
return """", fmt.Errorf(""error parsing role from response"")
}
roleCode, ok := role[""roleCode""].(string)
if !ok {
return """", fmt.Errorf(""error parsing roleCode from role"")
}
fmt.Println(""RoleCode:"", roleCode)
return roleCode, nil
}
func generateToken(host, username, password string) (string, error) {
nonce := rand.Int63()
requestBody, err := json.Marshal(map[string]string{
""userName"": username,
""password"": password,
})
if err != nil {
return """", err
}
client := &http.Client{}
request, err := http.NewRequest(""POST"", fmt.Sprintf(""%s/api/refresh-tokens"", host), bytes.NewBuffer(requestBody))
if err != nil {
return """", err
}
request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d"", time.Now().UnixMilli(), nonce))
request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
request.Header.Set(""Content-Type"", ""application/json"")
response, err := client.Do(request)
if err != nil {
return """", err
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return """", err
}
var jsonResponse map[string]interface{}
err = json.Unmarshal(responseBody, &jsonResponse)
if err != nil {
return """", err
}
accessToken, ok := jsonResponse[""_embedded""].(map[string]interface{})[""accessToken""].(map[string]interface{})[""securityToken""].(string)
if !ok {
return """", fmt.Errorf(""token not retrieved successfully"")
}
fmt.Println(""Access Token:"", accessToken)
return accessToken, nil
} |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
const fetch = require('node-fetch');
async function main() {
const host = ""http://localhost:8080/Yellowfin"";
const restUsername = ""admin@yellowfin.com.au"";
const restPassword = ""test"";
const userToUpdate = ""user1@yellowfin.com.au"";
const token = await generateToken(host, restUsername, restPassword);
if (!token) {
console.error(""Failed to retrieve access token"");
return;
}
const roleCode = await retrieveRole(host, token);
if (!roleCode) {
console.error(""Failed to retrieve role"");
return;
}
const userIpId = await retrieveUserIpIdForUsername(host, token, userToUpdate);
if (!userIpId) {
console.error(""Failed to retrieve user IP ID"");
return;
}
const updateUserPayload = JSON.stringify({ roleCode: roleCode });
console.log(""Payload:"", updateUserPayload);
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)}, token=${token}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
try {
const response = await fetch(`${host}/api/admin/users/${userIpId}`, {
method: 'PATCH',
headers: headers,
body: updateUserPayload
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const responseBody = await response.text();
console.log(responseBody);
} catch (error) {
console.error(""Error:"", error.message);
}
}
async function retrieveUserIpIdForUsername(host, token, userName) {
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)}, token=${token}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
try {
const response = await fetch(`${host}/api/rpc/users/user-details-by-username/${userName}`, {
method: 'GET',
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const responseBody = await response.json();
const userIpId = responseBody.userId;
if (userIpId !== undefined) {
return userIpId;
} else {
console.error(""User IP ID not retrieved successfully"");
return null;
}
} catch (error) {
console.error(""Error:"", error.message);
return null;
}
}
async function retrieveRole(host, token) {
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)}, token=${token}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
try {
const response = await fetch(`${host}/api/roles`, {
method: 'GET',
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const responseBody = await response.json();
const rolesList = responseBody.items;
if (rolesList && rolesList.length > 0) {
const roleCode = rolesList[0].roleCode;
console.log(""RoleCode:"", roleCode);
return roleCode;
} else {
console.error(""Role not retrieved successfully"");
return null;
}
} catch (error) {
console.error(""Error:"", error.message);
return null;
}
}
async function generateToken(host, restUsername, restPassword) {
const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
const body = JSON.stringify({
userName: restUsername,
password: restPassword
});
try {
const response = await fetch(`${host}/api/refresh-tokens`, {
method: 'POST',
headers: headers,
body: body
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const jsonResponse = await response.json();
const accessToken = jsonResponse._embedded.accessToken.securityToken;
if (accessToken) {
console.log(`Access Token: ${accessToken}`);
return accessToken;
} else {
console.error(""Token not retrieved"");
return null;
}
} catch (error) {
console.error(""Error:"", error.message);
return null;
}
}
main(); |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<?php
function main() {
$host = ""http://localhost:8080/Yellowfin"";
$restUsername = ""admin@yellowfin.com.au"";
$restPassword = ""test"";
$userToUpdate = ""user1@yellowfin.com.au"";
try {
$token = generateToken($host, $restUsername, $restPassword);
} catch (Exception $e) {
echo ""Error generating token: "" . $e->getMessage();
return;
}
try {
$roleCode = retrieveRole($host, $token);
} catch (Exception $e) {
echo ""Error retrieving role: "" . $e->getMessage();
return;
}
try {
$userIpId = retrieveUserIpIdForUsername($host, $token, $userToUpdate);
} catch (Exception $e) {
echo ""Error retrieving user IP ID: "" . $e->getMessage();
return;
}
$updateUserPayload = json_encode(array(""roleCode"" => $roleCode));
echo ""Payload: "" . $updateUserPayload . ""\n"";
$nonce = mt_rand();
$headers = array(
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
);
try {
$response = httpRequest('PATCH', ""$host/api/admin/users/$userIpId"", $headers, $updateUserPayload);
echo $response;
} catch (Exception $e) {
echo ""Error sending request: "" . $e->getMessage();
}
}
function retrieveUserIpIdForUsername($host, $token, $username) {
$nonce = mt_rand();
$headers = array(
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
);
try {
$response = httpRequest('GET', ""$host/api/rpc/users/user-details-by-username/$username"", $headers);
$jsonResponse = json_decode($response, true);
$userIpId = $jsonResponse[""userId""];
return $userIpId;
} catch (Exception $e) {
throw new Exception(""Error retrieving user IP ID: "" . $e->getMessage());
}
}
function retrieveRole($host, $token) {
$nonce = mt_rand();
$headers = array(
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
);
try {
$response = httpRequest('GET', ""$host/api/roles"", $headers);
$jsonResponse = json_decode($response, true);
$rolesList = $jsonResponse[""items""];
if (!empty($rolesList)) {
$roleCode = $rolesList[0][""roleCode""];
echo ""RoleCode: "" . $roleCode . ""\n"";
return $roleCode;
} else {
throw new Exception(""Role not retrieved successfully"");
}
} catch (Exception $e) {
throw new Exception(""Error retrieving role: "" . $e->getMessage());
}
}
function generateToken($host, $restUsername, $restPassword) {
$nonce = mt_rand();
$requestBody = json_encode(array(
""userName"" => $restUsername,
""password"" => $restPassword
));
$headers = array(
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
);
try {
$response = httpRequest('POST', ""$host/api/refresh-tokens"", $headers, $requestBody);
$jsonResponse = json_decode($response, true);
if (isset($jsonResponse[""_embedded""][""accessToken""][""securityToken""])) {
$accessToken = $jsonResponse[""_embedded""][""accessToken""][""securityToken""];
echo ""Access Token: "" . $accessToken . ""\n"";
return $accessToken;
} else {
throw new Exception(""Token not retrieved successfully"");
}
} catch (Exception $e) {
throw new Exception(""Error generating token: "" . $e->getMessage());
}
}
function httpRequest($method, $url, $headers, $data = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if ($data !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception('Error: ' . curl_error($ch));
}
curl_close($ch);
return $response;
}
main();
?> |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
import json
import random
import time
import requests
def main():
host = ""http://localhost:8080/Yellowfin""
rest_username = ""admin@yellowfin.com.au""
rest_password = ""test""
user_to_update = ""user1@yellowfin.com.au""
try:
token = generate_token(host, rest_username, rest_password)
except Exception as e:
print(f""Error generating token: {e}"")
return
try:
role_code = retrieve_role(host, token)
except Exception as e:
print(f""Error retrieving role: {e}"")
return
try:
user_ip_id = retrieve_user_ip_id_for_username(host, token, user_to_update)
except Exception as e:
print(f""Error retrieving user IP ID: {e}"")
return
update_user_payload = json.dumps({
""roleCode"": role_code
})
print(""Payload:"", update_user_payload)
nonce = random.randint(0, 2 ** 63 - 1)
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
try:
response = requests.patch(f""{host}/api/admin/users/{user_ip_id}"", headers=headers, data=update_user_payload)
response.raise_for_status()
print(response.text)
except requests.RequestException as e:
print(f""Error sending request: {e}"")
def retrieve_user_ip_id_for_username(host, token, username):
nonce = random.randint(0, 2 ** 63 - 1)
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
try:
response = requests.get(f""{host}/api/rpc/users/user-details-by-username/{username}"", headers=headers)
response.raise_for_status()
json_response = response.json()
user_ip_id = json_response[""userId""]
return user_ip_id
except requests.RequestException as e:
print(f""Error retrieving user IP ID: {e}"")
return None
def retrieve_role(host, token):
nonce = random.randint(0, 2 ** 63 - 1)
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
try:
response = requests.get(f""{host}/api/roles"", headers=headers)
response.raise_for_status()
json_response = response.json()
roles_list = json_response[""items""]
if roles_list:
role_code = roles_list[0][""roleCode""]
print(""RoleCode:"", role_code)
return role_code
else:
print(""Role not retrieved successfully"")
return None
except requests.RequestException as e:
print(f""Error retrieving role: {e}"")
return None
def generate_token(host, rest_username, rest_password):
nonce = random.randint(0, 2 ** 63 - 1)
request_body = json.dumps({
""userName"": rest_username,
""password"": rest_password
})
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
try:
response = requests.post(f""{host}/api/refresh-tokens"", headers=headers, data=request_body)
response.raise_for_status()
json_response = response.json()
access_token = json_response[""_embedded""][""accessToken""][""securityToken""]
print(""Access Token:"", access_token)
return access_token
except requests.RequestException as e:
print(f""Error generating token: {e}"")
return None
if __name__ == ""__main__"":
main() |
Change a user’s password
A user's password can generally only be updated by a user themselves, or by an administrator who has sufficient rights. Passwords are updated by calling PUT /api/admin/users/{userId}/password (https://developers.yellowfinbi.com/dev/api-docs/current/#operation/setUserPasswordAdmin ).
...