-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathApp.tsx
More file actions
266 lines (222 loc) · 9.55 KB
/
App.tsx
File metadata and controls
266 lines (222 loc) · 9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// ----------------------------------------------------------------------------
import { AuthenticationResult, InteractionType, EventMessage, EventType, AuthError } from "@azure/msal-browser";
import { MsalContext } from "@azure/msal-react";
import React from "react";
import { service, factories, models, IEmbedConfiguration } from "powerbi-client";
import "./App.css";
import * as config from "./Config";
const powerbi = new service.Service(factories.hpmFactory, factories.wpmpFactory, factories.routerFactory);
let accessToken = "";
let embedUrl = "";
let reportContainer: HTMLElement;
let reportRef: React.RefObject<HTMLDivElement>;
let loading: JSX.Element;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface AppProps { };
interface AppState { accessToken: string; embedUrl: string; error: string[] };
class App extends React.Component<AppProps, AppState> {
static contextType = MsalContext;
constructor(props: AppProps) {
super(props);
this.state = { accessToken: "", embedUrl: "", error: [] };
reportRef = React.createRef();
// Report container
loading = (
<div
id="reportContainer"
ref={reportRef} >
Loading the report...
</div>
);
}
// React function
render(): JSX.Element {
if (this.state.error.length) {
// Cleaning the report container contents and rendering the error message in multiple lines
reportContainer.textContent = "";
this.state.error.forEach(line => {
reportContainer.appendChild(document.createTextNode(line));
reportContainer.appendChild(document.createElement("br"));
});
}
else if (this.state.accessToken !== "" && this.state.embedUrl !== "") {
const embedConfiguration: IEmbedConfiguration = {
type: "report",
tokenType: models.TokenType.Aad,
accessToken,
embedUrl,
id: config.reportId,
/*
// Enable this setting to remove gray shoulders from embedded report
settings: {
background: models.BackgroundType.Transparent
}
*/
};
const report = powerbi.embed(reportContainer, embedConfiguration);
// Clear any other loaded handler events
report.off("loaded");
// Triggers when a content schema is successfully loaded
report.on("loaded", function () {
console.log("Report load successful");
});
// Clear any other rendered handler events
report.off("rendered");
// Triggers when a content is successfully embedded in UI
report.on("rendered", function () {
console.log("Report render successful");
});
// Clear any other error handler event
report.off("error");
// Below patch of code is for handling errors that occur during embedding
report.on("error", function (event) {
const errorMsg = event.detail;
// Use errorMsg variable to log error in any destination of choice
console.error(errorMsg);
});
}
return loading;
}
// React function
componentDidMount(): void {
if (reportRef !== null) {
reportContainer = reportRef.current!;
}
// User input - null check
if (config.workspaceId === "" || config.reportId === "") {
this.setState({ error: ["Please assign values to workspace Id and report Id in Config.ts file"] });
return;
}
this.authenticate();
}
// React function
componentDidUpdate(): void {
this.authenticate();
}
// React function
componentWillUnmount(): void {
powerbi.reset(reportContainer);
}
// Authenticating to get the access token
authenticate(): void {
const msalInstance = this.context.instance;
const msalAccounts = this.context.accounts;
const msalInProgress = this.context.inProgress;
const isAuthenticated = this.context.accounts.length > 0;
if (this.state.error.length > 0) {
return;
}
const eventCallback = msalInstance.addEventCallback((message: EventMessage) => {
if (message.eventType === EventType.LOGIN_SUCCESS && !accessToken) {
const payload = message.payload as AuthenticationResult;
const name: string = payload.account?.name ? payload.account?.name: "";
accessToken = payload.accessToken;
this.setUsername(name);
this.tryRefreshUserPermissions();
}
});
const loginRequest = {
scopes: config.scopeBase,
account: msalAccounts[0]
};
if (!isAuthenticated && msalInProgress === InteractionType.None) {
msalInstance.loginRedirect(loginRequest);
}
else if (isAuthenticated && accessToken && !embedUrl) {
this.getembedUrl();
msalInstance.removeEventCallback(eventCallback);
}
else if (isAuthenticated && !accessToken && !embedUrl && msalInProgress === InteractionType.None) {
this.setUsername(msalAccounts[0].name);
// get access token silently from cached id-token
msalInstance.acquireTokenSilent(loginRequest).then((response: AuthenticationResult) => {
accessToken = response.accessToken;
this.getembedUrl();
}).catch((error: AuthError) => {
// Refresh access token silently from cached id-token
// Makes the call to handleredirectcallback
if (error.errorCode === "consent_required" || error.errorCode === "interaction_required" || error.errorCode === "login_required") {
msalInstance.acquireTokenRedirect(loginRequest);
}
else if (error.errorCode === '429') {
this.setState({ error: ["Our Service Token Server (STS) is overloaded, please try again in sometime"] });
}
else {
this.setState({ error: ["There was some problem fetching the access token" + error.toString()] });
}
});
}
}
// Power BI REST API call to refresh User Permissions in Power BI
// Refreshes user permissions and makes sure the user permissions are fully updated
// https://docs.microsoft.com/rest/api/power-bi/users/refreshuserpermissions
tryRefreshUserPermissions(): void {
fetch(config.powerBiApiUrl + "v1.0/myorg/RefreshUserPermissions", {
headers: {
"Authorization": "Bearer " + accessToken
},
method: "POST"
})
.then(function (response) {
if (response.ok) {
console.log("User permissions refreshed successfully.");
} else {
// Too many requests in one hour will cause the API to fail
if (response.status === 429) {
console.error("Permissions refresh will be available in up to an hour.");
} else {
console.error(response);
}
}
})
.catch(function (error) {
console.error("Failure in making API call." + error);
});
}
// Power BI REST API call to get the embed URL of the report
getembedUrl(): void {
const thisObj: this = this;
fetch(config.powerBiApiUrl + "v1.0/myorg/groups/" + config.workspaceId + "/reports/" + config.reportId, {
headers: {
"Authorization": "Bearer " + accessToken
},
method: "GET"
})
.then(function (response) {
const errorMessage: string[] = [];
errorMessage.push("Error occurred while fetching the embed URL of the report")
errorMessage.push("Request Id: " + response.headers.get("requestId"));
response.json()
.then(function (body) {
// Successful response
if (response.ok) {
embedUrl = body["embedUrl"];
thisObj.setState({ accessToken: accessToken, embedUrl: embedUrl });
}
// If error message is available
else {
errorMessage.push("Error " + response.status + ": " + body.error.code);
thisObj.setState({ error: errorMessage });
}
})
.catch(function () {
errorMessage.push("Error " + response.status + ": An error has occurred");
thisObj.setState({ error: errorMessage });
});
})
.catch(function (error) {
// Error in making the API call
thisObj.setState({ error: error });
})
}
// Show username in the UI
setUsername(username: string): void {
const welcome = document.getElementById("welcome");
if (welcome !== null)
welcome.innerText = "Welcome, " + username;
}
}
export default App;