Merge pull request #4301 from SPFxAppDev/react-password-vault

This commit is contained in:
Hugo Bernier 2023-11-18 16:16:44 -08:00 committed by GitHub
commit f80d9918b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
53 changed files with 71046 additions and 2 deletions

View File

@ -0,0 +1,39 @@
// For more information on how to run this SPFx project in a VS Code Remote Container, please visit https://aka.ms/spfx-devcontainer
{
"name": "SPFx 1.18.1",
"image": "docker.io/m365pnp/spfx:1.18.1",
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [
4321,
35729
],
"portsAttributes": {
"4321": {
"protocol": "https",
"label": "Manifest",
"onAutoForward": "silent",
"requireLocalPort": true
},
// Not needed for SPFx>= 1.12.1
// "5432": {
// "protocol": "https",
// "label": "Workbench",
// "onAutoForward": "silent"
// },
"35729": {
"protocol": "https",
"label": "LiveReload",
"onAutoForward": "silent",
"requireLocalPort": true
}
},
"postCreateCommand": "bash .devcontainer/spfx-startup.sh",
"remoteUser": "node"
}

View File

@ -0,0 +1,33 @@
echo
echo -e "\e[1;94mInstalling Node dependencies\e[0m"
npm install
## commands to create dev certificate and copy it to the root folder of the project
echo
echo -e "\e[1;94mGenerating dev certificate\e[0m"
gulp trust-dev-cert
# Convert the generated PEM certificate to a CER certificate
openssl x509 -inform PEM -in ~/.rushstack/rushstack-serve.pem -outform DER -out ./spfx-dev-cert.cer
# Copy the PEM ecrtificate for non-Windows hosts
cp ~/.rushstack/rushstack-serve.pem ./spfx-dev-cert.pem
## add *.cer to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.cer' ./.gitignore
then
echo "# .CER Certificates" >> .gitignore
echo "*.cer" >> .gitignore
fi
## add *.pem to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.pem' ./.gitignore
then
echo "# .PEM Certificates" >> .gitignore
echo "*.pem" >> .gitignore
fi
echo
echo -e "\e[1;92mReady!\e[0m"
echo -e "\n\e[1;94m**********\nOptional: if you plan on using gulp serve, don't forget to add the container certificate to your local machine. Please visit https://aka.ms/spfx-devcontainer for more information\n**********"

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': 0,
// 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': 0,
// 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/no-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: {}
}
]
};

35
samples/react-password-vault/.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# 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
*.scss.d.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,2 @@
shamefully-hoist=true
auto-install-peers=true

View File

@ -0,0 +1 @@
v16.13.2

View File

@ -0,0 +1,5 @@
{
"recommendations": [
"msjsdiag.debugger-for-chrome"
]
}

View File

@ -0,0 +1,26 @@
{
/**
* Install Chrome Debugger Extension for Visual Studio Code to debug your components with the
* Chrome browser: https://aka.ms/spfx-debugger-extensions
*/
"version": "0.2.0",
"configurations": [{
"name": "Hosted workbench",
"type": "pwa-chrome",
"request": "launch",
"url": "https://enter-your-SharePoint-site/_layouts/workbench.aspx",
"webRoot": "${workspaceRoot}",
"sourceMaps": true,
"sourceMapPathOverrides": {
"webpack:///.././src/*": "${webRoot}/src/*",
"webpack:///../../../src/*": "${webRoot}/src/*",
"webpack:///../../../../src/*": "${webRoot}/src/*",
"webpack:///../../../../../src/*": "${webRoot}/src/*"
},
"runtimeArgs": [
"--remote-debugging-port=9222",
"-incognito"
]
}
]
}

View File

@ -0,0 +1,13 @@
// Place your settings in this file to overwrite default and user settings.
{
// Configure glob patterns for excluding files and folders in the file explorer.
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/bower_components": true,
"**/coverage": true,
"**/lib-amd": true,
"src/**/*.scss.ts": true
},
"typescript.tsdk": ".\\node_modules\\typescript\\lib"
}

View File

@ -0,0 +1,17 @@
{
"@microsoft/generator-sharepoint": {
"isCreatingSolution": true,
"environment": "spo",
"version": "1.16.1",
"libraryName": "sp-fx-app-dev-simple-password-vault",
"libraryId": "d091b369-f63d-459c-846e-5a4323e31745",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart",
"nodeVersion": "16.19.0",
"sdkVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.4.1"
}
}
}

View File

@ -0,0 +1,107 @@
# Password vault
## Summary
This web part allows you to protect your data, such as the username, password or even just a text note (rich text). This data is protected with a master password that you can choose yourself.
The data is encrypted and stored in the properties of the web part. This means that the data is not in plain text and can only be decrypted by entering the master password. You can also use this web part in SharePoint and Microsoft Teams (as a tab)
### Edit Mode
![Edit Mode](assets/PWVaultEditMode.png)
### Display Mode
![Display Mode](assets/PasswordVaultDisplayMode.png)
### Maintenance Mode
![Maintenance Mode](assets/PWVaultMaintenanceMode.png)
## Compatibility
| :warning: Important |
|:---------------------------|
| Every SPFx version is optimally compatible with specific versions of Node.js. In order to be able to build this sample, you need to 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.16.1](https://img.shields.io/badge/SPFx-1.16.1-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://learn.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Microsoft 365 tenant](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/m365devprogram)
## Contributors
* [Sergej Schwabauer](https://github.com/SPFxAppDev)
## Version history
Version|Date|Comments
-------|----|--------
1.0|October 27, 2023|Initial release
## Minimal path to awesome
* Clone this repository (or [download this solution as a .ZIP file](https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-password-vault) then unzip it)
* From your command line, change your current directory to the directory containing this sample (`react-password-vault`, located under `samples`)
* in the command line run:
* `npm install`
* `gulp serve` or `npm run serve` for `spfx-fast-serve`
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit <https://aka.ms/spfx-devcontainer> for further instructions.
## Features
This web part illustrates the following concepts on top of the SharePoint Framework:
* [Fluent UI React Controls](https://developer.microsoft.com/en-us/fluentui#/controls/web)
* [CryptoJS](https://cryptojs.gitbook.io/docs/)
The web part comes with this features
* Protect all data with a master password
* store as many usernames, passwords and notes as you want (similar "look and feel" as in SharePoint Standard, when you want to place a new web part)
* Copy username and password to clipboard
* Hide/display password in text field
* Close the safe manually or the safe will be closed automatically after a few minutes
* No possibility to "reset" the master password if the password is forgotten
* The data is NOT stored in plain text
## Video
[![Building SPFx Password Vault Web Part](./assets/video-thumbnail.jpg)](https://www.youtube.com/watch?v=y38RFnrrxrI "Building SPFx Password Vault Web Part")
## Help
We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.
You can try looking at [issues related to this sample](https://github.com/pnp/sp-dev-fx-webparts/issues?q=label%3A%22sample%3A%20react-password-vault%22) to see if anybody else is having the same issues.
You can also try looking at [discussions related to this sample](https://github.com/pnp/sp-dev-fx-webparts/discussions?discussions_q=react-password-vault) and see what the community is saying.
If you encounter any issues using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-password-vault&template=bug-report.yml&sample=react-password-vault&authors=@SPFxAppDev&title=react-password-vault%20-%20).
For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aquestion%2Csample%3A%20react-password-vault&template=question.yml&sample=react-password-vault&authors=@SPFxAppDev&title=react-password-vault%20-%20).
Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aenhancement%2Csample%3A%20react-password-vault&template=suggestion.yml&sample=react-password-vault&authors=@SPFxAppDev&title=react-password-vault%20-%20).
## 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-password-vault" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

View File

@ -0,0 +1,69 @@
[
{
"name": "pnp-sp-dev-spfx-web-parts-react-password-vault",
"source": "pnp",
"title": "Password Vault",
"shortDescription": "This web part allows you to protect your data, such as the username, password or even just a text note (rich text). This data is protected with a master password that you can choose yourself.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-password-vault",
"downloadUrl": "https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-password-vault",
"longDescription": [
"This web part allows you to protect your data, such as the username, password or even just a text note (rich text). This data is protected with a master password that you can choose yourself.",
"The data is encrypted and stored in the properties of the web part. This means that the data is not in plain text and can only be decrypted by entering the master password. You can also use this web part in SharePoint and Microsoft Teams (as a tab)"
],
"creationDateTime": "2023-10-27",
"updateDateTime": "2023-10-27",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "React"
},
{
"key": "SPFX-VERSION",
"value": "1.18.1"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-password-vault/assets/PasswordVaultDisplayMode.png",
"alt": "Web Part Preview"
},
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-password-vault/assets/PWVaultEditMode.png",
"alt": "Web Part Preview"
},
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-password-vault/assets/PWVaultMaintenanceMode.png",
"alt": "Web Part Preview"
},
{
"type": "video",
"order": 101,
"url": "https://www.youtube.com/embed/y38RFnrrxrI?si=EWoEglXZfqiKCs3V",
"alt": "Community demo of the web part"
}
],
"authors": [
{
"gitHubAccount": "SPFxAppDev",
"pictureUrl": "https://github.com/SPFxAppDev.png",
"name": "Sergej Schwabauer"
}
],
"references": [
{
"name": "Build your first SharePoint client-side web part",
"description": "Client-side web parts are client-side components that run in the context of a SharePoint page. Client-side web parts can be deployed to SharePoint environments that support the SharePoint Framework. You can also use modern JavaScript web frameworks, tools, and libraries to build them.",
"url": "https://docs.microsoft.com/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
}
]

View File

@ -0,0 +1,19 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"password-vault-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/passwordVault/PasswordVaultWebPart.js",
"manifest": "./src/webparts/passwordVault/PasswordVaultWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"PasswordVaultWebPartStrings": "lib/webparts/passwordVault/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": "sp-fx-app-dev-simple-password-vault",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,30 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "SPFx app dev Simple Password Vault",
"id": "d091b369-f63d-459c-846e-5a4323e31745",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "SPFXAppDev",
"websiteUrl": "https://spfx-app.dev/",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": ""
},
"features": [
{
"title": "SPFxAppDev PasswordVaultWebPart Feature",
"description": "The feature that activates PasswordVaultWebPart from the SPFxAppDev PasswordVaultWebPart solution.",
"id": "2c2420ee-ffdf-4dce-800f-d0d09f02bffd",
"version": "1.0.0.0",
"componentIds": ["2c2420ee-ffdf-4dce-800f-d0d09f02bffd"]
}
]
},
"paths": {
"zippedPackage": "solution/spfxappdev-simple-password-vault.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://enter-your-SharePoint-site/_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,6 @@
{
"$schema": "https://raw.githubusercontent.com/s-KaiNet/spfx-fast-serve/master/schema/config.latest.schema.json",
"cli": {
"isLibraryComponent": false
}
}

View File

@ -0,0 +1,31 @@
/*
* User webpack settings file. You can add your own settings here.
* Changes from this file will be merged into the base webpack configuration file.
* This file will not be overwritten by the subsequent spfx-fast-serve calls.
*/
const path = require('path');
// you can add your project related webpack configuration here, it will be merged using webpack-merge module
// i.e. plugins: [new webpack.Plugin()]
const webpackConfig = {
resolve: {
alias: {
"@webparts": path.resolve(__dirname, "..", "src/webparts"),
"@src": path.resolve(__dirname, "..", "src"),
}
}
}
// for even more fine-grained control, you can apply custom webpack settings using below function
const transformConfig = function (initialWebpackConfig) {
// transform the initial webpack config here, i.e.
// initialWebpackConfig.plugins.push(new webpack.Plugin()); etc.
return initialWebpackConfig;
}
module.exports = {
webpackConfig,
transformConfig
}

View File

@ -0,0 +1,43 @@
'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.`);
build.addSuppression(/Warning - \[sass\] The local CSS class/gi);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
/* fast-serve */
const { addFastServe } = require("spfx-fast-serve-helpers");
addFastServe(build);
/* end of fast-serve */
/* CUSTOM ALIAS */
const path = require('path');
build.configureWebpack.mergeConfig({
additionalConfiguration: (generatedConfiguration) => {
if(!generatedConfiguration.resolve.alias){
generatedConfiguration.resolve.alias = {};
}
// webparts folder
generatedConfiguration.resolve.alias['@webparts'] = path.resolve( __dirname, 'lib/webparts')
//root src folder
generatedConfiguration.resolve.alias['@src'] = path.resolve( __dirname, 'lib')
return generatedConfiguration;
}
});
/* CUSTOM ALIAS END */
build.initialize(require('gulp'));

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,48 @@
{
"name": "sp-fx-app-dev-simple-password-vault",
"version": "1.1.0",
"private": true,
"main": "lib/index.js",
"engines": {
"node": ">=16.13.0 <17.0.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test",
"serve": "gulp bundle --custom-serve --max_old_space_size=4096 && fast-serve"
},
"dependencies": {
"@microsoft/sp-core-library": "1.16.1",
"@microsoft/sp-lodash-subset": "1.16.1",
"@microsoft/sp-office-ui-fabric-core": "1.16.1",
"@microsoft/sp-property-pane": "1.16.1",
"@microsoft/sp-webpart-base": "1.16.1",
"@pnp/spfx-controls-react": "2.9.0",
"@spfxappdev/framework": "^1.0.7",
"@types/crypto-js": "^4.1.1",
"crypto-js": "^4.1.1",
"office-ui-fabric-react": "7.199.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.16.1",
"@microsoft/eslint-plugin-spfx": "1.16.1",
"@microsoft/decorators": "^1.16.1",
"@microsoft/rush-stack-compiler-4.5": "0.2.2",
"@microsoft/sp-application-base": "1.16.1",
"@microsoft/sp-build-web": "1.16.1",
"@microsoft/sp-module-interfaces": "1.16.1",
"@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-plugin-react-hooks": "4.3.0",
"gulp": "~4.0.2",
"spfx-fast-serve-helpers": "~1.16.0",
"typescript": "4.5.5"
}
}

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,7 @@
import { ModuleType } from "./ModuleType.enum";
export interface IModule {
id: string;
type: ModuleType;
data: string;
}

View File

@ -0,0 +1,3 @@
export interface IVaultData {
masterPW: string;
}

View File

@ -0,0 +1,5 @@
export enum ModuleType {
PasswordField = "PasswordField",
UserField = "UserField",
NoteField = "NoteField"
}

View File

@ -0,0 +1,3 @@
export { IVaultData } from './IVaultData';
export { ModuleType } from './ModuleType.enum';
export { IModule } from './IModule';

View File

@ -0,0 +1,184 @@
import * as CryptoJS from 'crypto-js';
import { isNullOrEmpty, toBoolean } from '@spfxappdev/utility';
import { SessionStorage } from '@spfxappdev/storage';
import { ModuleType } from '@src/models';
export interface IPasswordVaultService {
decryptModuleData(moduleType: ModuleType, encryptedData: string): string;
encryptModuleData(moduleType: ModuleType, plainData: string): string;
open(masterPW: string, encryptedMasterPW: string): boolean;
isOpen(): boolean;
close(): void;
setMasterPassword(plainPassword: string): string;
}
export class PasswordVaultService implements IPasswordVaultService {
private cache: SessionStorage = null;
private secretKey: string = "SPFxAppDevSecret";
private instanceId: string = "";
private encryptedInstanceId: string = "";
private encryptedMasterPWInstanceId: string = "";
private secretWasSet: boolean = false;
private isVaultOpen: boolean = false;
private get plainMasterPW() : string {
return this.decrypt(this.encryptedMasterPw, this.masterSecretKey);
}
private encryptedMasterPw: string = "";
private hashedMasterPw: string = "";
private get masterSecretKey(): string {
return `${this.secretKey}_M@5t€r`;
}
private get userNameSecretKey(): string {
return `${this.secretKey}_U5€r_${this.plainMasterPW}`;
}
private get passwordSecretKey(): string {
return `${this.secretKey}_P@5Sw0Rd_${this.plainMasterPW}`;
}
private get noteSecretKey(): string {
return `${this.secretKey}_n0t3_${this.plainMasterPW}`;
}
constructor(instanceId: string) {
this.instanceId = instanceId;
this.encryptedInstanceId = CryptoJS.HmacSHA256(instanceId, instanceId).toString();
this.setSecret(`SPFxAppDevSecret_${instanceId}`);
this.encryptedMasterPWInstanceId = CryptoJS.HmacSHA256(`${instanceId}_Master`, this.masterSecretKey).toString();
const cacheSettings = {
...SessionStorage.DefaultSettings,
...{
DefaultTimeToLife: 5
}
};
this.cache = new SessionStorage(cacheSettings);
this.isVaultOpen = toBoolean(this.cache.get(this.encryptedInstanceId));
const pwFromCache = this.cache.get(this.encryptedMasterPWInstanceId);
this.encryptedMasterPw = isNullOrEmpty(pwFromCache) ? "" : pwFromCache;
if(!isNullOrEmpty(this.encryptedMasterPw)) {
const plainPassword: string = this.decrypt(this.encryptedMasterPw, this.masterSecretKey);
this.hashedMasterPw = CryptoJS.HmacSHA256(plainPassword, this.masterSecretKey).toString();
}
}
public encryptModuleData(moduleType: ModuleType, plainData: string): string {
switch(moduleType) {
case ModuleType.UserField: return this.encryptUsername(plainData);
case ModuleType.PasswordField: return this.encryptPassword(plainData);
case ModuleType.NoteField: return this.encryptNote(plainData)
}
}
public decryptModuleData(moduleType: ModuleType, encryptedData: string): string {
if(!this.isVaultOpen) {
return "";
}
switch(moduleType) {
case ModuleType.UserField: return this.decryptUsername(encryptedData);
case ModuleType.PasswordField: return this.decryptPassword(encryptedData);
case ModuleType.NoteField: return this.decryptNote(encryptedData)
}
}
public open(masterPW: string, encryptedMasterPW: string): boolean {
const masterPWEncrypted = CryptoJS.HmacSHA256(masterPW, this.masterSecretKey);
if(masterPWEncrypted.toString() === encryptedMasterPW) {
this.isVaultOpen = true;
this.cache.set(this.encryptedInstanceId, true);
this.encryptedMasterPw = this.encrypt(masterPW, this.masterSecretKey);
this.cache.set(this.encryptedMasterPWInstanceId, this.encryptedMasterPw);
this.hashedMasterPw = masterPWEncrypted.toString();
return true;
}
return false;
}
public isOpen(): boolean {
return this.isVaultOpen;
}
public close(): void {
this.isVaultOpen = false;
this.cache.set(this.encryptedInstanceId, false);
this.cache.remove(this.encryptedMasterPWInstanceId);
this.encryptedMasterPw = "";
}
public setMasterPassword(plainPassword: string): string {
this.encryptedMasterPw = this.encrypt(plainPassword, this.masterSecretKey);
this.hashedMasterPw = CryptoJS.HmacSHA256(plainPassword, this.masterSecretKey).toString();
this.cache.set(this.encryptedMasterPWInstanceId, this.encryptedMasterPw);
return this.hashedMasterPw;
}
private setSecret(secretKey: string): void {
if(this.secretWasSet) {
return;
}
this.secretWasSet = true;
this.secretKey = secretKey;
}
private encrypt(text: string, secret: string): string {
if(isNullOrEmpty(text)) {
return null;
}
return CryptoJS.AES.encrypt(text, secret).toString(CryptoJS.format.OpenSSL);
}
private decrypt(encryptedText: string, secret: string): string {
if(isNullOrEmpty(encryptedText)) {
return null;
}
const bytes = CryptoJS.AES.decrypt(encryptedText, secret);
return bytes.toString(CryptoJS.enc.Utf8);
}
private encryptPassword(password: string): string {
return this.encrypt(password, this.passwordSecretKey);
}
private decryptPassword(encryptedPassword: string): string {
return this.decrypt(encryptedPassword, this.passwordSecretKey);
}
private encryptUsername(username: string): string {
return this.encrypt(username, this.userNameSecretKey);
}
private decryptUsername(encryptedUsername: string): string {
return this.decrypt(encryptedUsername, this.userNameSecretKey);
}
private encryptNote(note: string): string {
return this.encrypt(note, this.noteSecretKey);
}
private decryptNote(encryptedNote: string): string {
return this.decrypt(encryptedNote, this.noteSecretKey);
}
}

View File

@ -0,0 +1,57 @@
import {
IPropertyPaneField,
PropertyPaneFieldType,
IPropertyPaneCustomFieldProps
} from '@microsoft/sp-property-pane';
export interface IPropertyPaneAboutWebPartProps {
/**
* An UNIQUE key indicates the identity of this control
*/
key: string;
/**
* An UNIQUE key indicates the identity of this control
*/
html: string;
}
export interface IPropertyWebPartInformationPropsInternal extends IPropertyPaneAboutWebPartProps, IPropertyPaneCustomFieldProps {
}
class PropertyPaneAboutWebPartBuilder implements IPropertyPaneField<IPropertyPaneAboutWebPartProps> {
//Properties defined by IPropertyPaneField
public targetProperty: string;
public type: PropertyPaneFieldType = PropertyPaneFieldType.Custom;
public properties: IPropertyWebPartInformationPropsInternal;
private elem: HTMLElement;
public constructor(_properties: IPropertyPaneAboutWebPartProps) {
this.properties = {
key: _properties.key,
html: _properties.html,
onRender: this.onRender.bind(this)
};
}
public render(): void {
if (!this.elem) {
return;
}
this.onRender(this.elem);
}
private onRender(elem: HTMLElement, ctx?: any, changeCallback?: (targetProperty?: string, newValue?: any) => void): void {
if (!this.elem) {
this.elem = elem;
}
this.elem.innerHTML = this.properties.html;
}
}
export function PropertyPaneAboutWebPart(properties: IPropertyPaneAboutWebPartProps): IPropertyPaneField<IPropertyPaneAboutWebPartProps> {
return new PropertyPaneAboutWebPartBuilder(properties);
}

View File

@ -0,0 +1,39 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "2c2420ee-ffdf-4dce-800f-d0d09f02bffd",
"alias": "PasswordVaultWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart", "TeamsTab"],
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "Password vault" },
"description": { "default": "Simple Password vault webpart" },
"officeFabricIconFontName": "ProtectRestrict",
"properties": {
"masterPW": "",
"modules": [
{
"id": "718def44-3e0c-48bf-8843-ccabefece27e",
"data": "",
"type": "UserField"
},
{
"id": "65025036-e345-43f7-9561-6d3026294b2e",
"data": "",
"type": "PasswordField"
},
]
}
}]
}

View File

@ -0,0 +1,163 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import { IPropertyPaneConfiguration } from '@microsoft/sp-property-pane';
import { ISPFxAppDevClientSideWebPartProps, SPFxAppDevClientSideWebPart } from '@spfxappdev/framework';
import PasswordVault, { IPasswordVaultProps } from './components/PasswordVault';
import { PasswordVaultService, IPasswordVaultService } from '@src/services/PasswordVaultService';
import { IVaultData } from '@src/models/IVaultData';
import { PropertyPaneAboutWebPart } from '../PropertyPaneAboutWebPart';
import * as strings from 'PasswordVaultWebPartStrings';
import { IModule, ModuleType } from '@src/models';
import { Guid } from '@microsoft/sp-core-library';
export interface IPasswordVaultWebPartProps extends ISPFxAppDevClientSideWebPartProps, IVaultData {
modules: IModule[];
}
export default class PasswordVaultWebPart extends SPFxAppDevClientSideWebPart<IPasswordVaultWebPartProps> {
private passwordVaultService: IPasswordVaultService = null;
public onInit(): Promise<void> {
return new Promise<void>((resolve, reject) => {
super.onInit().then(() => {
this.passwordVaultService = new PasswordVaultService(this.context.instanceId);
this.migrateDataFromOldVersion();
return resolve();
});
});
}
public render(): void {
const element: React.ReactElement<IPasswordVaultProps> = React.createElement(
PasswordVault,
{
WebPart: this,
Title: this.properties.Title,
passwordVaultService: this.passwordVaultService,
masterPW: this.properties.masterPW,
modules: this.properties.modules||[],
onTitleChanged: (title: string): void => {
this.onTitleChanged(title);
},
onVaultDataChanged: (encryptedMasterPw: string, modules: IModule[]): void => {
this.onVaultDataChanged(encryptedMasterPw, modules);
},
onVaultPasswordChanged: (encryptedMasterPw: string): void => {
this.onMasterPasswordChanged(encryptedMasterPw);
}
}
);
ReactDom.render(element, this.domElement);
}
private migrateDataFromOldVersion(): void {
const oldProps: any = this.properties as any;
this.properties.modules = this.properties.modules||[];
if (!this.helper.functions.isNullOrEmpty(oldProps.username)) {
this.properties.modules.push({
id: Guid.newGuid().toString(),
type: ModuleType.UserField,
data: oldProps.username
});
}
if (!this.helper.functions.isNullOrEmpty(oldProps.password)) {
this.properties.modules.push({
id: Guid.newGuid().toString(),
type: ModuleType.PasswordField,
data: oldProps.password
});
}
if (!this.helper.functions.isNullOrEmpty(oldProps.note)) {
this.properties.modules.push({
id: Guid.newGuid().toString(),
type: ModuleType.NoteField,
data: oldProps.note
});
}
this.removePropertiesFromOldVersion();
}
private removePropertiesFromOldVersion(): void {
const oldProps: any = this.properties as any;
if (this.helper.functions.isset(oldProps.username)) {
delete oldProps.username;
}
if (this.helper.functions.isset(oldProps.password)) {
delete oldProps.password;
}
if (this.helper.functions.isset(oldProps.note)) {
delete oldProps.note;
}
}
public getLogCategory(): string {
return 'PasswordVaultWebPart';
}
public onTitleChanged(title: string): void {
this.properties.Title = title;
}
public onVaultDataChanged(encryptedMasterPW: string, modules: IModule[]): void {
this.properties.masterPW = encryptedMasterPW;
this.properties.modules = modules;
this.removePropertiesFromOldVersion();
}
private onMasterPasswordChanged(encryptedMasterPW: string): void {
this.properties.masterPW = encryptedMasterPW;
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: ''
},
groups: [
{
groupName: strings.WebPartPropertyGroupAbout,
groupFields: [
PropertyPaneAboutWebPart({
key: `bbc94d63-5630-4077-b6a8-6b8d37551766_${this.context.instanceId}`,
html: `
<div>
<h3>Author</h3>
<a href="https://spfx-app.dev/" data-interception="off" target="_blank">SPFx-App.dev</a>
<h3>Version</h3>
${this.context.manifest.version}
<h3>Web Part Instance id</h3>
${this.context.instanceId}
</div>
<div>
<a href="https://github.com/SPFxAppDev/sp-passwordvault-webpart" target="_blank">More info</a>
</div>
`
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,96 @@
import * as React from 'react';
import styles from './PasswordVault.module.scss';
import { cssClasses, isNullOrEmpty } from '@spfxappdev/utility';
import { ActionButton, Callout, Icon, TooltipHost, DirectionalHint } from 'office-ui-fabric-react';
import { ModuleType } from '@src/models';
import * as strings from 'PasswordVaultWebPartStrings';
export interface IAddNewModuleProps {
onModuleSelected(module: ModuleType): void;
}
interface IAddNewModuleState {
showAddNewCallout: boolean;
}
export default class AddNewModule extends React.Component<IAddNewModuleProps, IAddNewModuleState> {
private addNewButtonRef: HTMLButtonElement = null;
public state: IAddNewModuleState = {
showAddNewCallout: false
};
public render(): React.ReactElement<IAddNewModuleProps> {
const callOutVisbileClass: string = styles["active-separator"];
const isCallOutVisibleClass = {};
isCallOutVisibleClass[callOutVisbileClass] = this.state.showAddNewCallout;
return (
<div className={cssClasses(styles["separator-container"], isCallOutVisibleClass)}>
<button type="button"
aria-haspopup="true"
aria-label={strings.AddNewModuleLabel}
ref={(ref: HTMLButtonElement) => { this.addNewButtonRef = ref }}
onClick={() => {
this.setState({
showAddNewCallout: true
});
}}>
<TooltipHost content={strings.AddNewModuleLabel}
// id={this.WebPart.instanceId + "_addNewControl"}
>
<Icon iconName="Add" />
</TooltipHost>
</button>
{this.renderAddNewCallout()}
</div>
)
}
private renderAddNewCallout(): JSX.Element {
if(isNullOrEmpty(this.addNewButtonRef)) {
return <></>;
}
const icon = this.addNewButtonRef.querySelector(".ms-TooltipHost");
return (
<>
<Callout
target={icon}
className={"addnew-callout"}
hidden={!this.state.showAddNewCallout}
directionalHint={DirectionalHint.bottomCenter}
onDismiss={() => {
this.setState({
showAddNewCallout: false
});
}}
>
<ActionButton iconProps={{iconName: "PasswordField"}} onClick={() => { this.onModuleSelected(ModuleType.PasswordField); }}>
<div>{strings.PasswordModuleLabel}</div>
</ActionButton>
<ActionButton iconProps={{iconName: "UserOptional"}} onClick={() => { this.onModuleSelected(ModuleType.UserField); }}>
<div>{strings.UsernameModuleLabel}</div>
</ActionButton>
<ActionButton iconProps={{iconName: "EditNote"}} onClick={() => { this.onModuleSelected(ModuleType.NoteField); }}>
<div>{strings.NoteModuleLabel}</div>
</ActionButton>
</Callout>
</>
);
}
private onModuleSelected(module: ModuleType): void {
this.setState({
showAddNewCallout: false
});
this.props.onModuleSelected(module);
}
}

View File

@ -0,0 +1,50 @@
import * as React from 'react';
import * as strings from 'PasswordVaultWebPartStrings';
import { Label } from 'office-ui-fabric-react';
import { RichText } from "@pnp/spfx-controls-react/lib/RichText";
export interface INoteFieldProps {
isDisplayMode: boolean;
defaultValue: string;
onChange?(newValue: string): string;
}
interface INoteFieldState {
}
export default class NoteField extends React.Component<INoteFieldProps, INoteFieldState> {
public state: INoteFieldState = {
};
public render(): React.ReactElement<INoteFieldProps> {
if(this.props.isDisplayMode) {
return this.renderDisplayMode();
}
return this.renderEditMode();
}
private renderDisplayMode(): JSX.Element {
return (<>
<RichText
isEditMode={false}
value={this.props.defaultValue}
/>
</>);
}
private renderEditMode(): JSX.Element {
return (<>
<Label>{strings.NoteLabel}</Label>
<RichText
isEditMode={true}
value={this.props.defaultValue}
onChange={(note: string): string => {
return this.props.onChange(note);
}}
/>
</>);
}
}

View File

@ -0,0 +1,100 @@
import * as React from 'react';
import { Callout, Icon, DirectionalHint, TextField, ITextField } from 'office-ui-fabric-react';
import * as strings from 'PasswordVaultWebPartStrings';
import { getDeepOrDefault, issetDeep, isset } from '@spfxappdev/utility';
export interface IPasswordFieldProps {
isDisplayMode: boolean;
defaultValue: string;
onChange?(newValue: string): void;
tabIndex?: number;
}
interface IPasswordFieldState {
isCopyPasswordToClipboardCalloutHidden: boolean;
}
export default class PasswordField extends React.Component<IPasswordFieldProps, IPasswordFieldState> {
private passwordTextFieldDomElement: HTMLInputElement = null;
public state: IPasswordFieldState = {
isCopyPasswordToClipboardCalloutHidden: false
};
public render(): React.ReactElement<IPasswordFieldProps> {
if(this.props.isDisplayMode) {
return this.renderDisplayMode();
}
return this.renderEditMode();
}
public renderDisplayMode(): JSX.Element {
const showCopyToClipboard: boolean = issetDeep(window, "navigator.clipboard.writeText");
return (<>
<TextField
label={strings.PasswordLabel}
type="password"
disabled={true}
canRevealPassword={true}
defaultValue={this.props.defaultValue}
componentRef={(input: ITextField) => {
this.passwordTextFieldDomElement = getDeepOrDefault(input, "_textElement.current", null);
}}
onRenderSuffix={() => {
if(!showCopyToClipboard) {
return <></>;
}
return (<Icon iconName={"Copy"} className="copy-icon" onClick={() => {
this.copyToClipboard(this.props.defaultValue);
}} />);
}}
/>
{showCopyToClipboard && isset(this.passwordTextFieldDomElement) &&
<Callout
hidden={this.state.isCopyPasswordToClipboardCalloutHidden}
target={this.passwordTextFieldDomElement.parentElement}
isBeakVisible={false}
className={"clipboard-callout"}
directionalHint={DirectionalHint.rightCenter}
>
{strings.PasswordCopiedLabel}
</Callout>
}
</>)
}
public renderEditMode(): JSX.Element {
return (<><TextField
label={strings.PasswordLabel}
type="password"
canRevealPassword={true}
tabIndex={this.props.tabIndex}
onChange={(ev: any, newValue: string) => {
this.props.onChange(newValue);
}}
defaultValue={this.props.defaultValue}
/></>);
}
private copyToClipboard(text: string): void {
window.navigator.clipboard.writeText(text).then(() => {
this.setState({
isCopyPasswordToClipboardCalloutHidden: false
});
window.setTimeout(() => {
this.setState({
isCopyPasswordToClipboardCalloutHidden: true
});
}, 2000);
});
}
}

View File

@ -0,0 +1,281 @@
// @import '~@fluentui/react/dist/sass/References.scss';
@import '~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss';
.passwordVault {
display: block;
.separator-container {
display: flex;
justify-content: center;
margin: 4px 0;
width: 100%;
.separator {
&::before {
height: 3px;
}
}
button {
max-width: calc(100% - 8px);
width: 100%;
opacity: 0;
background: transparent;
border: none;
cursor: pointer;
height: 24px;
outline: none;
padding: 0;
position: relative;
user-select: none;
&::before {
border-top-style: solid;
border-top-width: 2px;
border-top-color: $ms-color-neutralTertiary;
content: "";
height: 0;
position: absolute;
top: 50%;
left: 0;
transition: opacity .3s ease-in-out;
width: 100%;
}
:global {
.ms-TooltipHost {
border-radius: 50%;
border-style: solid;
border-width: 2px;
border-color: $ms-color-neutralTertiary;
box-sizing: border-box;
height: 24px;
line-height: 12px;
margin: 0 auto;
padding: 4px;
position: relative;
transition: opacity .3s ease-in-out;
width: 24px;
background-color: $ms-color-neutralTertiary;
display: block;
i {
vertical-align: middle;
color: #fff;
}
}
}
}
&:hover, &.active-separator {
button {
opacity: 1;
}
}
button:focus {
opacity: 1;
}
}
.edit-container {
border: dotted 1px $ms-color-themePrimary;
&--header {
background-color: $ms-color-neutralLighter;
.delete-btn {
float: right;
}
button:disabled,
button[disabled] {
cursor: not-allowed;
i {
color: $ms-color-neutralTertiaryAlt;
}
}
}
&--content {
padding: 10px;
}
}
:global {
.ms-CommandBar {
padding: 0 0 10px;
}
}
}
:global {
.ql-editor
{
padding: 8px 0 0 !important;
}
.ql-editor[contenteditable='true'] {
padding: 8px 10px !important;
}
.addnew-callout {
display: block;
min-height: 200px;
.ms-Callout-main {
min-height: 200px;
padding-top: 40px;
}
.ms-Button--action {
margin: 10px;
span {
display: block;
& i {
font-size: 32px;
}
}
}
}
.spfxappdev-grid {
box-sizing: border-box;
zoom: 1;
padding: 0 8px;
&::before,
&::after {
display: table;
content: '';
line-height: 0;
-webkit-box-sizing: inherit;
box-sizing: inherit;
}
&::after {
clear: both;
}
&-row {
margin: 0 -8px;
box-sizing: border-box;
zoom: 1;
&::before,
&::after {
display: table;
content: '';
line-height: 0;
-webkit-box-sizing: inherit;
box-sizing: inherit;
}
&::after {
clear: both;
}
}
&-col {
position: relative;
min-height: 1px;
// padding-left: 8px;
// padding-right: 8px;
box-sizing: border-box;
float: left;
}
}
.spfxappdev-sm1 {
width: 8.33%
}
.spfxappdev-sm2 {
width: 16.66%;
}
.spfxappdev-sm3 {
width: 25%;
}
.spfxappdev-sm4 {
width: 33.33%;
}
.spfxappdev-sm5 {
width: 41.66%;
}
.spfxappdev-sm6 {
width: 50%;
}
.spfxappdev-sm7 {
width: 58.33%;
}
.spfxappdev-sm8 {
width: 66.66%;
}
.spfxappdev-sm9 {
width:75%;
}
.spfxappdev-sm10 {
width: 83.33%;
}
.spfxappdev-sm11 {
width: 91.66%;
}
.spfxappdev-sm12 {
width: 100%;
}
.spfxappdev-grid-col .ms-TextField-suffix {
cursor: pointer;
background-color: #fff;
color: $ms-color-themePrimary;
&:hover {
background-color: $ms-color-neutralLighter;
}
}
.spfxappdev-grid-col .ms-TextField-reveal.ms-Button {
cursor: pointer;
}
.spfxappdev-grid-col .quill {
border: solid 1px #000;
}
.grid-footer {
margin-top: 10px;
button {
margin-right: 15px;
}
}
.clipboard-callout {
margin-left: 20px;
padding: 10px;
background: $ms-color-themePrimary;
.ms-Callout-main {
background: $ms-color-themePrimary;
}
}
}

View File

@ -0,0 +1,599 @@
import * as React from 'react';
import styles from './PasswordVault.module.scss';
import { SPFxAppDevWebPartComponent, ISPFxAppDevWebPartComponentProps } from '@spfxappdev/framework';
import PasswordVaultWebPart from '../PasswordVaultWebPart';
import { IPasswordVaultService } from '@src/services/PasswordVaultService';
import { Dialog, DefaultButton, IconButton, MessageBar, MessageBarType, PrimaryButton, TextField, CommandBar, ICommandBarItemProps, DialogFooter, DialogType } from 'office-ui-fabric-react';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import * as strings from 'PasswordVaultWebPartStrings';
import AddNewModule from './AddNewModule';
import { IModule, ModuleType } from '@src/models';
import { Guid } from '@microsoft/sp-core-library';
import UserField from './UserField';
import PasswordField from './PasswordField';
import NoteField from './NoteField';
import { cloneDeep } from '@microsoft/sp-lodash-subset';
import '@spfxappdev/utility/lib/extensions/ArrayExtensions';
interface IPasswordVaultState {
isVaultOpen: boolean;
showWrongMasterInfo: boolean;
isSaveButtonDisabled: boolean;
modules: IModule[];
showChangePasswordDialog: boolean;
}
export interface IPasswordVaultProps extends ISPFxAppDevWebPartComponentProps<PasswordVaultWebPart> {
passwordVaultService: IPasswordVaultService;
masterPW?: string;
onTitleChanged?(value: string): void;
onVaultDataChanged?(encryptedMaster: string, modules: IModule[]): void;
onVaultPasswordChanged?(encryptedMaster: string): void;
modules?: IModule[];
}
export default class PasswordVault extends SPFxAppDevWebPartComponent<PasswordVaultWebPart, IPasswordVaultProps, IPasswordVaultState> {
public static defaultProps: IPasswordVaultProps = {
Title: "",
WebPart: null,
passwordVaultService: null
};
public state: IPasswordVaultState = {
isVaultOpen: this.isVaultOpen,
showWrongMasterInfo: false,
isSaveButtonDisabled: this.helper.functions.isNullOrEmpty(this.props.masterPW),
modules: cloneDeep(this.props.modules),
showChangePasswordDialog: false
};
private get isVaultOpen(): boolean {
let showForm: boolean = false;
if(this.WebPart.IsPageInEditMode) {
showForm = this.helper.functions.isNullOrEmpty(this.props.masterPW);
}
return showForm ||
(!this.helper.functions.isNullOrEmpty(this.props.masterPW) &&
this.props.passwordVaultService.isOpen());
}
private enteredMasterPW: string = "";
private repeatedEnteredMasterPW: string = "";
private encryptedModuleData: Record<string, string> = {};
private decryptedModuleData: Record<string, string> = {};
private isNewVault: boolean = true;
private currentMasterPW: string = "";
constructor(props: IPasswordVaultProps) {
super(props);
props.modules.forEach((module: IModule) => {
this.encryptedModuleData[module.id] = module.data;
this.decryptedModuleData[module.id] = this.props.passwordVaultService.decryptModuleData(module.type, module.data);
});
this.currentMasterPW = props.masterPW;
this.isNewVault = this.helper.functions.isNullOrEmpty(props.masterPW);
}
public componentDidUpdate(prevProps: Readonly<IPasswordVaultProps>, prevState: Readonly<IPasswordVaultState>, snapshot?: any): void {
if(prevProps.masterPW !== this.props.masterPW) {
this.currentMasterPW = this.props.masterPW;
}
}
public render(): React.ReactElement<IPasswordVaultProps> {
return (
<div className={styles.passwordVault}>
<WebPartTitle displayMode={this.WebPart.displayMode}
title={this.props.Title}
updateProperty={(title: string) => {
if(this.helper.functions.isFunction(this.props.onTitleChanged)) {
this.props.onTitleChanged(title);
}
}} />
{this.props.WebPart.IsPageInEditMode &&
this.renderEditMode()}
{!this.props.WebPart.IsPageInEditMode &&
this.renderDisplayMode()}
</div>
);
}
private renderDisplayMode(): JSX.Element {
return (
<>
{this.helper.functions.isNullOrEmpty(this.currentMasterPW) &&
<MessageBar messageBarType={MessageBarType.info}>
{strings.NoMasterPasswordSetLabel}
</MessageBar>
}
{this.renderOpenVaultForm()}
{this.state.isVaultOpen &&
<div className='spfxappdev-grid'>
{this.state.modules.map((module: IModule, index: number): JSX.Element => {
return this.renderModuleDisplayMode(module, index);
})}
<div className="spfxappdev-grid-row grid-footer">
<div className="spfxappdev-grid-col spfxappdev-sm12">
{!this.helper.functions.isNullOrEmpty(this.currentMasterPW) &&
<DefaultButton onClick={() => {
this.closeVault();
}}>
{strings.CloseVaultLabel}
</DefaultButton>
}
</div>
</div>
</div>
}
</>
);
}
private renderEditMode(): JSX.Element {
const showForm: boolean = this.state.isVaultOpen;
return (
<>
{this.renderOpenVaultForm()}
{showForm &&
<>
{this.renderCommandBarButtons()}
{this.renderChangePasswordDialog()}
{this.isNewVault &&
<MessageBar messageBarType={MessageBarType.warning}>
{strings.DontLoseMasterpasswordLabel}
</MessageBar>
}
<div className='spfxappdev-grid'>
{this.isNewVault && this.renderMasterPasswordControls()}
{this.state.modules.map((module: IModule, index: number): JSX.Element => {
return this.renderModuleEditMode(module, index);
})}
<div className={"spfxappdev-grid-row"}>
<AddNewModule onModuleSelected={(module: ModuleType) => {
this.onAddNewModule(module, this.state.modules.length + 1);
}} />
</div>
<div className="spfxappdev-grid-row grid-footer">
<div className="spfxappdev-grid-col spfxappdev-sm12">
<PrimaryButton disabled={this.state.isSaveButtonDisabled} onClick={() => {
this.onSaveButtonClick();
}}>
{strings.SaveLabel}
</PrimaryButton>
{!this.helper.functions.isNullOrEmpty(this.currentMasterPW) &&
<DefaultButton onClick={() => {
this.closeVault();
}}>
{strings.CloseVaultLabel}
</DefaultButton>
}
</div>
</div>
</div>
</>
}
</>
);
}
private renderModuleEditMode(module: IModule, index: number): JSX.Element {
return(
<>
<div className={"spfxappdev-grid-row"} key={module.id + '_addNewModuleContainer'}>
<AddNewModule onModuleSelected={(module: ModuleType) => {
this.onAddNewModule(module, index);
}} />
</div>
<div className="spfxappdev-grid-row" key={module.id}>
<div className="spfxappdev-grid-col spfxappdev-sm12">
<div className={styles["edit-container"]}>
<div className={styles["edit-container--header"]}>
<IconButton
className={styles["delete-btn"]}
iconProps={{ iconName: "Delete"}}
title={strings.DeleteModuleLabel}
onClick={() => {
this.onDeleteModule(index);
}}
/>
<IconButton
iconProps={{ iconName: "Up"}}
title={strings.MoveUpLabel}
disabled={this.state.modules.length === 1 || index === 0}
onClick={() => {
this.onMoveUp(index);
}}
/>
<IconButton
iconProps={{ iconName: "Down"}}
title={strings.MoveDownLabel}
disabled={this.state.modules.length === 1 || this.state.modules.length - 1 === index}
onClick={() => {
this.onMoveDown(index);
}}
/>
</div>
<div className={styles["edit-container--content"]}>
{module.type === ModuleType.UserField &&
<UserField defaultValue={this.decryptedModuleData[module.id]} tabIndex={index} onChange={(newVal: string) => {
this.decryptedModuleData[module.id] = newVal;
}} isDisplayMode={false} />
}
{module.type === ModuleType.PasswordField &&
<PasswordField defaultValue={this.decryptedModuleData[module.id]} tabIndex={index} onChange={(newVal: string) => {
this.decryptedModuleData[module.id] = newVal;
}} isDisplayMode={false} />
}
{module.type === ModuleType.NoteField &&
<NoteField defaultValue={this.decryptedModuleData[module.id]} onChange={(newVal: string) => {
this.decryptedModuleData[module.id] = newVal;
return newVal;
}} isDisplayMode={false} />
}
</div>
</div>
</div>
</div>
</>
);
}
private renderModuleDisplayMode(module: IModule, index: number): JSX.Element {
return(
<>
<div className="spfxappdev-grid-row" key={module.id}>
<div className="spfxappdev-grid-col spfxappdev-sm12">
{module.type === ModuleType.UserField &&
<UserField defaultValue={this.decryptedModuleData[module.id]} isDisplayMode={true} tabIndex={index} />
}
{module.type === ModuleType.PasswordField &&
<PasswordField defaultValue={this.decryptedModuleData[module.id]} isDisplayMode={true} tabIndex={index} />
}
{module.type === ModuleType.NoteField &&
<NoteField defaultValue={this.decryptedModuleData[module.id]} isDisplayMode={true} />
}
</div>
</div>
</>
);
}
private renderOpenVaultForm(): JSX.Element {
if(this.helper.functions.isNullOrEmpty(this.currentMasterPW)) {
return (<></>);
}
return (<>
{!this.state.isVaultOpen &&
<>
{this.state.showWrongMasterInfo &&
<MessageBar messageBarType={MessageBarType.error}>
{strings.WrongPasswordLabel}
</MessageBar>
}
<div className='spfxappdev-grid'>
<div className="spfxappdev-grid-row">
<div className="spfxappdev-grid-col spfxappdev-sm12">
<TextField
label={strings.MasterPasswordLabel}
type="password"
canRevealPassword={true}
onChange={(ev: any, newValue: string) => {
this.enteredMasterPW = newValue;
}}
onKeyUp={(ev: React.KeyboardEvent<HTMLInputElement>) => {
if(ev.keyCode === 13) {
this.onOpenVault();
}
}}
/>
</div>
</div>
<div className="spfxappdev-grid-row grid-footer">
<div className="spfxappdev-grid-col spfxappdev-sm12">
<PrimaryButton onClick={() => {
this.onOpenVault();
}}>
{strings.OpenVaultLabel}
</PrimaryButton>
</div>
</div>
</div>
</>
}
</>);
}
private renderMasterPasswordControls(): JSX.Element {
return (
<div className="spfxappdev-grid-row">
<div className="spfxappdev-grid-col spfxappdev-sm12">
<TextField
label={this.isNewVault ? strings.SetMasterPasswordLabel : strings.ChangeMasterPasswordLabel}
type="password"
required={this.isNewVault}
canRevealPassword={true}
onChange={(ev: any, newValue: string) => {
this.enteredMasterPW = newValue;
this.setState({
isSaveButtonDisabled: this.isSaveButtonDisabled()
});
}}
/>
</div>
<div className="spfxappdev-grid-col spfxappdev-sm12">
<TextField
label={strings.RepeatMasterPasswordLabel}
type="password"
required={this.isNewVault}
canRevealPassword={true}
onChange={(ev: any, newValue: string) => {
this.repeatedEnteredMasterPW = newValue;
this.setState({
isSaveButtonDisabled: this.isSaveButtonDisabled()
});
}}
/>
</div>
</div>);
}
private renderChangePasswordDialog(): JSX.Element {
return (
<Dialog
hidden={!this.state.showChangePasswordDialog}
dialogContentProps={{
title: strings.ChangeMasterPasswordDialogTitle,
type: DialogType.normal,
}}
onDismiss={() => { this.toggleChangePasswordDialogVisibility(); }}
>
<MessageBar messageBarType={MessageBarType.warning}>
{strings.DontLoseMasterpasswordLabel}
</MessageBar>
{this.renderMasterPasswordControls()}
<DialogFooter>
<PrimaryButton
disabled={this.state.isSaveButtonDisabled}
onClick={() => { this.onChangePasswordClick(); }}
text={strings.SaveLabel} />
<DefaultButton onClick={() => { this.toggleChangePasswordDialogVisibility(); }} text={strings.CancelLabel} />
</DialogFooter>
</Dialog>
);
}
private renderCommandBarButtons(): JSX.Element {
const buttons: ICommandBarItemProps[] = [];
const saveButton: ICommandBarItemProps = {
key: 'saveSettings',
text: strings.SaveLabel,
disabled: this.isSaveButtonDisabled(),
iconProps: { iconName: 'Save' },
onClick: () => {
this.onSaveButtonClick();
}
}
buttons.push(saveButton);
if(!this.isNewVault) {
const changeMasterPwButton: ICommandBarItemProps = {
key: 'changeMasterPassword',
text: strings.ChangeMasterPasswordButtonText,
iconProps: { iconName: 'PasswordField' },
onClick: () => {
this.toggleChangePasswordDialogVisibility();
},
}
buttons.push(changeMasterPwButton);
}
if(!this.helper.functions.isNullOrEmpty(this.currentMasterPW)) {
const closeButton: ICommandBarItemProps = {
key: 'closeVault',
text: strings.CloseVaultLabel,
iconProps: { iconName: 'Lock' },
onClick: () => {
this.closeVault();
}
}
buttons.push(closeButton);
}
return (
<CommandBar
items={buttons}
/>
);
}
private isSaveButtonDisabled(): boolean {
if((this.isNewVault || this.state.showChangePasswordDialog) && this.helper.functions.isNullOrEmpty(this.enteredMasterPW)) {
return true;
}
if(!this.enteredMasterPW.Equals(this.repeatedEnteredMasterPW, false)) {
return true;
}
return false;
}
private closeVault(): void {
this.props.passwordVaultService.close();
this.setState({
isVaultOpen: false,
showWrongMasterInfo: false
});
}
private onOpenVault(): void {
const props: IPasswordVaultProps = this.props;
const isCorrectPW = props.passwordVaultService.open(this.enteredMasterPW, this.currentMasterPW);
this.enteredMasterPW = "";
if(isCorrectPW) {
this.state.modules.forEach((module: IModule) => {
this.decryptedModuleData[module.id] = this.props.passwordVaultService.decryptModuleData(module.type, module.data);
});
}
this.setState({
isVaultOpen: isCorrectPW,
showWrongMasterInfo: !isCorrectPW
});
}
private onAddNewModule(moduleType: ModuleType, index: number): void {
const module: IModule = {
id: Guid.newGuid().toString(),
type: moduleType,
data: ''
};
this.state.modules.AddAt(index, module);
this.decryptedModuleData[module.id] = module.data;
this.encryptedModuleData[module.id] = module.data;
// this.state.modules.push(module);
this.setState({
modules: this.state.modules
});
}
private onDeleteModule(index: number): void {
this.state.modules.RemoveAt(index);
this.setState({
modules: this.state.modules
});
}
private onMoveUp(index: number): void {
const prevModule: IModule = this.state.modules[index-1];
this.state.modules[index-1] = this.state.modules[index];
this.state.modules[index] = prevModule;
this.setState({
modules: this.state.modules
});
}
private onMoveDown(index: number): void {
this.state.modules.RemoveAt(index);
this.setState({
modules: this.state.modules
});
}
private onSaveButtonClick(): void {
this.isNewVault = false;
let encryptedMaster = this.currentMasterPW;
if(!this.enteredMasterPW.IsEmpty()) {
encryptedMaster = this.props.passwordVaultService.setMasterPassword(this.enteredMasterPW);
this.currentMasterPW = encryptedMaster;
}
const encryptedModules: IModule[] = [];
this.state.modules.forEach((module: IModule) => {
const encryptedValue: string = this.props.passwordVaultService.encryptModuleData(module.type, this.decryptedModuleData[module.id]);
encryptedModules.push({
id: module.id,
data: encryptedValue,
type: module.type
});
});
this.props.onVaultDataChanged(encryptedMaster, encryptedModules);
this.setState({
modules: encryptedModules
});
this.enteredMasterPW = '';
this.repeatedEnteredMasterPW = '';
}
private onChangePasswordClick(): void {
let encryptedMaster = this.currentMasterPW;
if(!this.enteredMasterPW.IsEmpty()) {
encryptedMaster = this.props.passwordVaultService.setMasterPassword(this.enteredMasterPW);
this.currentMasterPW = encryptedMaster;
this.props.onVaultPasswordChanged(encryptedMaster);
}
this.enteredMasterPW = '';
this.repeatedEnteredMasterPW = '';
this.toggleChangePasswordDialogVisibility();
}
private toggleChangePasswordDialogVisibility(): void {
this.setState({
showChangePasswordDialog: !this.state.showChangePasswordDialog,
isSaveButtonDisabled: !this.state.showChangePasswordDialog
});
}
}

View File

@ -0,0 +1,97 @@
import * as React from 'react';
import { Callout, Icon, DirectionalHint, TextField, ITextField } from 'office-ui-fabric-react';
import * as strings from 'PasswordVaultWebPartStrings';
import { getDeepOrDefault, issetDeep, isset } from '@spfxappdev/utility';
export interface IUserFieldProps {
isDisplayMode: boolean;
defaultValue: string;
onChange?(newValue: string): void;
tabIndex?: number;
}
interface IUserFieldState {
isCopyUsernameToClipboardCalloutHidden: boolean;
}
export default class UserField extends React.Component<IUserFieldProps, IUserFieldState> {
private usernameTextFieldDomElement: HTMLInputElement = null;
public state: IUserFieldState = {
isCopyUsernameToClipboardCalloutHidden: false
};
public render(): React.ReactElement<IUserFieldProps> {
if(this.props.isDisplayMode) {
return this.renderDisplayMode();
}
return this.renderEditMode();
}
public renderDisplayMode(): JSX.Element {
const showCopyToClipboard: boolean = issetDeep(window, "navigator.clipboard.writeText");
return (<>
<TextField
label={strings.UsernameLabel}
disabled={true}
defaultValue={this.props.defaultValue}
componentRef={(input: ITextField) => {
this.usernameTextFieldDomElement = getDeepOrDefault(input, "_textElement.current", null);
}}
onRenderSuffix={() => {
if(!showCopyToClipboard) {
return <></>;
}
return (<Icon iconName={"Copy"} className="copy-icon" onClick={() => { this.copyToClipboard(this.props.defaultValue); }} />);
}}
/>
{showCopyToClipboard && isset(this.usernameTextFieldDomElement) &&
<Callout
hidden={this.state.isCopyUsernameToClipboardCalloutHidden}
target={this.usernameTextFieldDomElement.parentElement}
isBeakVisible={false}
className={"clipboard-callout"}
directionalHint={DirectionalHint.rightCenter}
>
{strings.UsernameCopiedLabel}
</Callout>
}
</>)
}
public renderEditMode(): JSX.Element {
return (<><TextField
label={strings.UsernameLabel}
type="text"
tabIndex={this.props.tabIndex}
onChange={(ev: any, newValue: string) => {
this.props.onChange(newValue);
}}
defaultValue={this.props.defaultValue}
/></>);
}
private copyToClipboard(text: string): void {
window.navigator.clipboard.writeText(text).then(() => {
this.setState({
isCopyUsernameToClipboardCalloutHidden: false
});
window.setTimeout(() => {
this.setState({
isCopyUsernameToClipboardCalloutHidden: true
});
}, 2000);
});
}
}

View File

@ -0,0 +1,30 @@
define([], function() {
return {
"WebPartPropertyGroupAbout": "Über das Webpart",
"NoMasterPasswordSetLabel": "Es wurde noch kein Master Passwort hinterlegt. Bitte hinterlegen Sie ein Masterpasswort.",
"PasswordLabel": "Passwort",
"MasterPasswordLabel": "Master Passwort",
"SetMasterPasswordLabel": "Master Passwort",
"RepeatMasterPasswordLabel": "Master Passwort wiederholen",
"ChangeMasterPasswordLabel": "Master Passwort ändern",
"UsernameLabel": "Benutezrname",
"NoteLabel": "Notiz",
"CloseVaultLabel": "Tresor schließen",
"SaveLabel": "Speichern",
"WrongPasswordLabel": "Falsches Passwort",
"OpenVaultLabel": "Tresor entsperren",
"UsernameCopiedLabel": "Benutzername kopiert",
"PasswordCopiedLabel": "Passwort kopiert",
"DontLoseMasterpasswordLabel": "Wenn Sie das Master passwort vergessen, können Sie den Tresor nicht mehr entsperren und alle Daten gehen verloren. Es ist nicht möglich das Passwort wiederherzustellen.",
"AddNewModuleLabel": "Ein neues Modul hinzufügen",
"DeleteModuleLabel": "Modul löschen",
"MoveUpLabel": "Nach oben verschieben",
"MoveDownLabel": "Nach unten verschieben",
"PasswordModuleLabel": "Passwort",
"UsernameModuleLabel": "Benutzername",
"NoteModuleLabel": "Notiz",
"ChangeMasterPasswordButtonText": "Master Passwort ändern",
"ChangeMasterPasswordDialogTitle": "Master Passwort ändern",
"CancelLabel": "Abbrechen"
}
});

View File

@ -0,0 +1,30 @@
define([], function() {
return {
"WebPartPropertyGroupAbout": "About",
"NoMasterPasswordSetLabel": "No master password has been stored yet. Please store a master password.",
"PasswordLabel": "Password",
"MasterPasswordLabel": "Master Password",
"SetMasterPasswordLabel": "Master Password",
"RepeatMasterPasswordLabel": "Repeat Master Password",
"ChangeMasterPasswordLabel": "Change Master Password",
"UsernameLabel": "Username",
"NoteLabel": "Note",
"CloseVaultLabel": "Close vault",
"SaveLabel": "Save",
"WrongPasswordLabel": "Wrong Password",
"OpenVaultLabel": "Open vault",
"UsernameCopiedLabel": "Username copied",
"PasswordCopiedLabel": "Password copied",
"DontLoseMasterpasswordLabel": "If you forget the master password, you will not be able to unlock the vault and all data will be lost. It is not possible to recover the password.",
"AddNewModuleLabel": "Add a new secured module",
"DeleteModuleLabel": "Delete",
"MoveUpLabel": "Move up",
"MoveDownLabel": "Move down",
"PasswordModuleLabel": "Password",
"UsernameModuleLabel": "Username",
"NoteModuleLabel": "Note",
"ChangeMasterPasswordButtonText": "Change Master Password",
"ChangeMasterPasswordDialogTitle": "Change Master Password",
"CancelLabel": "Cancel"
}
});

View File

@ -0,0 +1,33 @@
declare interface IPasswordVaultWebPartStrings {
WebPartPropertyGroupAbout: string;
NoMasterPasswordSetLabel: string;
PasswordLabel: string;
MasterPasswordLabel: string;
SetMasterPasswordLabel: string;
RepeatMasterPasswordLabel: string;
ChangeMasterPasswordLabel: string;
UsernameLabel: string;
NoteLabel: string;
CloseVaultLabel: string;
SaveLabel: string;
WrongPasswordLabel: string;
OpenVaultLabel: string;
UsernameCopiedLabel: string;
PasswordCopiedLabel: string;
DontLoseMasterpasswordLabel: string;
AddNewModuleLabel: string;
DeleteModuleLabel: string;
MoveUpLabel: string;
MoveDownLabel: string;
PasswordModuleLabel: string;
UsernameModuleLabel: string;
NoteModuleLabel: string;
ChangeMasterPasswordButtonText: string;
ChangeMasterPasswordDialogTitle: string;
CancelLabel: string;
}
declare module 'PasswordVaultWebPartStrings' {
const strings: IPasswordVaultWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 B

View File

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

View File

@ -1,7 +1,7 @@
// For more information on how to run this SPFx project in a VS Code Remote Container, please visit https://aka.ms/spfx-devcontainer
{
"name": "SPFx 1.16.1",
"image": "docker.io/m365pnp/spfx:1.16.1",
"name": "SPFx 1.18.1",
"image": "docker.io/m365pnp/spfx:1.18.1",
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.