Page History
User synchronization is an important aspect in integrating Yellowfin into a third-party application or integrated environment. User synchronization is the process of creating or updating users in Yellowfin to match an external system. Users need to be created in Yellowfin so that user history and preferences are stored and the correct security is applied when consuming content. Yellowfin contains a set of REST services for managing users and synchronizing user updates with external systems.
REST services related to user administration are available here.
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.
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} 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 createUserAdmin . 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:
Java | C# | Go | JavaScript | PHP | Python
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 ).
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.