@microsoft/mgt-teamsfx-provider
Version:
The Microsoft Graph Toolkit TeamsFx Provider
154 lines • 5.9 kB
JavaScript
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { IProvider, ProviderState, createFromProvider, MICROSOFT_GRAPH_DEFAULT_ENDPOINT } from '@microsoft/mgt-element';
/**
* TeamsFx Provider handler
*
* @export
* @class TeamsFxProvider
* @extends {IProvider}
*/
export class TeamsFxProvider extends IProvider {
/**
* Name used for analytics
*
* @readonly
* @memberof TeamsFxProvider
*/
get name() {
return 'MgtTeamsFxProvider';
}
/**
* Constructor of TeamsFxProvider.
*
* @example
* ```typescript
* import {Providers} from '@microsoft/mgt-element';
* import {TeamsFxProvider} from '@microsoft/mgt-teamsfx-provider';
* import {TeamsUserCredential, TeamsUserCredentialAuthConfig} from "@microsoft/teamsfx";
*
* const authConfig: TeamsUserCredentialAuthConfig = {
* clientId: process.env.REACT_APP_CLIENT_ID,
* initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL,
* };
* const scope = ["User.Read"];
*
* const credential = new TeamsUserCredential(authConfig);
* const provider = new TeamsFxProvider(credential, scope);
* Providers.globalProvider = provider;
* ```
*
* @param {TeamsFxUserCredential} credential - TeamsUserCredential instance in TeamsFx library.
* @param {string | string[]} scopes - The list of scopes for which the token will have access.
* @param {GraphEndpoint} baseURL - Graph endpoint.
*
*/
constructor(credential, scopes, baseURL = MICROSOFT_GRAPH_DEFAULT_ENDPOINT) {
super();
/**
* Privilege level for authentication
*
* Can use string array or space-separated string, such as ["User.Read", "Application.Read.All"] or "User.Read Application.Read.All"
*
* @type {string | string[]}
* @memberof TeamsFxProvider
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
this.scopes = [];
/**
* Access token provided by TeamsFx
*
* @type {string}
* @memberof TeamsFxProvider
*/
this._accessToken = '';
if (!this._credential) {
this._credential = credential;
}
this.validateScopesType(scopes);
const scopesArr = this.getScopesArray(scopes);
if (!scopesArr || scopesArr.length === 0) {
this.scopes = ['.default'];
}
else {
this.scopes = scopesArr;
}
this.approvedScopes = this.scopes;
this.baseURL = baseURL;
this.graph = createFromProvider(this);
}
/**
* Uses provider to receive access token via TeamsFx
*
* @returns {Promise<string>}
* @memberof TeamsFxProvider
*/
getAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
try {
const accessToken = yield this._credential.getToken(this.scopes);
this._accessToken = accessToken ? accessToken.token : '';
if (!this._accessToken) {
throw new Error('Access token is null');
}
}
catch (error) {
const err = error;
// eslint-disable-next-line no-console
console.error(`🦒: Cannot get access token due to error: ${err.toString()}`);
this.setState(ProviderState.SignedOut);
this._accessToken = '';
}
return this._accessToken;
});
}
/**
* Performs the login using TeamsFx
*
* @returns {Promise<void>}
* @memberof TeamsFxProvider
*/
login() {
return __awaiter(this, void 0, void 0, function* () {
const token = yield this.getAccessToken();
if (!token) {
yield this._credential.login(this.scopes);
}
this._accessToken = token !== null && token !== void 0 ? token : (yield this.getAccessToken());
this.setState(this._accessToken ? ProviderState.SignedIn : ProviderState.SignedOut);
});
}
validateScopesType(value) {
// string
if (typeof value === 'string' || value instanceof String) {
return;
}
// empty array
if (Array.isArray(value) && value.length === 0) {
return;
}
// string array
if (Array.isArray(value) && value.length > 0 && value.every(item => typeof item === 'string')) {
return;
}
throw new Error('The type of scopes is not valid, it must be string or string array');
}
getScopesArray(scopes) {
const scopesArray = typeof scopes === 'string' ? scopes.split(' ') : scopes;
return scopesArray.filter(x => x !== null && x !== '');
}
}
//# sourceMappingURL=TeamsFxProvider.js.map