Initial add of Governor Sharing App

This commit is contained in:
Robin Meure 2023-11-24 16:37:28 +01:00
parent 1f2c411017
commit 50f7fba3e5
54 changed files with 65863 additions and 0 deletions

View File

@ -0,0 +1,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {}
}
]
};

View File

@ -0,0 +1,34 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
.heft
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"nodeVersion": "16.20.0",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.12.0"
},
"version": "1.18.0",
"libraryName": "microsoft-governor-sharing",
"libraryId": "4502d2aa-3b7f-46ec-886a-f5346da9e16c",
"environment": "spo",
"packageManager": "npm",
"solutionName": "governor-sharing",
"solutionShortDescription": "governor-sharing description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,186 @@
# Governor Sharing
## Summary
SPFx WebPart shows documents which have been (explicitly) shared within a SharePoint site or Team.
It does this by using the following steps:
- Issueing a Search Query (KQL) against the Graph API to retrieve documents where the managed property SharedWithUsersOWSUSER contains a value
- Iterate through the result of the search query to get the permissions (e.g. sharing information) per file (/permissions endpoint of driveItems on GraphAPI)
- Show the results in a ShimmeredDetailsList and the Pagination control for paging the results
- By selecting a document and clicking on the Sharing Settings button will open the Manage Access pane for further review of the sharing
Here is an example with a list of shared documents, with a clear distinction when they are shared with external users (notice the tooltip & icon in front of the document)
![Example Image](/assets/screenshot.png)
When you want to know more about the sharing settings of a particlar document, you can select the document and then click on the <b>Sharing Settings</b> button, this will open up the Manage Access page for the selected document which tells you that a sharing link was created for the external user.
![Example Image](/assets/screenshot2.png)
## Compatibility
| :warning: Important |
|:---------------------------|
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
This sample is optimally compatible with the following environment configuration:
![SPFx 1.18.0](https://img.shields.io/badge/version-1.18.0-green.svg)
![Node.js v16.13+](https://img.shields.io/badge/Node.js-v16.13+-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/o365devprogram)
## Contributors
* [Robin Meure](https://github.com/robinmeure)
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.0 | October 27, 2023 | Initial release |
## Minimal Path to Awesome
* Clone this repository
* Move to right solution folder
* in the command line run:
* `npm install`
* `gulp serve`
## Deployment Overview
- [SharePoint App Deployment](#sharepoint-app-deployment)
- [Prerequisites](#prerequisites-1)
- [Step 1 - Add the app to the SharePoint App catalog](#step-1---add-the-app-to-the-sharepoint-app-catalog)
- [Step 2 - Provide API consent](#step-2---provide-api-consent)
- [Step 3 - Adding the app to a SharePoint site](#step-3---adding-the-app-to-a-sharepoint-site)
- [Teams App Deployment](#teams-app-deployment)
- [Prerequisites](#prerequisites-2)
- [Step 1 - Add the app to Teams App Catalog](#step-1---add-the-app-to-teams-app-catalog)
- [Step 2 - Add the app to a Teams a tab](#step-2---add-the-app-to-a-teams-a-tab)
# SharePoint App Deployment
## Prerequisites
- A copy of the solution .sppkg package.
- The user deploying an app must be a SharePoint Administrator or Global Administrator in Microsoft 365.
- The same user needs to approve and provide consent for the API permissions (this to call the Graph Search endpoint).
## Step 1 - Add the app to the SharePoint App catalog
Follow the steps below to add the app to the SharePoint App catalog:
- Go to [More features](https://go.microsoft.com/fwlink/?linkid=2185077) in the SharePoint admin center, and sign in with an account that has the SharePoint Administrator or Global Administrator for your organization.
- Under Apps, select Open. If you didnt have an app catalog before, it might take a few minutes to load.
<img src="assets/SharePoint_Admin_Center_Manage_apps.png" width="1000"/>
- On the Manage apps page, click <b>Upload</b>, and browse to location fo the app package. The package file should have .sppkg extension.
- Select <b>Enable this app and add it to all sites</b>. This will automatically add the app to the sites, so that site owners will not need to do it themselves. Unchecked the box <b>Add to Teams</b>. If you want to add the App to Teams you need to follow these instructions. Click <b>Enable app</b> at the bottom of the side panel.
<img src="assets/SharePoint_Admin_Center_Enable_app.png" width="300"/>
## Step 2 - Provide API consent
After the API is Enable you will need to provide consent. For this step you need the Global Administrator role.
You will provide delegated permissions that will allow the application to act on a user's behalf. The application will never be able to access anything the signed in user themselves couldn't access. To learn more about delegated permissions see: https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview#types-of-permissions
- Click on <b>Go to the API access</b> page.
<img src="assets/SharePoint_Admin_Center_API_Consent.png" width="300"/>
- Click <b>Approve</b> to provide consent.
<img src="assets/SharePoint_Admin_Center_API_Consent_Approve.png" width="600"/>
## Step 3 - Adding the app to a SharePoint site
- On the site where you want to use the app go to a page and open it for editing or create a new page for this purpose.
- Click on the <b>“+”</b> to add a new web part and search for “Governor sharing”. Click on it to add it to the page.
<img src="assets/Govenor_Sharing_AddtoSharePointSite.png" width="600"/>
- The webpart should now be added to your page.
<img src="assets/Govenor_Sharing_SharedItemsExample.png" width="900"/>
- Save or Republish the page to see the changes applied.
# Teams App Deployment
For the Teams App deployment, the app needs to be deployed to the SharePoint App Catalog first (Step 1 and Step 2).
## Prerequisites
- A copy of the Teams Apps solution [package](/assets/governorsharing_teamspackage.zip)
- The user deploying the app must be a Teams Administrator or Global Administrator in Microsoft 365.
## Step 1 - Add the app to Teams App Catalog
- Browse to the Manage Apps page in the Teams Admin Center: https://admin.teams.microsoft.com/policies/manage-apps
- Click <b>Upload new App</b>, Click <b>Upload</b> and browse to the teams app package location. The package file should have .zip extension. After selecting the package click <b>Open</b>. The app will be uploaded.
<img src="assets/Teams_Admin_Center_Manage_apps.png" width="500"/>
<img src="assets/Teams_Admin_Center_Manage_apps_Upload.png" width="500"/>
<img src="assets/Teams_Admin_Center_Manage_apps_Uploaded.png" width="500"/>
- You may need to adjust your Teams App policies to make the app availabe for you organisation. For more information see https://learn.microsoft.com/en-us/microsoftteams/teams-app-permission-policies.
## Step 2 - Add the app to a Teams a tab
- Go to MS Teams and click on the <b>Apps</b> on the left bar to open the App store of Teams.
- On the left menu choose <b>Built for your Org</b> option to prefilter the apps and select “Governor sharing”. Click <b>Add</b>.
<img src="assets/Govenor_Sharing_AddtoTeam.png" width="500"/>
- Click on <b>Add to a team</b>, choose a team and a channel where you want the app to be added and click <b>Set up a tab</b> on the bottom right of the pop-up window.
<img src="assets/Govenor_Sharing_AddtoTeamTab.png" width="500"/>
<img src="assets/Govenor_Sharing_AddtoTeam_SelectTeam.png" width="500"/>
- Click on <b>Save</b>
<img src="assets/Govenor_Sharing_AddtoTeam_Save.png" width="500"/>
- The app has been added to a Team. The settings panel on the right side can be closed.
<img src="assets/Govenor_Sharing_AddedtoTeam.png" width="500"/>
# Troubleshooting
If you face any other errors, you can enable the debugging mode from the configuration pane. When this is enabled, there is a lot more details being outputted to the written to the console.
- In green you see the search (KQL) query what is used to retrieve documents
- In yellow, you see the search results
- In blue, you see the transformation of combining the searchresults and the permission calls
<img src="assets/debug.png" width="500"/>
## Known errors
Issue: We can't upload the app because there's already an app in the catalog with the same app ID. To upload a new app, change the app ID and try again. To update an existing app, go to the app details page.
Solution: Detele the app in the Teams Apps overview and re-add the package.
More information about deleting apps in Teams can found here: https://learn.microsoft.com/en-us/microsoftteams/teams-custom-app-policies-and-settings#delete-custom-apps-from-your-organizations-catalog
## Disclaimer
**THIS CODE IS PROVIDED _AS IS_ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
<img src="https://m365-visitor-stats.azurewebsites.net/sp-dev-fx-webparts/samples/react-governor-sharing" >

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

View File

@ -0,0 +1,19 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"sharing-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/sharing/SharingWebPart.js",
"manifest": "./src/webparts/sharing/SharingWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"SharingWebPartStrings": "lib/webparts/sharing/loc/{locale}.js",
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "microsoft-governor-sharing",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,47 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "Governor Sharing",
"id": "81a9fd71-f423-4420-8a6d-393fba93dc95",
"iconPath": "530be57e-cc29-49a2-9596-2068462b6d9a_96_color.png",
"version": "2.0.0.6",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "Robin Meure",
"websiteUrl": "http://github.com/robinmeure",
"privacyUrl": "https://privacy.microsoft.com/en-us/privacystatement",
"termsOfUseUrl": "https://www.microsoft.com/en-us/servicesagreement",
"mpnId": "Undefined-1.15.0"
},
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "Sites.Read.All"
}
],
"metadata": {
"shortDescription": {
"default": "App that shows explicit sharing on a site or team."
},
"longDescription": {
"default": "App that shows explicit sharing on a site or a team."
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "governor-sharing Feature",
"description": "The feature that activates elements of the governor-sharing solution.",
"id": "75e0dfb2-a990-45a2-b138-53bb431534c8",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/governor-sharing.sppkg"
}
}

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://{tenantDomain}/_layouts/workbench.aspx"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,16 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,50 @@
{
"name": "governor-sharing",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=16.13.0 <17.0.0 || >=18.17.1 <19.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@fluentui/react": "^8.106.4",
"@microsoft/microsoft-graph-types": "^2.38.0",
"@microsoft/sp-component-base": "1.18.0",
"@microsoft/sp-core-library": "1.18.0",
"@microsoft/sp-lodash-subset": "1.18.0",
"@microsoft/sp-office-ui-fabric-core": "1.18.0",
"@microsoft/sp-property-pane": "1.18.0",
"@microsoft/sp-webpart-base": "1.18.0",
"@microsoft/teams-js": "^2.15.0",
"@pnp/core": "^3.18.0",
"@pnp/graph": "^3.18.0",
"@pnp/logging": "^3.18.0",
"@pnp/queryable": "^3.18.0",
"@pnp/sp": "^3.18.0",
"@pnp/spfx-controls-react": "^3.15.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.18.0",
"@microsoft/eslint-plugin-spfx": "1.18.0",
"@microsoft/rush-stack-compiler-4.7": "0.1.0",
"@microsoft/sp-build-web": "1.18.0",
"@microsoft/sp-module-interfaces": "1.18.0",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.7.4"
}
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,23 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "530be57e-cc29-49a2-9596-2068462b6d9a",
"alias": "SharingWebPart",
"componentType": "WebPart",
"version": "*",
"manifestVersion": 2,
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart","TeamsTab"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70",
"group": { "default": "Governor" },
"title": { "default": "Governor Sharing" },
"description": { "default": "Shows explicit sharing of documents" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "Sharing",
"debugMode":false
}
}]
}

View File

@ -0,0 +1,3 @@
.sharing {
display: flex;
}

View File

@ -0,0 +1,96 @@
/* eslint-disable @typescript-eslint/typedef */
import * as React from 'react'
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import "@pnp/graph/groups";
import { ISharingViewProps } from './components/SharingView/ISharingViewProps';
import { initializeIcons } from '@fluentui/react/lib/Icons';
import PnPTelemetry from "@pnp/telemetry-js";
import "@pnp/sp/webs";
import "@pnp/sp/search";
import IDataProvider from './components/SharingView/DataProvider';
import DataProvider from './components/SharingView/DataProvider';
import { initializeFileTypeIcons } from '@fluentui/react-file-type-icons';
import {
Logger,
ConsoleListener,
LogLevel
} from "@pnp/logging";
import { IPropertyPaneConfiguration, PropertyPaneToggle, PropertyPaneTextField } from '@microsoft/sp-property-pane';
import SharingViewSingle from './components/SharingView/SharingViewSingle';
const LOG_SOURCE: string = 'Microsoft-Governance-Sharing';
export interface ISharingWebPartProps {
description: string;
debugMode: boolean;
}
export default class SharingWebPart extends BaseClientSideWebPart<ISharingWebPartProps> {
private dataProvider: IDataProvider;
protected async onInit(): Promise<void> {
// load the filetype icons and other icons
initializeIcons(undefined, { disableWarnings: true });
initializeFileTypeIcons();
// setting up the logging framework
Logger.subscribe(ConsoleListener(LOG_SOURCE));
Logger.activeLogLevel = (this.properties.debugMode) ? LogLevel.Verbose : LogLevel.Warning;
// if you don't want to send telemetry data to PnP, you can opt-out here (see https://github.com/pnp/telemetry-js for details on what is being sent)
// const telemetry = PnPTelemetry.getInstance();
// telemetry.optOut();
// loading the data provider to get access to the REST/Search API
this.dataProvider = new DataProvider(this.context);
}
public render(): void {
// determine if we're in Teams or not
let isTeams: boolean = false;
if (this.context.sdks.microsoftTeams) {
isTeams = true;
}
const element: React.ReactElement<ISharingViewProps> = React.createElement(
SharingViewSingle,
{
pageLimit: 15,
context: this.context,
isTeams: isTeams,
dataProvider: this.dataProvider
}
);
ReactDom.render(element, this.domElement);
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: this.properties.description
},
groups: [
{
groupName: "Configuration",
groupFields: [
PropertyPaneToggle('debugMode', {
label: "Enable debug mode",
})
]
}
]
}
]
};
}
protected get dataVersion(): Version {
return Version.parse('2.0');
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,34 @@
@import '~@fluentui/react/dist/sass/References.scss';
.sharing {
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
.welcome {
text-align: center;
}
.welcomeImage {
width: 100%;
max-width: 420px;
}
.links {
a {
text-decoration: none;
color: "[theme:link, default:#03787c]";
color: var(--link); // note: CSS Custom Properties support is limited to modern browsers only
&:hover {
text-decoration: underline;
color: "[theme:linkHovered, default: #014446]";
color: var(--linkHovered); // note: CSS Custom Properties support is limited to modern browsers only
}
}
}

View File

@ -0,0 +1,309 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { spfi, SPFx } from '@pnp/sp';
import { ISearchResultExtended } from "./ISearchResultExtended";
import { IFacepilePersona } from "@fluentui/react";
import { graphfi, graphGet, GraphQueryable, SPFx as graphSPFx } from "@pnp/graph";
import "@pnp/graph/batching";
import "@pnp/graph/onedrive";
import "@pnp/graph/search";
import "@pnp/graph/users";
import { Logger, LogLevel, PnPLogging } from "@pnp/logging";
import { Caching } from "@pnp/queryable";
import "@pnp/sp/presets/all";
import "@pnp/sp/search";
import "@pnp/sp/sharing";
import "@pnp/sp/webs";
import { ISharingResult } from "./ISharingResult";
import { convertToFacePilePersona, convertUserToFacePilePersona, processUsers, uniqForObject } from "./Utils";
export default interface IDataProvider {
getSharingLinks(listItems: Record<string, any>): Promise<ISharingResult[]>;
getSearchResults(): Promise<Record<string, any>>;
loadAssociatedGroups(): Promise<void>;
}
export default class DataProvider implements IDataProvider {
private webpartContext: WebPartContext;
private isTeams: boolean;
private siteUrl: string;
private tenantId: string;
private groupId: string;
private isPrivateChannel:boolean = true;
private sp: any;
private graph: any;
private standardGroups: string[] = [];
constructor(context: WebPartContext) {
this.webpartContext = context;
this.sp = spfi().using(SPFx(this.webpartContext), Caching);
this.graph = graphfi().using(graphSPFx(this.webpartContext), Caching).using(PnPLogging(LogLevel.Warning));
if (this.webpartContext.sdks.microsoftTeams) {
this.isTeams = true;
}
if (this.isTeams) {
this.siteUrl = this.webpartContext.sdks.microsoftTeams.context.teamSiteUrl;
this.tenantId = this.webpartContext.sdks.microsoftTeams.context.tid;
this.groupId = this.webpartContext.sdks.microsoftTeams.context.groupId;
this.isPrivateChannel = (this.webpartContext.sdks.microsoftTeams.context.channelType == "Private");
}
else {
this.siteUrl = this.webpartContext.pageContext.web.absoluteUrl;
this.tenantId = this.webpartContext.pageContext.aadInfo.tenantId;
}
}
public async loadAssociatedGroups(): Promise<void> {
// Gets the associated visitors group of a web
const visitorsGroup = await this.sp.web.associatedVisitorGroup.select("Title")();
this.standardGroups.push(visitorsGroup.Title);
// Gets the associated members group of a web
const membersGroup = await this.sp.web.associatedMemberGroup.select("Title")();
this.standardGroups.push(membersGroup.Title);
// Gets the associated owners group of a web
const ownersGroup = await this.sp.web.associatedOwnerGroup.select("Title")();
this.standardGroups.push(ownersGroup.Title);
}
private async getDriveItemsBySearchResult(listItems: Record<string, any>): Promise<Record<string, any>> {
const driveItems: Record<string, any> = {};
const [batchedGraph, execute] = this.graph.batched();
batchedGraph.using(Caching());
// for each file, we need to get the permissions
// eslint-disable-next-line guard-for-in
for (const fileId in listItems) {
const file = listItems[fileId];
// the permissions endpoint on the driveItem is not (yet?) exposed in pnpjs, so we need to use the graphQueryable
const driveItemQuery = batchedGraph.drives.getById(file.DriveId).getItemById(file.DriveItemId);
// adding the permissions endpoint
const graphQueryable = GraphQueryable(driveItemQuery, "permissions")
// getting the permissions and adding the request to the batch
graphGet(GraphQueryable(graphQueryable)).then(r => {
driveItems[fileId] = r;
});
}
// Executes the batched calls
await execute();
return driveItems;
}
public async getSharingLinks(listItems: Record<string, any>): Promise<ISharingResult[]> {
const sharedResults: ISharingResult[] = [];
const driveItems = await this.getDriveItemsBySearchResult(listItems);
// now we have all the data we need, we can start building up the result
// eslint-disable-next-line guard-for-in
for (const fileId in driveItems) {
const driveItem = driveItems[fileId];
const file = listItems[fileId];
let sharedWithUser: IFacepilePersona[] = [];
let sharingUserType = "Member";
// Getting all the details of the file and in which folder is lives
let folderUrl = file.Path.replace(`/${file.FileName}`, '');
let folderName = folderUrl.lastIndexOf("/") > 0 ? folderUrl.substring(folderUrl.lastIndexOf("/") + 1) : folderUrl;
// for certain filetypes we get the dispform.aspx link back instead of the full path, so we need to fix that
if (folderName.indexOf("DispForm.aspx") > -1) {
folderUrl = folderUrl.substring(0, folderUrl.lastIndexOf("/Forms/DispForm.aspx"));
folderName = folderUrl.lastIndexOf("/") > 0 ? folderUrl.substring(folderUrl.lastIndexOf("/") + 1) : folderUrl;
file.FileExtension = file.FileName.substring(file.FileName.lastIndexOf(".") + 1);
}
file.FileUrl = file.Path;
file.FolderUrl = folderUrl;
file.FolderName = folderName;
file.FileId = fileId;
// if a file has inherited permissions, the propery is returned as "inheritedFrom": {}
// if a file has unique permissions, the propery is not returned at all
driveItem.forEach(permission => {
if (permission.link) {
switch (permission.link.scope) {
case "anonymous":
break;
case "organization": {
const _user: IFacepilePersona = {};
_user.personaName = permission.link.scope + " " + permission.link.type;
_user.data = "Organization";
if (sharedWithUser.indexOf(_user) === -1) {
sharedWithUser.push(_user);
}
break;
}
case "users": {
const _users = convertToFacePilePersona(permission.grantedToIdentitiesV2);
sharedWithUser.push(..._users);
break;
}
default:
break;
}
}
else // checking the normal permissions as well, other than the sharing links
{
// if the permission is not the same as the default associated spo groups, we need to add it to the sharedWithUser array
if (this.standardGroups.indexOf(permission.grantedTo.user.displayName) === -1) {
const _users = convertUserToFacePilePersona(permission.grantedToV2);
sharedWithUser.push(_users);
}
else // otherwise, we're gonna add these groups and mark it as inherited permissions
{
const _user: IFacepilePersona = {};
_user.personaName = permission.grantedTo.user.displayName;
_user.data = "Inherited";
if (sharedWithUser.indexOf(_user) === -1) {
sharedWithUser.push(_user);
}
}
}
});
if (file.SharedWithUsersOWSUSER !== null) {
const _users = processUsers(file.SharedWithUsersOWSUSER);
sharedWithUser.push(..._users);
}
// if there are any duplicates, this will remove them (e.g. multiple organization links)
sharedWithUser = uniqForObject(sharedWithUser);
if (sharedWithUser.length === 0)
continue;
let isGuest = false;
let isLink = false;
let isInherited = false;
for (const user of sharedWithUser) {
switch(user.data)
{
case "Guest":isGuest = true;break;
case "Organization":isLink = true;break;
case "Inherited":isInherited = true;break;
}
}
// if we found a guest user, we need to set the sharingUserType to Guest
if (isGuest) {
sharingUserType = "Guest";
}
else if (isLink) {
sharingUserType = "Link";
}
else if (isInherited) {
sharingUserType = "Inherited";
}
// building up the result to be returned
const sharedResult: ISharingResult =
{
FileExtension: (file.FileExtension == null) ? "folder" : file.FileExtension,
FileName: file.FileName,
Channel: file.FolderName,
LastModified: file.LastModifiedTime,
SharedWith: sharedWithUser,
ListId: file.ListId,
ListItemId: file.ListItemId,
Url: file.FileUrl,
FolderUrl: file.FolderUrl,
SharingUserType: sharingUserType,
FileId: file.FileId,
SiteUrl: file.SiteUrl
};
sharedResults.push(sharedResult);
Logger.writeJSON(sharedResult, LogLevel.Verbose);
}
return sharedResults;
}
public async getSearchResults(): Promise<Record<string, any>> {
const listItems: Record<string, any> = {};
let searchResults: any[] = [];
searchResults = await this.fetchSearchResultsAll(0, searchResults);
searchResults.forEach(results => {
results.forEach(result => {
result.hitsContainers.forEach(hits => {
hits.hits.forEach(hit => {
const SharedWithUsersOWSUser = (hit.resource.listItem.fields.sharedWithUsersOWSUSER != undefined) ? hit.resource.listItem.fields.sharedWithUsersOWSUSER : null;
// if we don't get a driveId back (e.g. documentlibrary), then skip the returned item
if (hit.resource.listItem.fields.driveId == undefined)
return;
const result: ISearchResultExtended = {
DriveItemId: hit.resource.id,
FileName: hit.resource.listItem.fields.fileName,
FileExtension: hit.resource.listItem.fields.fileExtension,
ListId: hit.resource.listItem.fields.listId,
FileId: hit.resource.listItem.id,
DriveId: hit.resource.listItem.fields.driveId,
ListItemId: hit.resource.listItem.fields.listItemId,
Path: hit.resource.webUrl,
LastModifiedTime: hit.resource.lastModifiedDateTime,
SharedWithUsersOWSUSER: SharedWithUsersOWSUser,
SiteUrl:hit.resource.listItem.fields.spSiteUrl
}
listItems[result.FileId] = result;
Logger.writeJSON(result, LogLevel.Verbose);
});
});
});
});
return listItems;
}
private async fetchSearchResultsAll(page: number, searchResults?: any[]): Promise<any> {
if (page === 0) {
searchResults = [];
}
const everyoneExceptExternalsUserName = `spo-grid-all-users/${this.tenantId}`;
// the query consists of checking for the following things:
// - IsDocument:TRUE OR IsContainer:TRUE -> we only want to return documents and folders
// - NOT FileExtension:aspx -> we don't want to return aspx pages
// - (SharedWithUsersOWSUSER:*) OR (SharedWithUsersOWSUSER:${everyoneExceptExternalsUserName} OR SharedWithUsersOWSUser:Everyone) -> we only want to return items that are shared with someone
// - (GroupId:${this.groupId} OR RelatedGroupId:${this.groupId}) -> we only want to return items that are in the current group
// - SPSiteUrl:${this.siteUrl} -> we only want to return items that are in the current site
// - size: 500 -> we want to return 500 items per page
// - from: ${page} -> we want to return the next page of results
const query = (this.isTeams && !this.isPrivateChannel) ?
`(IsDocument:TRUE OR IsContainer:TRUE) AND (NOT FileExtension:aspx) AND ((SharedWithUsersOWSUSER:*) OR (SharedWithUsersOWSUSER:${everyoneExceptExternalsUserName} OR SharedWithUsersOWSUser:Everyone)) AND (GroupId:${this.groupId} OR RelatedGroupId:${this.groupId})`
: `(IsDocument:TRUE OR IsContainer:TRUE) AND (NOT FileExtension:aspx) AND ((SharedWithUsersOWSUSER:*) OR (SharedWithUsersOWSUSER:${everyoneExceptExternalsUserName} OR SharedWithUsersOWSUser:Everyone)) AND (SPSiteUrl:${this.siteUrl})`
Logger.write(`Issuing search query: ${query}`, LogLevel.Verbose);
const results = await this.graph.query({
entityTypes: ["driveItem", "listItem"],
query: {
queryString: `${query}`
},
fields: ["path", "id", "driveId", "driveItemId", "listId", "listItemId", "fileName", "fileExtension", "webUrl", "lastModifiedDateTime", "lastModified", "SharedWithUsersOWSUSER","SPSiteUrl"],
from: `${page}`,
size: 500
});
searchResults.push(results);
if (results[0].hitsContainers[0].moreResultsAvailable) {
searchResults = await this.fetchSearchResultsAll(page + 500, searchResults)
}
return searchResults;
}
}

View File

@ -0,0 +1,26 @@
import { Guid } from "@microsoft/sp-core-library";
import { ISearchResult } from "@pnp/sp/search";
import { SearchHit } from "@microsoft/microsoft-graph-types";
export interface ISearchResultExtended extends ISearchResult {
SPSiteURL?: string;
ListItemId?: number;
ListId?: string;
ListUrl?: string;
SharedWithUsersOWSUSER?: string;
FileName?: string;
SharedWithDetails?: string;
Rank?: number;
DocId?: number;
WorkId?: number;
IdentityListItemId?: Guid;
ViewableByExternalUsers?: boolean;
DriveItemId?: string;
FileId?: string;
DriveId?: string;
SiteUrl?: string;
}
export interface IGraphSearchResultExtended extends SearchHit {
}

View File

@ -0,0 +1,17 @@
import { IFacepilePersona } from "@fluentui/react";
export interface ISharingResult {
FileExtension: string;
FileName: string;
LastModified: Date;
SharedWith: IFacepilePersona[];
ListId: string;
ListItemId: number;
Url: string;
FolderUrl: string;
Channel?: string;
FileId?: string;
SharingUserType?: any;
SiteUrl?:string;
}
export default ISharingResult;

View File

@ -0,0 +1,8 @@
import IDataProvider from "./DataProvider";
export interface ISharingViewProps {
pageLimit: number;
context: any;
isTeams: boolean;
dataProvider: IDataProvider;
}

View File

@ -0,0 +1,24 @@
import { ISharingResult } from "./ISharingResult";
import { IContextualMenuProps } from '@fluentui/react';
export interface ISharingViewState {
files: ISharingResult[];
fileIds: string[];
searchItems: Record<string, any>;
groups: any[];
isOpen: boolean;
selectedDocument: ISharingResult;
hideSharingSettingsDialog: boolean;
frameUrlSharingSettings: string;
contextualMenuProps?: IContextualMenuProps;
showResetFilters?: boolean;
currentPage: number,
totalPages: number,
pageLimit: number,
selectedFilter?: string,
loadingComplete: boolean,
statusMessage: string,
}
export default ISharingViewState;

View File

@ -0,0 +1,406 @@
import {
DialogType,
Facepile,
IColumn,
Icon,
Label,
Link,
OverflowButtonType,
Persona,
PersonaSize,
Selection,
SelectionMode,
ShimmeredDetailsList,
Text,
ThemeProvider,
TooltipHost
} from '@fluentui/react';
import { FileIconType, getFileTypeIconProps } from '@fluentui/react-file-type-icons';
import { EnhancedThemeProvider } from "@pnp/spfx-controls-react/lib/EnhancedThemeProvider";
import { IFrameDialog } from "@pnp/spfx-controls-react/lib/IFrameDialog";
import { Toolbar } from '@pnp/spfx-controls-react/lib/Toolbar';
import { Pagination } from "@pnp/spfx-controls-react/lib/pagination";
import * as moment from 'moment';
import * as React from 'react';
import { ISharingResult } from "./ISharingResult";
import { ISharingViewProps } from './ISharingViewProps';
import ISharingViewState from './ISharingViewState';
import { genericSort, textSort } from './Utils';
export default class SharingViewSingle extends React.Component<ISharingViewProps, ISharingViewState> {
private columns: IColumn[];
private selection: Selection;
private siteUrl: string;
private fileIds: string[];
private files: ISharingResult[];
constructor(props: ISharingViewProps) {
super(props);
// setting the URL of where the web part is running, either in Teams using the TeamsContext or using SPO using the webpartcontext
this.siteUrl = (this.props.isTeams) ? this.props.context.sdks.microsoftTeams.context.teamSiteUrl : this.props.context.pageContext.legacyPageContext.webAbsoluteUrl;
this.selection = new Selection({});
this.state = {
// initialization of the arrys holding the documents
files: [],
fileIds: [],
searchItems: [],
groups: [],
// initialization of the pagination - need to do this for each detailsList
currentPage: 1,
totalPages: 1,
pageLimit: this.props.pageLimit,
// initialization of the selected document
selectedDocument: { FileExtension: "", FileName: "", LastModified: null, SharedWith: null, ListId: "", ListItemId: 0, Url: "", FolderUrl: "", SiteUrl: "", Channel: "", SharingUserType: "" },
// initialization of the dialog
isOpen: false,
hideSharingSettingsDialog: true,
frameUrlSharingSettings: "",
loadingComplete: false,
statusMessage: ""
};
const overflowButtonProps = {
ariaLabel: 'More users'
};
this.columns = [
{
key: 'SharingUserType',
name: 'SharingUserType',
fieldName: 'SharingUserType',
minWidth: 16,
maxWidth: 16,
isIconOnly: true,
isResizable: false,
onColumnClick: this._onColumnClick,
},
{
key: 'FileExtension',
name: 'FileExtension',
fieldName: 'FileExtension',
minWidth: 16,
maxWidth: 16,
isIconOnly: true,
isResizable: false,
onColumnClick: this._onColumnClick,
},
{
key: 'FileName',
name: 'Filename',
fieldName: 'FileName',
minWidth: 100,
maxWidth: 200,
isResizable: true,
//isSorted: true,
isSortedDescending: false,
isRowHeader: true,
sortAscendingAriaLabel: 'Sorted A to Z',
sortDescendingAriaLabel: 'Sorted Z to A',
data: 'string',
onColumnClick: this._onColumnClick,
},
{
key: 'SharedWith',
name: 'Shared with',
fieldName: 'SharedWith',
minWidth: 150,
maxWidth: 185,
isResizable: true,
onColumnClick: this._onColumnClick,
onRender: (item: ISharingResult) => {
if (item.SharedWith === null)
return <span />;
if (item.SharedWith.length > 1) {
return <Facepile
personaSize={PersonaSize.size24}
maxDisplayablePersonas={5}
personas={item.SharedWith}
overflowButtonType={OverflowButtonType.descriptive}
overflowButtonProps={overflowButtonProps}
ariaDescription="List of people who has been shared with."
ariaLabel="List of people who has been shared with."
/>
}
else {
switch (item.SharingUserType) {
case "Link": return <Persona text={`${item.SharedWith[0].personaName}`} hidePersonaDetails={true} size={PersonaSize.size24} />; break;
default:
return <Persona text={`${item.SharedWith[0].personaName}`} hidePersonaDetails={true} size={PersonaSize.size24} />; break;
}
}
},
},
{
key: 'Channel',
name: 'Channel / Folder',
fieldName: 'Channel',
minWidth: 100,
maxWidth: 150,
isResizable: true,
data: 'string',
onColumnClick: this._onColumnClick,
},
{
key: 'LastModified',
name: 'Last modified',
fieldName: 'LastModified',
minWidth: 70,
maxWidth: 90,
isResizable: true,
isPadded: true,
data: 'date',
onColumnClick: this._onColumnClick,
},
];
}
private _renderItemColumn(item: ISharingResult, index: number, column: IColumn): any {
const fieldContent = item[column.fieldName as keyof ISharingResult] as string;
// in here we're going to make the column render differently based on the column name
switch (column.key) {
case 'FileExtension':
switch (item.FileExtension) {
case "folder": return <Icon {...getFileTypeIconProps({ type: FileIconType.documentsFolder, size: 16, imageFileType: 'png' })} />; break;
default: return <Icon {...getFileTypeIconProps({ extension: `${item.FileExtension}`, size: 16, imageFileType: 'png' })} />; break;
}
case 'SharingUserType':
switch (item.SharingUserType) {
case "Guest": return <TooltipHost content="Shared with guest/external users" id="guestTip">
<Icon aria-label="SecurityGroup" aria-describedby="guestTip" iconName="SecurityGroup" id="Guest" />
</TooltipHost>;break;
case "Everyone": return <TooltipHost content="Shared with everyone" id="everyoneTip">
<Icon aria-label="Family" aria-describedby="everyoneTip" iconName="Family" id="Family" />
</TooltipHost>;break;
case "Member": return <span />;
case "Link": return <TooltipHost content="Shared with organization" id="everyoneTip">
<Icon aria-label="Family" aria-describedby="everyoneTip" iconName="Family" id="Family" />
</TooltipHost>;break;
case "Inherited": return <TooltipHost content="Shared by inheritance" id="inheritedTip">
<Icon aria-label="PartyLeader" aria-describedby="inheritedTip" iconName="PartyLeader" id="PartyLeader" />
</TooltipHost>;break;
}
break;
case 'LastModified':
return <span>{moment(item.LastModified).format('LL')}</span>;break;
case 'FileName':
return <span><Text><Link href={`${item.Url}`}>{`${item.FileName}`}</Link></Text></span>;break;
case 'Channel':
return <span><Text><Link href={`${item.FolderUrl}`}>{`${item.Channel}`}</Link></Text></span>;break;
default:
return <span>{fieldContent}</span>;break;
}
}
// Gets the Selection Details
private loadSharingDialogDetails(): void {
const item = this.selection.getSelection()[0] as ISharingResult;
const url = `${item.SiteUrl}/_layouts/15/sharedialog.aspx?listId=${item.ListId}&listItemId=${item.ListItemId}&clientId=sharePoint&mode=manageAccess&ma=0`;
this.setState(
{
frameUrlSharingSettings: url,
selectedDocument: item,
hideSharingSettingsDialog: false
});
}
// Handle Item Invoked - Item Invoked is when user selects a row
// and presses the ENTER key
private _handleItemInvoked = (item: ISharingResult): void => {
}
private _onColumnClick = (ev: React.MouseEvent<HTMLElement>, column: IColumn): void => {
const newColumns: IColumn[] = this.columns.slice();
const currColumn: IColumn = newColumns.filter(currCol => column.key === currCol.key)[0];
newColumns.forEach((newCol: IColumn) => {
if (newCol === currColumn) {
currColumn.isSortedDescending = !currColumn.isSortedDescending;
currColumn.isSorted = true;
} else {
newCol.isSorted = false;
newCol.isSortedDescending = true;
}
});
if (currColumn.data === 'string')
this.setState({ files: textSort(this.state.files, currColumn.fieldName!, currColumn.isSortedDescending) });
else
this.setState({ files: genericSort(this.state.files, currColumn.fieldName!, currColumn.isSortedDescending) });
}
private _onSelectedFiltersChange = (selectedFilters: string[]): void => {
this.setState({ selectedFilter: selectedFilters[0] });
// we only have 1 filter, so no need to actually see what we're filtering on,
// it's either showing only guests/external users or all users
this.setState({ files: (selectedFilters.length > 0) ? this.state.files.filter(i => i.SharingUserType == "Guest") : this.files });
}
private _findItem = (findQuery: string): string => {
this.setState({ files: findQuery ? this.files.filter(i => i.FileName.toLowerCase().indexOf(findQuery.toLowerCase()) > -1) : this.files });
return findQuery;
};
// needs to be here for the iframe to be rendered that holds the manage access page
private _onIframeLoaded() { }
private _onDialogDismiss() {
this.setState(
{
hideSharingSettingsDialog: true
});
}
private async _processSharingLinks(fileIds: string[]): Promise<ISharingResult[]> {
// setting these to be empty because of the pagination,
// otherwise in the pagination items will be added to the existing array
const sharingLinks: ISharingResult[] = [];
const paginatedListItems: Record<string, any> = {};
fileIds.forEach((fileId) => {
paginatedListItems[fileId] = this.state.searchItems[fileId];
});
// getting the sharing links using expensive REST API calls based on the given list of Id's
const sharedLinkResults = await this.props.dataProvider.getSharingLinks(paginatedListItems);
if (sharedLinkResults === null)
return;
sharedLinkResults.forEach((sharedResult) => {
if (sharedResult.SharedWith === null)
return;
sharingLinks.push(sharedResult)
});
return (sharingLinks);
}
private async loadPage(page: number): Promise<void> {
// to inform the user we're getting items, we set the loadingComplete to false to enable the 'shimmer' effect
this.setState({ loadingComplete: false });
// get the first and last index of the items to be displayed on the page
const lastIndex = page * this.state.pageLimit;
const firstIndex = lastIndex - this.state.pageLimit;
// get the items to be displayed on the page
const paginatedItems = this.fileIds.slice(firstIndex, lastIndex);
this.setState({ currentPage: page });
// if there are no items to be displayed, we're done
if (paginatedItems.length == 0) {
this.setState({ loadingComplete: true, statusMessage: "No items to display" });
return;
}
else {
this.setState({ statusMessage: `${this.fileIds.length} shared items found` });
}
// get the sharing links for the items on the page
this.files = await this._processSharingLinks(paginatedItems);
this.setState({ files: this.files });
// if the filter is set already, enable it again for the next paged result set
if (this.state.selectedFilter !== undefined) {
this.setState({ files: this.files.filter(i => i.SharingUserType === "Guest") });
}
else {
this.setState({ files: this.files });
}
this.setState({ loadingComplete: true });
}
public componentDidMount() {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async () => {
// get the default group titles, this is used to later determine if documents have inherited permissions
await this.props.dataProvider.loadAssociatedGroups();
// this will hold all the shared documents based on the search query
const searchItems: Record<string, any> = await this.props.dataProvider.getSearchResults();
this.fileIds = Object.keys(searchItems);
this.setState({
searchItems: searchItems,
fileIds: this.fileIds,
totalPages: Math.ceil(this.fileIds.length / this.state.pageLimit),
});
await this.loadPage(this.state.currentPage);
})();
}
public render(): React.ReactElement<ISharingViewProps> {
const { currentPage, totalPages, files, loadingComplete, statusMessage } = this.state;
return (
<ThemeProvider>
<EnhancedThemeProvider context={this.props.context}>
<Toolbar actionGroups={{
'share': {
'share': {
title: 'Sharing Settings',
iconName: 'Share',
onClick: () => this.loadSharingDialogDetails()
}
}
}}
filters={[
{
id: "f1",
title: "Guest/External Users",
}]}
onSelectedFiltersChange={this._onSelectedFiltersChange.bind(this)}
find={true}
onFindQueryChange={this._findItem}
/>
<IFrameDialog
url={this.state.frameUrlSharingSettings}
iframeOnLoad={this._onIframeLoaded.bind(this)}
hidden={this.state.hideSharingSettingsDialog}
onDismiss={this._onDialogDismiss.bind(this)}
modalProps={{
isBlocking: false
}}
dialogContentProps={{
type: DialogType.close,
showCloseButton: false
}}
width={'570px'}
height={'815px'}
/>
<Label>{statusMessage}</Label>
<ShimmeredDetailsList
usePageCache={true}
columns={this.columns}
enableShimmer={(!loadingComplete)}
items={files}
selection={this.selection}
onItemInvoked={this._handleItemInvoked}
selectionMode={SelectionMode.single}
onRenderItemColumn={this._renderItemColumn}
/>
<Pagination
key="files"
currentPage={currentPage}
totalPages={totalPages}
onChange={(page) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.loadPage(page);
}}
limiter={3} // Optional - default value 3
hideFirstPageJump // Optional
hideLastPageJump // Optional
limiterIcon={"Emoji12"} // Optional
/>
</EnhancedThemeProvider>
</ThemeProvider>
);
}
}

View File

@ -0,0 +1,226 @@
import { IColumn, IContextualMenuItem, IFacepilePersona } from '@fluentui/react';
import { IdentitySet } from '@microsoft/microsoft-graph-types';
import { isEqual } from '@microsoft/sp-lodash-subset';
// need to rework this sorting method to be a) working with dates and b) be case insensitive
export function genericSort<T>(items: T[], columnKey: string, isSortedDescending?: boolean): T[] {
const key = columnKey as keyof T;
return items.slice(0).sort((a: T, b: T) => ((isSortedDescending ? a[key] < b[key] : a[key] > b[key]) ? 1 : -1));
}
// thanks to Michael Norward for this function, https://stackoverflow.com/questions/8900732/sort-objects-in-an-array-alphabetically-on-one-property-of-the-array
export function textSort(objectsArr: any[], prop, isSortedDescending = true): any[] {
const objectsHaveProp = objectsArr.every(object => object.hasOwnProperty(prop));
if (objectsHaveProp) {
const newObjectsArr = objectsArr.slice();
newObjectsArr.sort((a, b) => {
if (isNaN(Number(a[prop]))) {
const textA = a[prop].toUpperCase(),
textB = b[prop].toUpperCase();
if (isSortedDescending) {
return textA < textB ? -1 : textA > textB ? 1 : 0;
} else {
return textB < textA ? -1 : textB > textA ? 1 : 0;
}
} else {
return isSortedDescending ? a[prop] - b[prop] : b[prop] - a[prop];
}
});
return newObjectsArr;
}
return objectsArr;
}
export function uniqForObject<T>(array: T[]): T[] {
const result: T[] = [];
for (const item of array) {
const found = result.some((value) => isEqual(value, item));
if (!found) {
result.push(item);
}
}
return result;
}
export function rightTrim(sourceString: string, searchString: string): string {
for (; ;) {
const pos = sourceString.lastIndexOf(searchString);
if (pos === sourceString.length - 1) {
const result = sourceString.slice(0, pos);
sourceString = result;
}
else {
break;
}
}
return sourceString;
}
export function convertToGraphUserFromLinkKind(linkKind: number): microsoftgraph.User {
const _user: microsoftgraph.User = {};
switch (linkKind) {
case 2: _user.displayName = "Organization View"; break;
case 3: _user.displayName = "Organization Edit"; break;
case 4: _user.displayName = "Anonymous View"; break;
case 5: _user.displayName = "Anonymous Edit"; break;
default: break;
}
_user.userType = "Link";
return _user;
}
export function convertUserToFacePilePersona(user: IdentitySet): IFacepilePersona {
if (user['siteUser'] != null) {
const siteUser = user['siteUser'];
const _user: IFacepilePersona =
{
data: (siteUser.loginName.indexOf('#ext') != -1) ? "Guest" : "Member",
personaName: siteUser.displayName,
name: siteUser.loginName.replace("i:0#.f|membership|", "")
};
return _user;
}
else if (user['siteGroup'] != null) {
const siteGroup = user['siteGroup'];
const _user: IFacepilePersona =
{
data: "Group",
personaName: siteGroup.displayName,
name: siteGroup.loginName.replace("c:0t.c|tenant|", "")
};
return _user;
}
else {
const _user: IFacepilePersona =
{
name: user.user.id,
data: (user.user.id == null) ? "Guest" : "Member",
personaName: user.user.displayName
};
return _user;
}
}
export function convertToFacePilePersona(users: IdentitySet[]): IFacepilePersona[] {
const _users: IFacepilePersona[] = [];
if (users.length > 1) {
users.forEach((user) => {
if (user['siteUser'] != null) {
const siteUser = user['siteUser'];
const _user: IFacepilePersona =
{
data: (siteUser.loginName.indexOf('#ext') !== -1) ? "Guest" : "Member",
personaName: siteUser.displayName,
name: siteUser.loginName.replace("i:0#.f|membership|", "")
};
_users.push(_user);
}
else {
const _user: IFacepilePersona =
{
name: user.user.id,
data: (user.user.id == null) ? "Guest" : "Member",
personaName: user.user.displayName
};
_users.push(_user);
}
});
}
else {
_users.push(convertUserToFacePilePersona(users[0]));
}
return _users;
}
export function getSortingMenuItems(column: IColumn, onSortColumn: (column: IColumn, isSortedDescending: boolean) => void): IContextualMenuItem[] {
const menuItems = [];
if (column.data === Number) {
menuItems.push(
{
key: 'smallToLarger',
name: 'Smaller to larger',
canCheck: true,
checked: column.isSorted && !column.isSortedDescending,
onClick: () => onSortColumn(column, false)
},
{
key: 'largerToSmall',
name: 'Larger to smaller',
canCheck: true,
checked: column.isSorted && column.isSortedDescending,
onClick: () => onSortColumn(column, true)
}
);
}
else if (column.data === Date) {
menuItems.push(
{
key: 'oldToNew',
name: 'Older to newer',
canCheck: true,
checked: column.isSorted && !column.isSortedDescending,
onClick: () => onSortColumn(column, false)
},
{
key: 'newToOld',
name: 'Newer to Older',
canCheck: true,
checked: column.isSorted && column.isSortedDescending,
onClick: () => onSortColumn(column, true)
}
);
}
else
//(column.data == String)
// NOTE: in case of 'complex columns like Taxonomy, you need to add more logic'
{
menuItems.push(
{
key: 'aToZ',
name: 'A to Z',
canCheck: true,
checked: column.isSorted && !column.isSortedDescending,
onClick: () => onSortColumn(column, false)
},
{
key: 'zToA',
name: 'Z to A',
canCheck: true,
checked: column.isSorted && column.isSortedDescending,
onClick: () => onSortColumn(column, true)
}
);
}
return menuItems;
}
/// this is used to process the SharedWithUsersOWSUSER output to get the userPrincipalName and userType
export function processUsers(users: string): IFacepilePersona[] {
const _users: microsoftgraph.User[] = [];
if (users === null || users === undefined)
return _users;
if (users.match("\n\n")) {
const allUsers = users.split("\n\n");
allUsers.forEach(element => {
const user: IFacepilePersona = {
personaName: element.split("|")[1].trim(),
data: (element.indexOf("#ext#") > -1) ? "Guest" : "Member",
id: element.split("|")[0].trim()
};
_users.push(user)
});
}
else {
const user: IFacepilePersona = {
personaName: users.split("|")[1].trim(),
data: (users.indexOf("#ext#") > -1) ? "Guest" : "Member",
id: users.split("|")[0].trim()
};
_users.push(user)
}
return _users;
}

View File

@ -0,0 +1,4 @@
define([], function() {
return {
}
});

View File

@ -0,0 +1,7 @@
declare interface ISharingWebPartStrings {
}
declare module 'SharingWebPartStrings' {
const strings: ISharingWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,37 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.7/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"noImplicitAny": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}