-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
156 lines (141 loc) · 4.87 KB
/
index.ts
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
/* This code sample provides a starter kit to implement server side logic for your Teams App in TypeScript,
* refer to https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference for complete Azure Functions
* developer guide.
*/
// Import polyfills for fetch required by msgraph-sdk-javascript.
import "isomorphic-fetch";
import { Context, HttpRequest } from "@azure/functions";
import { Client } from "@microsoft/microsoft-graph-client";
import { createMicrosoftGraphClient, IdentityType, TeamsFx, UserInfo } from "@microsoft/teamsfx";
import { getInstallationId } from "./getInstallationId";
interface Response {
status: number;
body: { [key: string]: any };
}
type TeamsfxContext = { [key: string]: any };
/**
* This function handles requests from teamsfx client.
* The HTTP request should contain an SSO token queried from Teams in the header.
* Before trigger this function, teamsfx binding would process the SSO token and generate teamsfx configuration.
*
* This function initializes the teamsfx SDK with the configuration and calls these APIs:
* - TeamsFx().setSsoToken() - Construct teamsfx instance with the received SSO token and initialized configuration.
* - getUserInfo() - Get the user's information from the received SSO token.
* - createMicrosoftGraphClient() - Get a graph client to access user's Microsoft 365 data.
*
* The response contains multiple message blocks constructed into a JSON object, including:
* - An echo of the request body.
* - The display name encoded in the SSO token.
* - Current user's Microsoft 365 profile if the user has consented.
*
* @param {Context} context - The Azure Functions context object.
* @param {HttpRequest} req - The HTTP request.
* @param {teamsfxContext} TeamsfxContext - The context generated by teamsfx binding.
*/
export default async function run(
context: Context,
req: HttpRequest,
teamsfxContext: TeamsfxContext
): Promise<Response> {
context.log("HTTP trigger function processed a request.");
// Initialize response.
const res: Response = {
status: 200,
body: {},
};
// Put an echo into response body.
res.body.receivedHTTPRequestBody = req.headers || "";
// Prepare access token.
const accessToken: string = teamsfxContext["AccessToken"];
if (!accessToken) {
return {
status: 400,
body: {
error: "No access token was found in request header.",
},
};
}
// Construct teamsfx.
let teamsfx: TeamsFx;
try {
teamsfx = new TeamsFx().setSsoToken(accessToken);
} catch (e) {
context.log.error(e);
return {
status: 500,
body: {
error:
"Failed to construct TeamsFx using your accessToken. " +
"Ensure your function app is configured with the right Azure AD App registration.",
},
};
}
/////
try {
// do sth here, to call activity notification api
//
const graphClient_userId: Client = await createMicrosoftGraphClient(teamsfx, ["User.Read"]);
const userId = await graphClient_userId.api("/me").get()["id"];
// get installationId
const installationId = await getInstallationId(teamsfx, userId);
let postbody = {
topic: {
source: "entityUrl",
value:
"https://graph.microsoft.com/v1.0/users/" +
userId +
"/teamwork/installedApps/" +
installationId,
},
activityType: "taskCreated",
previewText: {
content: "Task Created",
},
// templateParameters: [
// {
// name: "taskId",
// value: "12322",
// },
// ],
};
let teamsfx_app: TeamsFx;
teamsfx_app = new TeamsFx(IdentityType.App);
const graphClient: Client = createMicrosoftGraphClient(teamsfx_app, [".default"]);
await graphClient.api("users/" + userId + "/teamwork/sendActivityNotification").post(postbody);
} catch (e) {
console.log(e);
}
// Query user's information from the access token.
try {
const currentUser: UserInfo = await teamsfx.getUserInfo();
if (currentUser && currentUser.displayName) {
res.body.userInfoMessage = `User display name is ${currentUser.displayName}.`;
} else {
res.body.userInfoMessage = "No user information was found in access token.";
}
} catch (e) {
context.log.error(e);
return {
status: 400,
body: {
error: "Access token is invalid.",
},
};
}
// Create a graph client to access user's Microsoft 365 data after user has consented.
try {
const graphClient: Client = createMicrosoftGraphClient(teamsfx, [".default"]);
const profile: any = await graphClient.api("/me").get();
res.body.graphClientMessage = profile;
} catch (e) {
context.log.error(e);
return {
status: 500,
body: {
error:
"Failed to retrieve user profile from Microsoft Graph. The application may not be authorized.",
},
};
}
return res;
}