Page History
...
There are two main approaches to user synchronization, the difference between the approaches relates to when the user synchronization takes place.:
- Linked with an existing user synchronization process
In this approach, a user is created at the same time as a user is created in the external system. This means the user is created before the user attempts to login to Yellowfin for the first time. Updates to the user in the external system would also be propagated to Yellowfin via services immediately. - On-Demand (or Lazy) synchronization
The on-demand approach will only create a user in Yellowfin as they are about to login for the first time. This can be done in conjunction with an SSO login process. A common pattern is to have the SSO code perform the following process when the user first attempts to log in: -
...
- Check whether the user attempting to log in to Yellowfin exists
...
- If the user does not exist in Yellowfin, create the user
...
- If the user does exist in Yellowfin, update the user if any details have changed
...
- Check that the user has the correct security access
...
- If the user access differs from the external system, then adjust the user's group membership so that it is correct.
...
- Perform SSO, and direct the user into Yellowfin.
One issue with on-demand synchronization is that group membership will only be updated when a user logs in. If the user is a recipient of broadcasts via group membership, then they may continue to receive broadcasts after they have been removed from the group in an external system until they login. However an administrator can remove a user from a group manually within Yellowfin.
When using REST services to create and manage users, a user JSON model needs to be provided. This is the format of the User JSON model:
Code Block |
---|
{ |
...
"userId": |
...
"user1", |
...
"emailAddress": " |
...
user1@yellowfin.com.au", |
...
"roleCode": "Consumer & Collaborator", |
...
"password": "secr3t", |
...
"firstName": "User", |
...
"lastName": "One", |
...
"languageCode": "EN", |
...
"timeZoneCode": "AUSTRALIA/SYDNEY", |
...
} |
When editing or creating users, populate the model with required attributes. Users can be given a First Name, Last Name, Username and Email address, as well as specifying language and timezone settings.
Users are also assigned a role which determines their access to various functions within the application. Available Roles can be requested via another API call ( https://developers.yellowfinbi.com/dev/api-docs/current/#operation/getRoles ).
Retrieving a User
Fetch the details of an existing user from the application. This can also be used to check whether a user already exists. Retrieve user details by querying GET /api/rpc/users/user-details-by-username/{user-name}( https://developers.yellowfinbi.com/dev/api-docs/current/#operation/user-details-by-username ) Get a User by Username.
The following examples illustrate how to retrieve an existing user (via username) in various programming languages.
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; /** * Retrieve a user using the Yellowfin REST API */ public class RetrieveAUser { public static void main(String[] args) throws Exception { String host = "http://localhost:8080/yellowfinHead"; String restUsername = "admin@yellowfin.com.au"; String restPassword = "test"; String userToRetrieve = "admin@yellowfin.com.au"; String token = generateToken(host, restUsername, restPassword); System.out.println("Retrieving User: " + userToRetrieve); Content c = Request.get(host + "/api/rpc/users/user-details-by-username/" + userToRetrieve) .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(); System.out.print(c.asString()); } 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 | ||||||
---|---|---|---|---|---|---|
| ||||||
namespace YellowfinAPIExamples;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class RetrieveAUser
{
static async Task Main(string[] args)
{
string host = "http://localhost:8080/yellowfinHead";
string restUsername = "admin@yellowfin.com.au";
string restPassword = "test";
string userToRetrieve = "admin@yellowfin.com.au";
string token = await GenerateToken(host, restUsername, restPassword);
Console.WriteLine("Retrieving User: " + userToRetrieve);
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("YELLOWFIN", "ts=" + DateTimeOffset.Now.ToUnixTimeMilliseconds() + " , nonce=" + new Random().NextInt64() + ", token=" + token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));
HttpResponseMessage response = await httpClient.GetAsync(host + "/api/rpc/users/user-details-by-username/" + userToRetrieve);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine("Failed to retrieve user details. Status code: " + response.StatusCode);
}
}
}
static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
{
using (var client = new HttpClient())
{
// Generate nonce
long nonce = new Random().NextInt64();
// Create HTTP request
var request = new HttpRequestMessage(HttpMethod.Post, host + "/api/refresh-tokens");
request.Headers.Add("Authorization", "YELLOWFIN ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + ", nonce=" + nonce);
request.Headers.Add("Accept", "application/vnd.yellowfin.api-v1+json");
request.Content = new StringContent(
JsonConvert.SerializeObject(new { userName = restUsername, password = restPassword }),
MediaTypeHeaderValue.Parse("application/json")
);
// Send request and get response
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
// Parse JSON response
JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString();
if (!string.IsNullOrEmpty(accessToken))
{
Console.WriteLine("Access Token: " + accessToken);
}
else
{
Console.WriteLine("Token not retrieved");
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"
userToRetrieve := "admin@yellowfin.com.au"
token, err := generateToken(host, restUsername, restPassword)
if err != nil {
fmt.Println("Error generating token:", err)
return
}
fmt.Println("Retrieving User:", userToRetrieve)
client := &http.Client{}
req, err := http.NewRequest("GET", host+"/api/rpc/users/user-details-by-username/"+userToRetrieve, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
nonce := rand.Int63()
req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixMilli(), nonce, token))
req.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json")
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
fmt.Println(string(body))
}
func generateToken(host, restUsername, restPassword string) (string, error) {
// Generate nonce
nonce := rand.Int63()
// Create request body
requestBody, err := json.Marshal(map[string]string{
"userName": restUsername,
"password": restPassword,
})
if err != nil {
fmt.Println("Error marshaling request body:", err)
return "", err
}
// Create HTTP client
client := &http.Client{}
// Create HTTP request
request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
if err != nil {
fmt.Println("Error creating request:", err)
return "", err
}
// Add request headers
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")
// Send HTTP request
response, err := client.Do(request)
if err != nil {
fmt.Println("Error sending request:", err)
return "", err
}
defer response.Body.Close()
// Read response body
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return "", err
}
// Parse JSON response
var jsonResponse map[string]interface{}
err = json.Unmarshal(responseBody, &jsonResponse)
if err != nil {
fmt.Println("Error parsing JSON response:", err)
return "", err
}
// Get access token from response
accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
if !ok {
fmt.Println("Token not retrieved")
return "", fmt.Errorf("Token not retrieved successfully")
}
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 userToRetrieve = "admin@yellowfin.com.au";
try {
const token = await generateToken(host, restUsername, restPassword);
console.log("Retrieving User:", userToRetrieve);
const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
const response = await fetch(`${host}/api/rpc/users/user-details-by-username/${userToRetrieve}`, {
method: 'GET',
headers: headers
});
const userResponse = await response.json();
console.log(JSON.stringify(userResponse));
} catch (error) {
console.error("Error:", error.response ? error.response.data : error.message);
}
}
async function generateToken(host, restUsername, restPassword) {
// Generate nonce
const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
// Create request headers
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
// Create request body
const body = JSON.stringify({
userName: restUsername,
password: restPassword
});
try {
// Make POST request
const response = await fetch(`${host}/api/refresh-tokens`, {
method: 'POST',
headers: headers,
body: body
});
// Check if request was successful
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse JSON response
const jsonResponse = await response.json();
const accessToken = jsonResponse._embedded.accessToken.securityToken;
if (accessToken) {
console.log(`Access Token: ${accessToken}`);
} else {
console.log("Token not retrieved");
}
return accessToken;
} 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";
$userToRetrieve = "admin@yellowfin.com.au";
try {
$token = generateToken($host, $restUsername, $restPassword);
echo "Retrieving User: $userToRetrieve\n";
$nonce = mt_rand();
$headers = [
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
];
$url = "$host/api/rpc/users/user-details-by-username/$userToRetrieve";
$response = httpRequest('GET', $url, $headers);
echo $response . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
function generateToken($host, $restUsername, $restPassword) {
// Generate nonce
$nonce = mt_rand();
// Create request body
$requestBody = json_encode(array(
"userName" => $restUsername,
"password" => $restPassword
));
// Create request headers
$headers = array(
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
);
$response = httpRequest('POST', "$host/api/refresh-tokens", $headers, $requestBody);
// Parse JSON response
$jsonResponse = json_decode($response, true);
// Get access token from response
if (isset($jsonResponse["_embedded"]["accessToken"]["securityToken"])) {
$accessToken = $jsonResponse["_embedded"]["accessToken"]["securityToken"];
echo "Access Token: " . $accessToken;
return $accessToken;
} else {
throw new Exception("Token not retrieved successfully");
}
}
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/yellowfinHead"
rest_username = "admin@yellowfin.com.au"
rest_password = "test"
user_to_retrieve = "admin@yellowfin.com.au"
try:
token = generate_token(host, rest_username, rest_password)
print("Retrieving User:", user_to_retrieve)
nonce = str(random.randint(1, 1000000000))
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
url = f"{host}/api/rpc/users/user-details-by-username/{user_to_retrieve}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
print(response.text)
else:
print("Failed to retrieve user details. Status code:", response.status_code)
except Exception as e:
print("Error:", e)
def generate_token(host, rest_username, rest_password):
nonce = random.randint(0, 2 ** 63 - 1)
# Create request body
request_body = json.dumps({
"userName": rest_username,
"password": rest_password
})
# Create request headers
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
# Send HTTP request
response = requests.post(host + "/api/refresh-tokens", headers=headers, data=request_body)
# Check response status
if response.status_code == 200:
# Parse JSON response
json_response = response.json()
access_token = json_response["_embedded"]["accessToken"]["securityToken"]
print("Access Token:", access_token)
return access_token
else:
raise Exception("Token not retrieved successfully")
if __name__ == "__main__":
main() |
Creating a User
Create a new user by providing an array of user models to POST /api/admin/users Create User Admin. Pass multiple user models to create multiple users simultaneously.
The following examples create a new user in various programming languages.
This Java Code example uses Apache HTTP Client and GSON for handling REST calls and JSON serialization.
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 CreateAUser {
public static void main(String[] args) throws Exception {
String host = "http://localhost:8080/Yellowfin";
String restUsername = "admin@yellowfin.com.au";
String restPassword = "test";
String createUserPayload = "[ {" +
" \"userId\": \"user1\"," +
" \"emailAddress\": \"user1@yellowfin.com.au\"," +
" \"roleCode\": \"Consumer & Collaborator\"," +
" \"password\": \"test\"," +
" \"firstName\": \"User\"," +
" \"lastName\": \"One\"," +
" \"languageCode\": \"EN\"," +
" \"timeZoneCode\": \"AUSTRALIA/SYDNEY\" +
" } ]";
String token = generateToken(host, restUsername, restPassword);
System.out.println("Payload: " + createUserPayload);
Content c = Request.post(host + "/api/admin/users")
.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(createUserPayload, null)
.execute().returnContent();
System.out.print(c.asString());
}
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 | ||||||
---|---|---|---|---|---|---|
| ||||||
namespace YellowfinAPIExamples;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class CreateAUser
{
static async Task Main(string[] args)
{
string host = "http://localhost:8080/Yellowfin";
string restUsername = "admin@yellowfin.com.au";
string restPassword = "test";
string createUserPayload = "[ {" +
" \"userId\": \"user1\"," +
" \"emailAddress\": \"user1@yellowfin.com.au\"," +
" \"roleCode\": \"Consumer & Collaborator\"," +
" \"password\": \"test\"," +
" \"firstName\": \"User\"," +
" \"lastName\": \"One\"," +
" \"languageCode\": \"EN\"," +
" \"timeZoneCode\": \"AUSTRALIA/SYDNEY\" +
" } ]";
string token = await GenerateToken(host, restUsername, restPassword);
Console.WriteLine("Payload: " + createUserPayload);
using (HttpClient client = new HttpClient())
{
long nonce = new Random().NextInt64();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, host + "/api/admin/users");
request.Headers.Add("Authorization", "YELLOWFIN ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + ", nonce=" + nonce + ", token=" + token);
request.Headers.Add("Accept", "application/vnd.yellowfin.api-v1+json");
request.Content = new StringContent(createUserPayload, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(request);
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
{
using (var client = new HttpClient())
{
// Generate nonce
long nonce = new Random().NextInt64();
// Create HTTP request
var request = new HttpRequestMessage(HttpMethod.Post, host + "/api/refresh-tokens");
request.Headers.Add("Authorization", "YELLOWFIN ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + ", nonce=" + nonce);
request.Headers.Add("Accept", "application/vnd.yellowfin.api-v1+json");
request.Content = new StringContent(
JsonConvert.SerializeObject(new { userName = restUsername, password = restPassword }),
MediaTypeHeaderValue.Parse("application/json")
);
// Send request and get response
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
// Parse JSON response
JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString();
if (!string.IsNullOrEmpty(accessToken))
{
Console.WriteLine("Access Token: " + accessToken);
}
else
{
Console.WriteLine("Token not retrieved");
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"
createUserPayload := `[{
"userId": "user1",
"emailAddress": "user1@yellowfin.com.au",
"roleCode": "Consumer & Collaborator",
"password": "test",
"firstName": "User",
"lastName": "One",
"languageCode": "EN",
"timeZoneCode": "AUSTRALIA/SYDNEY"
}]`
token, err := generateToken(host, restUsername, restPassword)
if err != nil {
fmt.Println("Error generating token:", err)
return
}
fmt.Println("Payload:", createUserPayload)
client := &http.Client{}
request, err := http.NewRequest("POST", host+"/api/admin/users", bytes.NewBuffer([]byte(createUserPayload)))
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()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
fmt.Println(string(body))
}
func generateToken(host, restUsername, restPassword string) (string, error) {
// Generate nonce
nonce := rand.Int63()
// Create request body
requestBody, err := json.Marshal(map[string]string{
"userName": restUsername,
"password": restPassword,
})
if err != nil {
fmt.Println("Error marshaling request body:", err)
return ", err
}
// Create HTTP client
client := &http.Client{}
// Create HTTP request
request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
if err != nil {
fmt.Println("Error creating request:", err)
return ", err
}
// Add request headers
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")
// Send HTTP request
response, err := client.Do(request)
if err != nil {
fmt.Println("Error sending request:", err)
return ", err
}
defer response.Body.Close()
// Read response body
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return ", err
}
// Parse JSON response
var jsonResponse map[string]interface{}
err = json.Unmarshal(responseBody, &jsonResponse)
if err != nil {
fmt.Println("Error parsing JSON response:", err)
return ", err
}
// Get access token from response
accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
if !ok {
fmt.Println("Token not retrieved")
return ", fmt.Errorf("Token not retrieved successfully")
}
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 createUserPayload = JSON.stringify([{
userId: "user1",
emailAddress: "user1@yellowfin.com.au",
roleCode: "Consumer & Collaborator",
password: "test",
firstName: "User",
lastName: "One",
languageCode: "EN",
timeZoneCode: "AUSTRALIA/SYDNEY"
}]);
const token = await generateToken(host, restUsername, restPassword);
if (token === null) {
console.error("Failed to retrieve access token");
return;
}
console.log("Payload:", createUserPayload);
const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
try {
const response = await fetch(`${host}/api/admin/users`, {
method: 'POST',
headers: headers,
body: createUserPayload
});
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 generateToken(host, restUsername, restPassword) {
// Generate nonce
const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
// Create request headers
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
// Create request body
const body = JSON.stringify({
userName: restUsername,
password: restPassword
});
try {
// Make POST request
const response = await fetch(`${host}/api/refresh-tokens`, {
method: 'POST',
headers: headers,
body: body
});
// Check if request was successful
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Parse JSON response
const jsonResponse = await response.json();
const accessToken = jsonResponse._embedded.accessToken.securityToken;
if (accessToken) {
console.log(`Access Token: ${accessToken}`);
} else {
console.log("Token not retrieved");
}
return accessToken;
} 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";
$createUserPayload = json_encode(array(
array(
"userId" => "user1",
"emailAddress" => "user1@yellowfin.com.au",
"roleCode" => "Consumer & Collaborator",
"password" => "test",
"firstName" => "User",
"lastName" => "One",
"languageCode" => "EN",
"timeZoneCode" => "AUSTRALIA/SYDNEY"
)
));
try {
$token = generateToken($host, $restUsername, $restPassword);
} catch (Exception $e) {
echo "Error generating token: " . $e->getMessage();
return;
}
echo "Payload: " . $createUserPayload . "\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('POST', "$host/api/admin/users", $headers, $createUserPayload);
echo $response;
} catch (Exception $e) {
echo "Error sending request: " . $e->getMessage();
}
}
function generateToken($host, $restUsername, $restPassword) {
// Generate nonce
$nonce = mt_rand();
// Create request body
$requestBody = json_encode(array(
"userName" => $restUsername,
"password" => $restPassword
));
// Create request headers
$headers = array(
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
);
$response = httpRequest('POST', "$host/api/refresh-tokens", $headers, $requestBody);
// Parse JSON response
$jsonResponse = json_decode($response, true);
// Get access token from response
if (isset($jsonResponse["_embedded"]["accessToken"]["securityToken"])) {
$accessToken = $jsonResponse["_embedded"]["accessToken"]["securityToken"];
echo "Access Token: " . $accessToken;
return $accessToken;
} else {
throw new Exception("Token not retrieved successfully");
}
}
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"
create_user_payload = json.dumps([{
"userId": "user1",
"emailAddress": "user1@yellowfin.com.au",
"roleCode": "Consumer & Collaborator",
"password": "test",
"firstName": "User",
"lastName": "One",
"languageCode": "EN",
"timeZoneCode": "AUSTRALIA/SYDNEY"
}])
try:
token = generate_token(host, rest_username, rest_password)
except Exception as e:
print(f"Error generating token: {e}")
return
print("Payload:", create_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.post(host + "/api/admin/users", headers=headers, data=create_user_payload)
response.raise_for_status()
print(response.text)
except requests.RequestException as e:
print(f"Error sending request: {e}")
def generate_token(host, rest_username, rest_password):
nonce = random.randint(0, 2 ** 63 - 1)
# Create request body
request_body = json.dumps({
"userName": rest_username,
"password": rest_password
})
# Create request headers
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
# Send HTTP request
response = requests.post(host + "/api/refresh-tokens", headers=headers, data=request_body)
# Check response status
if response.status_code == 200:
# Parse JSON response
json_response = response.json()
access_token = json_response["_embedded"]["accessToken"]["securityToken"]
print("Access Token:", access_token)
return access_token
else:
raise Exception("Token not retrieved successfully")
if __name__ == "__main__":
main() |
Updating a User
Updating a user uses the same JSON model specified above. A model including the required changes can be consumed by PATCH /api/admin/users/{userId} Update a User, where the {userId} is the integer identifier, as returned by GET /api/rpc/users/user-details-by-username/{user-name}
The update end-point supports only a single User JSON model, compared to the create user end-point which can accept an array of User JSON models.
The following examples update an existing user in various programming languages:
This Java Code example uses Apache HTTP Client and GSON for handling REST calls and JSON serialization.
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 UpdateAUser {
public static void main(String[] args) throws Exception {
String host = "http://localhost:8080/yellowfinHead";
String restUsername = "admin@yellowfin.com.au";
String restPassword = "test";
Integer userIp = 13235;
String updateUserPayload =
"{" +
" \"emailAddress\": \"user1@yellowfin.com.au\"," +
" \"roleCode\": \"Consumer & Collaborator\"," +
" \"password\": \"test\"," +
" \"firstName\": \"User\"," +
" \"lastName\": \"Two\"," +
" \"languageCode\": \"EN\"," +
" \"timeZoneCode\": \"AUSTRALIA/SYDNEY\" +
"}";
String token = generateToken(host, restUsername, restPassword);
System.out.println("Payload: " + updateUserPayload);
Content c = Request.patch(host + "/api/admin/users/" + userIp)
.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 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 | ||||||
---|---|---|---|---|---|---|
| ||||||
namespace YellowfinAPIExamples
{
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class UpdateAUser
{
static async Task Main(string[] args)
{
string host = "http://localhost:8080/yellowfinHead";
string restUsername = "admin@yellowfin.com.au";
string restPassword = "test";
int userIp = 13235;
string updateUserPayload = JsonConvert.SerializeObject(new
{
emailAddress = "user1@yellowfin.com.au",
roleCode = "Consumer & Collaborator",
password = "test",
firstName = "User",
lastName = "Two",
languageCode = "EN",
timeZoneCode = "AUSTRALIA/SYDNEY"
});
string token = await GenerateToken(host, restUsername, restPassword);
using (var client = new HttpClient())
{
// Generate nonce
long nonce = new Random().NextInt64();
// Create HTTP request
var request = new HttpRequestMessage(HttpMethod.Patch, $"{host}/api/admin/users/{userIp}");
request.Headers.Add("Authorization", $"YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()} , nonce={nonce}, 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");
// Send request and get response
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
}
public static async Task<string> GenerateToken(string host, string username, string password)
{
using (var client = new HttpClient())
{
// Generate nonce
long nonce = new Random().NextInt64();
// Create HTTP request
var request = new HttpRequestMessage(HttpMethod.Post, $"{host}/api/refresh-tokens");
request.Headers.Add("Authorization", $"YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()} , nonce={nonce}");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));
request.Content = new StringContent(
JsonConvert.SerializeObject(new { userName = username, password = password }),
System.Text.Encoding.UTF8,
"application/json"
);
// Send request and get response
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
// Parse JSON response
JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString();
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/yellowfinHead"
restUsername := "admin@yellowfin.com.au"
restPassword := "test"
userIp := 13235
updateUserPayload := map[string]string{
"emailAddress": "user1@yellowfin.com.au",
"roleCode": "Consumer & Collaborator",
"password": "test",
"firstName": "User",
"lastName": "Two",
"languageCode": "EN",
"timeZoneCode": "AUSTRALIA/SYDNEY",
}
token, err := generateToken(host, restUsername, restPassword)
if err != nil {
fmt.Println("Error generating token:", err)
return
}
payloadBytes, err := json.Marshal(updateUserPayload)
if err != nil {
fmt.Println("Error marshaling payload:", err)
return
}
nonce := rand.Int63()
client := &http.Client{}
request, err := http.NewRequest("PATCH", fmt.Sprintf("%s/api/admin/users/%d", host, userIp), bytes.NewBuffer(payloadBytes))
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(), nonce, 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.Print(string(responseBody))
}
func generateToken(host, username, password string) (string, error) {
requestBody, err := json.Marshal(map[string]string{
"userName": username,
"password": password,
})
if err != nil {
return ", fmt.Errorf("error marshaling request body: %v", err)
}
nonce := rand.Int63()
client := &http.Client{}
request, err := http.NewRequest("POST", fmt.Sprintf("%s/api/refresh-tokens", host), bytes.NewBuffer(requestBody))
if err != nil {
return ", fmt.Errorf("error creating request: %v", 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 ", fmt.Errorf("error sending request: %v", err)
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return ", fmt.Errorf("error reading response body: %v", err)
}
var jsonResponse map[string]interface{}
err = json.Unmarshal(responseBody, &jsonResponse)
if err != nil {
return ", fmt.Errorf("error parsing JSON response: %v", err)
}
accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
if !ok {
return ", fmt.Errorf("token not retrieved")
}
fmt.Println("Access Token:", accessToken)
return accessToken, nil
} |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
const fetch = require('node-fetch');
async function main() {
const host = "http://localhost:8080/yellowfinHead";
const restUsername = "admin@yellowfin.com.au";
const restPassword = "test";
const userIp = 13235;
const updateUserPayload = JSON.stringify({
emailAddress: "user1@yellowfin.com.au",
roleCode: "Consumer & Collaborator",
password: "test",
firstName: "User",
lastName: "Four",
languageCode: "EN",
timeZoneCode: "AUSTRALIA/SYDNEY"
});
const token = await generateToken(host, restUsername, restPassword);
console.log("Payload:", updateUserPayload);
const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
try {
const response = await fetch(`${host}/api/admin/users/${userIp}`, {
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 generateToken(host, username, password) {
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: username,
password: password
});
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.log("Token not retrieved successfully");
process.exit(-1);
}
} catch (error) {
console.error("Error:", error.message);
process.exit(-1);
}
}
main(); |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<?php
function main()
{
$host = "http://localhost:8080/yellowfinHead";
$restUsername = "admin@yellowfin.com.au";
$restPassword = "test";
$userIp = 13235;
$updateUserPayload = json_encode(array(
"emailAddress" => "user1@yellowfin.com.au",
"roleCode" => "Consumer & Collaborator",
"password" => "test",
"firstName" => "User",
"lastName" => "Two",
"languageCode" => "EN",
"timeZoneCode" => "AUSTRALIA/SYDNEY"
));
$token = generateToken($host, $restUsername, $restPassword);
echo "Payload: " . $updateUserPayload . PHP_EOL;
$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'
);
$response = httpRequest('PATCH', "$host/api/admin/users/$userIp", $headers, $updateUserPayload);
echo $response . PHP_EOL;
}
function generateToken($host, $username, $password)
{
$nonce = mt_rand();
$headers = array(
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
);
$body = json_encode(array(
"userName" => $username,
"password" => $password
));
$response = httpRequest('POST', "$host/api/refresh-tokens", $headers, $body);
$jsonResponse = json_decode($response, true);
if (isset($jsonResponse["_embedded"]["accessToken"]["securityToken"])) {
$accessToken = $jsonResponse["_embedded"]["accessToken"]["securityToken"];
echo "Access Token: " . $accessToken . PHP_EOL;
return $accessToken;
} else {
echo "Token not retrieved successfully" . PHP_EOL;
exit(-1);
}
}
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/yellowfinHead"
rest_username = "admin@yellowfin.com.au"
rest_password = "test"
user_ip = 13235
update_user_payload = json.dumps({
"emailAddress": "user1@yellowfin.com.au",
"roleCode": "Consumer & Collaborator",
"password": "test",
"firstName": "User",
"lastName": "Seven",
"languageCode": "EN",
"timeZoneCode": "AUSTRALIA/SYDNEY"
})
token = generate_token(host, rest_username, rest_password)
print("Payload:", update_user_payload)
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={random.randint(0, 2**63 - 1)}, token={token}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
response = requests.patch(f"{host}/api/admin/users/{user_ip}", headers=headers, data=update_user_payload)
print(response.text)
def generate_token(host, username, password):
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={random.randint(0, 2**63 - 1)}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
body = json.dumps({
"userName": username,
"password": password
})
response = requests.post(f"{host}/api/refresh-tokens", headers=headers, data=body)
if response.status_code == 200:
json_response = response.json()
access_token = json_response["_embedded"]["accessToken"]["securityToken"]
print("Access Token:", access_token)
return access_token
else:
print("Token not retrieved successfully")
exit(-1)
if __name__ == "__main__":
main()
|
Changing a user’s role
A user’s role can be updated with the standard update end-point. This is done by setting the roleCode in the User JSON model when calling PATCH /api/admin/users/{userId} Update a User.
The following example introduces the GET /api/roles end-point to retrieve available roles. The example code will modify a user’s role to the first role returned by GET /api/roles.
The following examples change a user’s role in various programming languages:
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 Update a User's Password.
The payload for this REST call can consist of a simple JSON entry that includes the password:
{ "password": "test"}
The following examples update an existing user in various programming languages.
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 UpdateUsersPassword {
public static void main(String[] args) throws Exception {
String host = "http://localhost/yellowfinHead";
String restUsername = "admin@yellowfin.com.au";
String restPassword = "test";
String userToUpdate = "user1@yellowfin.com.au";
String newPassword = "test";
String token = generateToken(host, restUsername, restPassword);;
Integer userIpId = retrieveUserIpIdForUsername(host, token, userToUpdate);
String updatePasswordPayload =
"{" +
" \"password\": \" + newPassword + "\" +
"}";
System.out.println("Payload: " + updatePasswordPayload);
Content c = Request.put(host + "/api/admin/users/" + userIpId + "/password")
.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(updatePasswordPayload, 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 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 | ||||||
---|---|---|---|---|---|---|
| ||||||
namespace YellowfinAPIExamples
{
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class UpdateUsersPassword
{
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 newPassword = "test";
string token = await GenerateToken(host, restUsername, restPassword);
int userIpId = await RetrieveUserIpIdForUsername(host, token, userToUpdate);
string updatePasswordPayload = JsonConvert.SerializeObject(new { password = newPassword });
Console.WriteLine("Payload: " + updatePasswordPayload);
long nonce = new Random().NextInt64();
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("YELLOWFIN", $"ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()} , nonce={nonce}, token={token}");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, $"{host}/api/admin/users/{userIpId}/password")
{
Content = new StringContent(updatePasswordPayload, System.Text.Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine("Failed to update user password. Status code: " + response.StatusCode);
}
}
}
static async Task<int> RetrieveUserIpIdForUsername(string host, string token, string userName)
{
long nonce = new Random().NextInt64();
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("YELLOWFIN", $"ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()} , nonce={nonce}, token={token}");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));
HttpResponseMessage response = await httpClient.GetAsync($"{host}/api/rpc/users/user-details-by-username/{userName}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseBody);
int userIpId = jsonObject["userId"].Value<int>();
return userIpId;
}
else
{
throw new Exception("Failed to retrieve user IP ID. Status code: " + response.StatusCode);
}
}
}
static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
{
using (var client = new HttpClient())
{
long nonce = new Random().NextInt64();
var request = new HttpRequestMessage(HttpMethod.Post, $"{host}/api/refresh-tokens");
request.Headers.Add("Authorization", $"YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, nonce={nonce}");
request.Headers.Add("Accept", "application/vnd.yellowfin.api-v1+json");
request.Content = new StringContent(
JsonConvert.SerializeObject(new { userName = restUsername, password = restPassword }),
System.Text.Encoding.UTF8,
"application/json"
);
HttpResponseMessage response = await client.SendAsync(request);
string responseContent = await response.Content.ReadAsStringAsync();
JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
string accessToken = jsonObject["_embedded"]["accessToken"]["securityToken"].ToString();
if (!string.IsNullOrEmpty(accessToken))
{
Console.WriteLine("Access Token: " + accessToken);
}
else
{
Console.WriteLine("Token not retrieved");
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"
newPassword := "test"
token, err := generateToken(host, restUsername, restPassword)
if err != nil {
fmt.Println("Error generating token:", err)
return
}
userIpId, err := retrieveUserIpIdForUsername(host, token, userToUpdate)
if err != nil {
fmt.Println("Error retrieving user IP ID:", err)
return
}
updatePasswordPayload := map[string]string{
"password": newPassword,
}
payloadBytes, err := json.Marshal(updatePasswordPayload)
if err != nil {
fmt.Println("Error marshaling payload:", err)
return
}
fmt.Println("Payload:", string(payloadBytes))
nonce := rand.Int63()
client := &http.Client{}
req, err := http.NewRequest("PUT", fmt.Sprintf("%s/api/admin/users/%d/password", host, userIpId), bytes.NewBuffer(payloadBytes))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixMilli(), nonce, token))
req.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json")
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
fmt.Println(string(body))
}
func retrieveUserIpIdForUsername(host, token, userName string) (int, error) {
nonce := rand.Int63()
client := &http.Client{}
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/rpc/users/user-details-by-username/%s", host, userName), nil)
if err != nil {
fmt.Println("Error creating request:", err)
return 0, err
}
req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixMilli(), nonce, token))
req.Header.Set("Accept", "application/vnd.yellowfin.api-v1+json")
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return 0, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return 0, err
}
var jsonResponse map[string]interface{}
if err := json.Unmarshal(body, &jsonResponse); err != nil {
fmt.Println("Error parsing JSON response:", err)
return 0, err
}
userIpId, ok := jsonResponse["userId"].(float64)
if !ok {
return 0, fmt.Errorf("Failed to retrieve user ID")
}
return int(userIpId), nil
}
func generateToken(host, restUsername, restPassword string) (string, error) {
nonce := rand.Int63()
requestBody, err := json.Marshal(map[string]string{
"userName": restUsername,
"password": restPassword,
})
if err != nil {
fmt.Println("Error marshaling request body:", err)
return ", err
}
client := &http.Client{}
request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
if err != nil {
fmt.Println("Error creating request:", err)
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 {
fmt.Println("Error sending request:", err)
return ", err
}
defer response.Body.Close()
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return ", err
}
var jsonResponse map[string]interface{}
if err := json.Unmarshal(responseBody, &jsonResponse); err != nil {
fmt.Println("Error parsing JSON response:", err)
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 newPassword = "test";
const token = await generateToken(host, restUsername, restPassword);
if (token === null) {
console.error("Failed to retrieve access token");
return;
}
const userIpId = await retrieveUserIpIdForUsername(host, token, userToUpdate);
const updatePasswordPayload = `{"password": "${newPassword}"}`;
console.log("Payload:", updatePasswordPayload);
const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
};
try {
const response = await fetch(`${host}/api/admin/users/${userIpId}/password`, {
method: 'PUT',
headers: headers,
body: updatePasswordPayload
});
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 nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
const headers = {
'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, 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 jsonResponse = await response.json();
const userIpId = jsonResponse.userId;
return userIpId;
} 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}`);
} else {
console.log("Token not retrieved");
}
return accessToken;
} 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";
$newPassword = "test";
try {
$token = generateToken($host, $restUsername, $restPassword);
} catch (Exception $e) {
echo "Error generating token: " . $e->getMessage();
return;
}
$userIpId = retrieveUserIpIdForUsername($host, $token, $userToUpdate);
$updatePasswordPayload = '{"password": "' . $newPassword . '"}';
echo "Payload: " . $updatePasswordPayload . "\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('PUT', "$host/api/admin/users/$userIpId/password", $headers, $updatePasswordPayload);
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) {
echo "Error: " . $e->getMessage();
}
return null;
}
function generateToken($host, $restUsername, $restPassword) {
// Generate nonce
$nonce = mt_rand();
// Create request body
$requestBody = json_encode(array(
"userName" => $restUsername,
"password" => $restPassword
));
// Create request headers
$headers = array(
'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
'Accept: application/vnd.yellowfin.api-v1+json',
'Content-Type: application/json'
);
$response = httpRequest('POST', "$host/api/refresh-tokens", $headers, $requestBody);
// Parse JSON response
$jsonResponse = json_decode($response, true);
// Get access token from response
if (isset($jsonResponse["_embedded"]["accessToken"]["securityToken"])) {
$accessToken = $jsonResponse["_embedded"]["accessToken"]["securityToken"];
echo "Access Token: " . $accessToken;
return $accessToken;
} else {
throw new Exception("Token not retrieved successfully");
}
}
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"
new_password = "test"
try:
token = generate_token(host, rest_username, rest_password)
except Exception as e:
print(f"Error generating token: {e}")
return
user_ip_id = retrieve_user_ip_id_for_username(host, token, user_to_update)
update_password_payload = '{"password": "' + new_password + '"}'
print("Payload:", update_password_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.put(f"{host}/api/admin/users/{user_ip_id}/password", headers=headers, data=update_password_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, user_name):
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/{user_name}", 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: {e}")
return None
def generate_token(host, rest_username, rest_password):
nonce = random.randint(0, 2 ** 63 - 1)
# Create request body
request_body = json.dumps({
"userName": rest_username,
"password": rest_password
})
# Create request headers
headers = {
'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
'Accept': 'application/vnd.yellowfin.api-v1+json',
'Content-Type': 'application/json'
}
# Send HTTP request
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:
raise Exception("Token not retrieved successfully") from e
if __name__ == "__main__":
main() |