diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 6007bdbd61fb..2924e893692b 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -222,6 +222,7 @@ specifiers: '@rush-temp/communication-job-router': file:./projects/communication-job-router.tgz '@rush-temp/communication-network-traversal': file:./projects/communication-network-traversal.tgz '@rush-temp/communication-phone-numbers': file:./projects/communication-phone-numbers.tgz + '@rush-temp/communication-recipient-verification': file:./projects/communication-recipient-verification.tgz '@rush-temp/communication-rooms': file:./projects/communication-rooms.tgz '@rush-temp/communication-short-codes': file:./projects/communication-short-codes.tgz '@rush-temp/communication-sms': file:./projects/communication-sms.tgz @@ -555,6 +556,7 @@ dependencies: '@rush-temp/communication-job-router': file:projects/communication-job-router.tgz '@rush-temp/communication-network-traversal': file:projects/communication-network-traversal.tgz '@rush-temp/communication-phone-numbers': file:projects/communication-phone-numbers.tgz + '@rush-temp/communication-recipient-verification': file:projects/communication-recipient-verification.tgz '@rush-temp/communication-rooms': file:projects/communication-rooms.tgz '@rush-temp/communication-short-codes': file:projects/communication-short-codes.tgz '@rush-temp/communication-sms': file:projects/communication-sms.tgz @@ -4030,7 +4032,7 @@ packages: dependencies: semver: 7.3.8 shelljs: 0.8.5 - typescript: 5.1.0-dev.20230308 + typescript: 5.1.0-dev.20230309 dev: false /ecdsa-sig-formatter/1.0.11: @@ -8961,8 +8963,8 @@ packages: hasBin: true dev: false - /typescript/5.1.0-dev.20230308: - resolution: {integrity: sha512-CSITPpBYNdPYujl36d9VhNNCLE+isuwm/ArFbYgPsWsLniLCcfBl+NcaOkVqyjV0XEjP+uN1yywiglCkEzed1w==} + /typescript/5.1.0-dev.20230309: + resolution: {integrity: sha512-pCqgzbHDsuACtq0v+pjNY6Zf7cdWZstY38Jq7FfD1HqAeEGnFKhrZgSRh7kS/QE5UOctGAqbp1ynTGdVI7s4Mw==} engines: {node: '>=4.2.0'} hasBin: true dev: false @@ -16078,6 +16080,49 @@ packages: - utf-8-validate dev: false + file:projects/communication-recipient-verification.tgz: + resolution: {integrity: sha512-a9j1M/U77hTkZB3o2jL78moPmHfbf/P2GyRzm0tWXuSOCqL5qC5BfFnYVYrLYf1eyn2KM7TkGKOwtWweMZzHnw==, tarball: file:projects/communication-recipient-verification.tgz} + name: '@rush-temp/communication-recipient-verification' + version: 0.0.0 + dependencies: + '@azure/identity': 2.1.0 + '@microsoft/api-extractor': 7.34.4_@types+node@14.18.37 + '@types/chai': 4.3.4 + '@types/mocha': 7.0.2 + '@types/node': 14.18.37 + '@types/sinon': 9.0.11 + '@types/uuid': 8.3.4 + chai: 4.3.7 + cross-env: 7.0.3 + dotenv: 16.0.3 + eslint: 8.35.0 + events: 3.3.0 + inherits: 2.0.4 + karma: 6.4.1 + karma-chrome-launcher: 3.1.1 + karma-coverage: 2.2.0 + karma-env-preprocessor: 0.1.1 + karma-firefox-launcher: 1.3.0 + karma-junit-reporter: 2.0.1_karma@6.4.1 + karma-mocha: 2.0.1 + karma-mocha-reporter: 2.2.5_karma@6.4.1 + karma-sourcemap-loader: 0.3.8 + mocha: 7.2.0 + mocha-junit-reporter: 2.2.0_mocha@7.2.0 + nyc: 15.1.0 + prettier: 2.8.4 + rimraf: 3.0.2 + sinon: 9.2.4 + tslib: 2.5.0 + typescript: 4.8.4 + uuid: 8.3.2 + transitivePeerDependencies: + - bufferutil + - debug + - supports-color + - utf-8-validate + dev: false + file:projects/communication-rooms.tgz: resolution: {integrity: sha512-uNbfpRCHzUkqoPHpJbkf8yFZyyll6Zzbj6b6yFM+hGDbth1gi4ILcHlztl/lZ+Oif/f0Vd3CfHFqS9cWLrRuzA==, tarball: file:projects/communication-rooms.tgz} name: '@rush-temp/communication-rooms' diff --git a/rush.json b/rush.json index 8c5464069bfb..977c7c5e9937 100644 --- a/rush.json +++ b/rush.json @@ -430,6 +430,11 @@ "projectFolder": "sdk/communication/communication-short-codes", "versionPolicyName": "client" }, + { + "packageName": "@azure-tools/communication-recipient-verification", + "projectFolder": "sdk/communication/communication-recipient-verification", + "versionPolicyName": "client" + }, { "packageName": "@azure-tools/communication-alpha-ids", "projectFolder": "sdk/communication/communication-alpha-ids", @@ -1944,4 +1949,4 @@ "versionPolicyName": "client" } ] -} \ No newline at end of file +} diff --git a/sdk/communication/ci.yml b/sdk/communication/ci.yml index 3e362fc912de..baedd17aea1f 100644 --- a/sdk/communication/ci.yml +++ b/sdk/communication/ci.yml @@ -55,3 +55,7 @@ extends: safeName: azurecommunicationjobrouter - name: azure-tools-communication-toll-free-verification safeName: azuretoolscommunicationtollfreeverification + - name: azure-tools-communication-recipient-verification + safeName: azuretoolscommunicationrecipientverification + skipPublishDocMs: true + skipPublishDocGithubIo: true diff --git a/sdk/communication/communication-recipient-verification/.nycrc b/sdk/communication/communication-recipient-verification/.nycrc new file mode 100644 index 000000000000..29174b423579 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/.nycrc @@ -0,0 +1,10 @@ +{ + "include": ["dist-esm/src/**/*.js"], + "exclude": ["**/*.d.ts", "dist-esm/src/generated/*"], + "reporter": ["text-summary", "html", "cobertura"], + "exclude-after-remap": false, + "sourceMap": true, + "produce-source-map": true, + "instrument": true, + "all": true +} diff --git a/sdk/communication/communication-recipient-verification/CHANGELOG.md b/sdk/communication/communication-recipient-verification/CHANGELOG.md new file mode 100644 index 000000000000..fe5886f62d7e --- /dev/null +++ b/sdk/communication/communication-recipient-verification/CHANGELOG.md @@ -0,0 +1,10 @@ +# Release History + +## 1.0.0-beta.1 (2023-03-08) + +The first preview of the Azure Communication Recipient Verification client library has the following features: + +- Verifying code for a phone number +- Request a verification code to a phone number(US) +- Removing a verified/pending phone number +- Returning the constant values for a resource in relation to recipient verification diff --git a/sdk/communication/communication-recipient-verification/README.md b/sdk/communication/communication-recipient-verification/README.md new file mode 100644 index 000000000000..c8c377937caf --- /dev/null +++ b/sdk/communication/communication-recipient-verification/README.md @@ -0,0 +1,194 @@ +# Azure Communication Recipient Verification client library for JavaScript + +The Recipient Verification library allows users to verify the phone number of recipients before sending messages or making calls to the phone number. + +## Getting started + +### Prerequisites + +- An [Azure subscription][azure_sub]. +- An existing Communication Services resource. If you need to create the resource, you can use the [Azure Portal][azure_portal], the [Azure PowerShell][azure_powershell], or the [Azure CLI][azure_cli]. + +### Installing + +```bash +npm install @azure-tools/communication-recipient-verification +``` + +### Browser support + +#### JavaScript Bundle + +To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our [bundling documentation](https://aka.ms/AzureSDKBundling). + +## Key concepts + +## Examples + +## Authentication + +To create a client object to access the Communication Services API, you will need a `connection string` or the `endpoint` of your Communication Services resource and a `credential`. The Recipient Verification client can use either Azure Active Directory credentials or an API key credential to authenticate. + +You can get a key and/or connection string from your Communication Services resource in the [Azure Portal][azure_portal]. You can also find the endpoint for your Communication Services resource in the [Azure Portal][azure_portal]. + +Once you have a key, you can authenticate the `RecipientVerificationClient` with any of the following methods: + +### Using a connection string + +```javascript +const { + RecipientVerificationClient, +} = require("@azure-tools/communication-recipient-verification"); +const connectionString = "endpoint=;accessKey="; +const client = new RecipientVerificationClient(connectionString); +``` + +### Using an access key with `AzureKeyCredential` + +If you use a key to initialize the client you will also need to provide the appropriate endpoint. You can get this endpoint from your Communication Services resource in [Azure Portal][azure_portal]. Once you have a key and endpoint, you can authenticate with the following code: + +```javascript +const { AzureKeyCredential } = require("@azure/core-auth"); +const { + RecipientVerificationClient, +} = require("@azure-tools/communication-recipient-verification"); +const credential = new AzureKeyCredential(""); +const client = new RecipientVerificationClient("", credential); +``` + +### Using an Azure Active Directory Credential + +Connection string authentication is used in most of the examples, but you can also authenticate with Azure Active Directory using the [Azure Identity library][azure_identity]. To use the [DefaultAzureCredential][defaultazurecredential] provider shown below, or other credential providers provided with the Azure SDK, please install the [`@azure/identity`][azure_identity] package: + +```bash +npm install @azure/identity +``` + +The [`@azure/identity`][azure_identity] package provides a variety of credential types that your application can use to do this. The [README for `@azure/identity`][azure_identity_readme] provides more details and samples to get you started. + +```javascript +const { DefaultAzureCredential } = require("@azure/identity"); +const { + RecipientVerificationClient, +} = require("@azure-tools/communication-recipient-verification"); + +let credential = new DefaultAzureCredential(); +const client = new RecipientVerificationClient("", credential); +``` + +## Usage + +The following sections provide code snippets that cover some of the common tasks using the Azure Communication Services Recipient Verification Client. The scenarios that are covered here consist of: + +- [Request phone number verification code](#request-phone-number-verification-code) +- [Verify phone number](#verify-phone-number) +- [Remove a verified number](#remove-verified-number) +- [Get verified numbers](#get-verified-numbers) + +### Request phone number verification code + +```typescript +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; +const connectionString = "endpoint=;accessKey="; +const client = new RecipientVerificationClient(connectionString); + +async main function() { + // body of the request + const VerificationRequest = { + identity: "+11234567890", + channel: "sms", + }; + + // get the verification status + var status = await client.requestVerification(VerificationRequest); + console.log(status); +} + +main(); +``` + +### Verify phone number + +```typescript +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; +const connectionString = "endpoint=;accessKey="; +const client = new RecipientVerificationClient(connectionString); + +async main function() { + // id that is used to reference users phone number + const verificationId = "7e5dd7e1-5203-41ab-960e-65c1eb804fc6"; + + // body of the request + const VerificationRequest = { + verificationCode: "1234567", + }; + + // verifying your phone number + const status = await client.verifyIdentity(verificationId, VerificationRequest); + console.log(status); +} + +main(); +``` + +### Remove verified number + +```typescript +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; +const connectionString = "endpoint=;accessKey="; +const client = new RecipientVerificationClient(connectionString); + +async main function() { + // id that is used to reference users phone number + const verificationId = "4d313ff0-3aeb-477e-8c15-7c9a893e8999"; + + // delete verification for a resource + await client.deleteVerification(verificationId); +} + +main(); +``` + +### Get verified numbers + +```typescript +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; +const connectionString = "endpoint=;accessKey="; +const client = new RecipientVerificationClient(connectionString); + +async main function() { + // get all verifications for a resource + var verifications = await client.getVerifications(); + + // print all verifications + for await (const verification of verifications) { + console.log(verification); + } +} + +main(); +``` + +## Troubleshooting + +## Next steps + +Please take a look at the samples directory for detailed examples on how to use this library. + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +## Related projects + +- [Microsoft Azure SDK for Javascript](https://github.com/Azure/azure-sdk-for-js) + +[azure_cli]: https://docs.microsoft.com/cli/azure +[azure_sub]: https://azure.microsoft.com/free/ +[azure_portal]: https://portal.azure.com +[azure_powershell]: https://docs.microsoft.com/powershell/module/az.communication/new-azcommunicationservice +[defaultazurecredential]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential +[azure_identity]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity +[azure_identity_readme]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/README.md + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcommunication%2Fcommunication-toll-free-verification%2FREADME.png) diff --git a/sdk/communication/communication-recipient-verification/api-extractor.json b/sdk/communication/communication-recipient-verification/api-extractor.json new file mode 100644 index 000000000000..adda95354d78 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/api-extractor.json @@ -0,0 +1,35 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "mainEntryPointFilePath": "types/src/index.d.ts", + "docModel": { + "enabled": true + }, + "apiReport": { + "enabled": true, + "reportFolder": "./review" + }, + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "", + "publicTrimmedFilePath": "./types/communication-recipient-verification.d.ts" + }, + "messages": { + "tsdocMessageReporting": { + "default": { + "logLevel": "none" + } + }, + "extractorMessageReporting": { + "ae-forgotten-export": { + "logLevel": "error", + "addToApiReportFile": false + }, + "ae-missing-release-tag": { + "logLevel": "none" + }, + "ae-unresolved-link": { + "logLevel": "error" + } + } + } +} diff --git a/sdk/communication/communication-recipient-verification/karma.conf.js b/sdk/communication/communication-recipient-verification/karma.conf.js new file mode 100644 index 000000000000..b7223a7f2b76 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/karma.conf.js @@ -0,0 +1,129 @@ +// https://github.com/karma-runner/karma-chrome-launcher +process.env.CHROME_BIN = require("puppeteer").executablePath(); +require("dotenv").config(); +const { relativeRecordingsPath } = require("@azure-tools/test-recorder"); + +process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath(); +module.exports = function (config) { + config.set({ + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: "./", + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ["mocha"], + + plugins: [ + "karma-mocha", + "karma-mocha-reporter", + "karma-chrome-launcher", + "karma-firefox-launcher", + "karma-env-preprocessor", + "karma-coverage", + "karma-sourcemap-loader", + "karma-junit-reporter", + ], + + // list of files / patterns to load in the browser + files: ["dist-test/index.browser.js"], + + // list of files / patterns to exclude + exclude: [], + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + "**/*.js": ["sourcemap", "env"], + // IMPORTANT: COMMENT following line if you want to debug in your browsers!! + // Preprocess source file to calculate code coverage, however this will make source file unreadable + //"dist-test/index.browser.js": ["coverage"] + }, + + // inject following environment values into browser testing with window.__env__ + // environment values MUST be exported or set with same console running "karma start" + // https://www.npmjs.com/package/karma-env-preprocessor + envPreprocessor: [ + "TEST_MODE", + "COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING", + "INCLUDE_PHONENUMBER_LIVE_TESTS", + "AZURE_PHONE_NUMBER", + "COMMUNICATION_ENDPOINT", + "AZURE_CLIENT_ID", + "AZURE_CLIENT_SECRET", + "AZURE_TENANT_ID", + "COMMUNICATION_SKIP_INT_PHONENUMBERS_TESTS", + "RECORDINGS_RELATIVE_PATH", + ], + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ["mocha", "coverage", "junit"], + + coverageReporter: { + // specify a common output directory + dir: "coverage-browser/", + reporters: [ + { type: "json", subdir: ".", file: "coverage.json" }, + { type: "lcovonly", subdir: ".", file: "lcov.info" }, + { type: "html", subdir: "html" }, + { type: "cobertura", subdir: ".", file: "cobertura-coverage.xml" }, + ], + }, + + junitReporter: { + outputDir: "", // results will be saved as $outputDir/$browserName.xml + outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile + suite: "", // suite will become the package name attribute in xml testsuite element + useBrowserName: false, // add browser name to report and classes names + nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element + classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element + properties: {}, // key value pair of properties to add to the section of the report + }, + + // web server port + port: 9876, + + // enable / disable colors in the output (reporters and logs) + colors: true, + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + // 'ChromeHeadless', 'Chrome', 'Firefox', 'Edge', 'IE' + browsers: ["HeadlessChrome"], + + customLaunchers: { + HeadlessChrome: { + base: "ChromeHeadless", + flags: ["--no-sandbox", "--disable-web-security"], + }, + }, + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: true, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: 1, + + browserNoActivityTimeout: 600000, + browserDisconnectTimeout: 10000, + browserDisconnectTolerance: 3, + + client: { + mocha: { + // change Karma's debug.html to the mocha web reporter + reporter: "html", + timeout: "600000", + }, + }, + }); +}; diff --git a/sdk/communication/communication-recipient-verification/package.json b/sdk/communication/communication-recipient-verification/package.json new file mode 100644 index 000000000000..47853230c0a2 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/package.json @@ -0,0 +1,139 @@ +{ + "name": "@azure-tools/communication-recipient-verification", + "version": "1.0.0-beta.1", + "description": "Test", + "sdk-type": "client", + "main": "dist/index.js", + "module": "dist-esm/src/index.js", + "types": "types/communication-recipient-verification.d.ts", + "scripts": { + "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", + "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local", + "build:autorest": "autorest --typescript ./swagger/README.md && rushx format", + "build:clean": "rush update --recheck && rush rebuild && npm run build", + "build:browser": "tsc -p . && dev-tool run bundle", + "build:node": "tsc -p . && dev-tool run bundle", + "build:samples": "dev-tool samples publish --force", + "build:test": "tsc -p . && dev-tool run bundle", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"", + "clean": "rimraf dist dist-* types *.tgz *.log", + "execute:samples": "dev-tool samples run samples-dev", + "extract-api": "tsc -p . && api-extractor run --local", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"", + "integration-test:browser": "dev-tool run test:browser", + "integration-test:node": "dev-tool run test:node-js-input -- --timeout 300000 'dist-esm/test/public/*.spec.js'", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "lint:fix": "eslint package.json api-extractor.json README.md src test --ext .ts,.javascript,.js --fix --fix-type [problem,suggestion]", + "lint": "eslint package.json api-extractor.json README.md src test --ext .ts,.javascript,.js", + "pack": "npm pack 2>&1", + "test": "rimraf dist-test && npm run build:test && npm run unit-test && npm run integration-test", + "test:browser": "npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "test:node": "npm run build:test && npm run unit-test:node && npm run integration-test:node", + "test:watch": "npm run test -- --watch --reporter min", + "unit-test:browser": "dev-tool run test:browser", + "unit-test:node": "dev-tool run test:node-ts-input -- --exclude 'test/**/browser/*.spec.ts' 'test/**/*.spec.ts'", + "unit-test": "npm run unit-test:node && npm run unit-test:browser" + }, + "files": [ + "dist/", + "dist-esm/src/", + "types/communication-recipient-verification.d.ts", + "README.md", + "LICENSE" + ], + "keywords": [ + "azure", + "cloud", + "communication" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-recipient-verification/", + "repository": "github:Azure/azure-sdk-for-js", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "sideEffects": false, + "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "@azure/communication-common": "^2.2.0", + "@azure/core-auth": "^1.3.0", + "@azure/core-client": "^1.3.2", + "@azure/core-lro": "^2.2.0", + "@azure/core-paging": "^1.1.1", + "@azure/core-rest-pipeline": "^1.3.2", + "@azure/core-tracing": "^1.0.0", + "@azure/logger": "^1.0.0", + "events": "^3.0.0", + "tslib": "^2.2.0", + "uuid": "^8.3.2" + }, + "devDependencies": { + "@azure-tools/test-recorder": "^3.0.0", + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0", + "@azure/identity": "^2.0.1", + "@azure/test-utils": "^1.0.0", + "@microsoft/api-extractor": "^7.31.1", + "@types/chai": "^4.1.6", + "@types/mocha": "^7.0.2", + "@types/node": "^14.0.0", + "@types/sinon": "^9.0.4", + "@types/uuid": "^8.3.2", + "chai": "^4.2.0", + "cross-env": "^7.0.2", + "dotenv": "^16.0.0", + "eslint": "^8.0.0", + "inherits": "^2.0.3", + "karma": "^6.2.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-env-preprocessor": "^0.1.1", + "karma-firefox-launcher": "^1.1.0", + "karma-junit-reporter": "^2.0.1", + "karma-mocha": "^2.0.1", + "karma-mocha-reporter": "^2.2.5", + "karma-sourcemap-loader": "^0.3.8", + "mocha": "^7.1.1", + "mocha-junit-reporter": "^2.0.0", + "nyc": "^15.0.0", + "prettier": "^2.5.1", + "rimraf": "^3.0.0", + "sinon": "^9.0.2", + "typescript": "~4.8.0" + }, + "//metadata": { + "constantPaths": [ + { + "path": "src/generated/src/RecipientVerificationClient.ts", + "prefix": "packageDetails" + }, + { + "path": "src/generated/src/tracing.ts", + "prefix": "packageVersion" + }, + { + "path": "src/utils/constants.ts", + "prefix": "SDK_VERSION" + }, + { + "path": "swagger/README.md", + "prefix": "package-version" + } + ] + }, + "//sampleConfiguration": { + "productName": "Azure Communication Services - Recipient Verification", + "productSlugs": [ + "azure", + "azure-communication-services" + ], + "requiredResources": { + "Azure Communication Services account": "https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource" + } + } +} diff --git a/sdk/communication/communication-recipient-verification/recordings/browsers/recipientverificationclient__get_verification_constants/recording_get_verification_constants.json b/sdk/communication/communication-recipient-verification/recordings/browsers/recipientverificationclient__get_verification_constants/recording_get_verification_constants.json new file mode 100644 index 000000000000..53ceb8b28229 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/recordings/browsers/recipientverificationclient__get_verification_constants/recording_get_verification_constants.json @@ -0,0 +1,47 @@ +{ + "Entries": [ + { + "RequestUri": "https://endpoint/verifications/configuration?api-version=2022-11-15", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate, br", + "Accept-Language": "en-US", + "Authorization": "Sanitized", + "Connection": "keep-alive", + "Referer": "http://localhost:9876/", + "sec-ch-ua": "", + "sec-ch-ua-mobile": "?0", + "sec-ch-ua-platform": "", + "Sec-Fetch-Dest": "empty", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": "same-site", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/111.0.5555.0 Safari/537.36", + "x-ms-client-request-id": "9d787bd6-07fc-4c7b-8e57-17f1fee41298", + "x-ms-content-sha256": "47DEQpj8HBSa\u002B/TImW\u002B5JCeuQeRkm5NMpJWZG3hSuFU=", + "x-ms-date": "Fri, 10 Mar 2023 01:30:35 GMT", + "x-ms-useragent": "azsdk-js-communication-recipient-verification/1.0.0-beta.1 core-rest-pipeline/1.10.3 OS" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Accept-Ranges": "bytes", + "Connection": "keep-alive", + "Content-Length": "84", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 10 Mar 2023 01:30:32 GMT", + "MS-CV": "wXkedrH9vkC42Xk/\u002BBOpWA.0", + "Strict-Transport-Security": "max-age=2592000", + "x-azure-ref": "20230310T013031Z-fa3ruqzpcp06b9urqf99mwm7u0000000013000000002mx0f", + "X-Cache": "CONFIG_NOCACHE", + "X-Processing-Time": "109ms" + }, + "ResponseBody": { + "maxRetriesAllowed": 5, + "maxVerificationsAllowed": 3, + "currentNumberOfVerifications": 0 + } + } + ], + "Variables": {} +} diff --git a/sdk/communication/communication-recipient-verification/recordings/browsers/recipientverificationclient__list_all_verifications/recording_get_list_of_all_verifications.json b/sdk/communication/communication-recipient-verification/recordings/browsers/recipientverificationclient__list_all_verifications/recording_get_list_of_all_verifications.json new file mode 100644 index 000000000000..a6dee2fb3f5a --- /dev/null +++ b/sdk/communication/communication-recipient-verification/recordings/browsers/recipientverificationclient__list_all_verifications/recording_get_list_of_all_verifications.json @@ -0,0 +1,43 @@ +{ + "Entries": [ + { + "RequestUri": "https://endpoint/verifications?api-version=2022-11-15", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate, br", + "Accept-Language": "en-US", + "Authorization": "Sanitized", + "Connection": "keep-alive", + "Referer": "http://localhost:9876/", + "sec-ch-ua": "", + "sec-ch-ua-mobile": "?0", + "sec-ch-ua-platform": "", + "Sec-Fetch-Dest": "empty", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": "same-site", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/111.0.5555.0 Safari/537.36", + "x-ms-client-request-id": "9d787bd6-07fc-4c7b-8e57-17f1fee41298", + "x-ms-content-sha256": "47DEQpj8HBSa\u002B/TImW\u002B5JCeuQeRkm5NMpJWZG3hSuFU=", + "x-ms-date": "Fri, 10 Mar 2023 01:30:35 GMT", + "x-ms-useragent": "azsdk-js-communication-recipient-verification/1.0.0-beta.1 core-rest-pipeline/1.10.3 OS" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Accept-Ranges": "bytes", + "Connection": "keep-alive", + "Content-Length": "2", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 10 Mar 2023 01:30:31 GMT", + "MS-CV": "FhFgEDnKV0qqkaQYIrPu7g.0", + "Strict-Transport-Security": "max-age=2592000", + "x-azure-ref": "20230310T013031Z-fa3ruqzpcp06b9urqf99mwm7u0000000013000000002mwx8", + "X-Cache": "CONFIG_NOCACHE", + "X-Processing-Time": "256ms" + }, + "ResponseBody": "[]" + } + ], + "Variables": {} +} diff --git a/sdk/communication/communication-recipient-verification/recordings/node/recipientverificationclient__get_verification_constants/recording_get_verification_constants.json b/sdk/communication/communication-recipient-verification/recordings/node/recipientverificationclient__get_verification_constants/recording_get_verification_constants.json new file mode 100644 index 000000000000..6fc9b4211c76 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/recordings/node/recipientverificationclient__get_verification_constants/recording_get_verification_constants.json @@ -0,0 +1,38 @@ +{ + "Entries": [ + { + "RequestUri": "https://endpoint/verifications/configuration?api-version=2022-11-15", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip,deflate", + "Authorization": "Sanitized", + "Connection": "keep-alive", + "User-Agent": "azsdk-js-communication-recipient-verification/1.0.0-beta.1 core-rest-pipeline/1.10.3 Node/v18.12.1 OS/(x64-Linux-5.15.90.1-microsoft-standard-WSL2)", + "x-ms-client-request-id": "9d787bd6-07fc-4c7b-8e57-17f1fee41298", + "x-ms-content-sha256": "47DEQpj8HBSa\u002B/TImW\u002B5JCeuQeRkm5NMpJWZG3hSuFU=", + "x-ms-date": "Fri, 10 Mar 2023 01:30:25 GMT" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Accept-Ranges": "bytes", + "Connection": "keep-alive", + "Content-Length": "84", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 10 Mar 2023 01:30:22 GMT", + "MS-CV": "ONnocPTEdE\u002BDzaIrENU04Q.0", + "Strict-Transport-Security": "max-age=2592000", + "x-azure-ref": "20230310T013022Z-zknv4tf89d2xr0au6shszqc6a000000001f000000002k9y8", + "X-Cache": "CONFIG_NOCACHE", + "X-Processing-Time": "113ms" + }, + "ResponseBody": { + "maxRetriesAllowed": 5, + "maxVerificationsAllowed": 3, + "currentNumberOfVerifications": 0 + } + } + ], + "Variables": {} +} diff --git a/sdk/communication/communication-recipient-verification/recordings/node/recipientverificationclient__list_all_verifications/recording_get_list_of_all_verifications.json b/sdk/communication/communication-recipient-verification/recordings/node/recipientverificationclient__list_all_verifications/recording_get_list_of_all_verifications.json new file mode 100644 index 000000000000..9e5b29760ccf --- /dev/null +++ b/sdk/communication/communication-recipient-verification/recordings/node/recipientverificationclient__list_all_verifications/recording_get_list_of_all_verifications.json @@ -0,0 +1,34 @@ +{ + "Entries": [ + { + "RequestUri": "https://endpoint/verifications?api-version=2022-11-15", + "RequestMethod": "GET", + "RequestHeaders": { + "Accept": "application/json", + "Accept-Encoding": "gzip,deflate", + "Authorization": "Sanitized", + "Connection": "keep-alive", + "User-Agent": "azsdk-js-communication-recipient-verification/1.0.0-beta.1 core-rest-pipeline/1.10.3 Node/v18.12.1 OS/(x64-Linux-5.15.90.1-microsoft-standard-WSL2)", + "x-ms-client-request-id": "9d787bd6-07fc-4c7b-8e57-17f1fee41298", + "x-ms-content-sha256": "47DEQpj8HBSa\u002B/TImW\u002B5JCeuQeRkm5NMpJWZG3hSuFU=", + "x-ms-date": "Fri, 10 Mar 2023 01:30:26 GMT" + }, + "RequestBody": null, + "StatusCode": 200, + "ResponseHeaders": { + "Accept-Ranges": "bytes", + "Connection": "keep-alive", + "Content-Length": "2", + "Content-Type": "application/json; charset=utf-8", + "Date": "Fri, 10 Mar 2023 01:30:22 GMT", + "MS-CV": "04JT3\u002BLzqUSm6Ll396UR7Q.0", + "Strict-Transport-Security": "max-age=2592000", + "x-azure-ref": "20230310T013022Z-zknv4tf89d2xr0au6shszqc6a000000001f000000002ka2h", + "X-Cache": "CONFIG_NOCACHE", + "X-Processing-Time": "105ms" + }, + "ResponseBody": "[]" + } + ], + "Variables": {} +} diff --git a/sdk/communication/communication-recipient-verification/review/communication-recipient-verification.api.md b/sdk/communication/communication-recipient-verification/review/communication-recipient-verification.api.md new file mode 100644 index 000000000000..122932d4d5b8 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/review/communication-recipient-verification.api.md @@ -0,0 +1,107 @@ +## API Report File for "@azure-tools/communication-recipient-verification" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +/// + +import { CommonClientOptions } from '@azure/core-client'; +import * as coreClient from '@azure/core-client'; +import { KeyCredential } from '@azure/core-auth'; +import { TokenCredential } from '@azure/core-auth'; + +// @public +export interface AcsVerification { + attempts?: number; + challengeId?: string; + identity?: string; + immutableId?: string; + retries?: number; + status?: string; + subscriptionId?: string; + verificationId?: string; +} + +// @public +export interface AcsVerificationDeleteVerificationOptionalParams extends coreClient.OperationOptions { +} + +// @public +export interface AcsVerificationGetVerificationConstantsOptionalParams extends coreClient.OperationOptions { +} + +// @public +export type AcsVerificationGetVerificationConstantsResponse = VerificationConstantsResponse; + +// @public +export interface AcsVerificationGetVerificationsOptionalParams extends coreClient.OperationOptions { +} + +// @public +export type AcsVerificationGetVerificationsResponse = AcsVerification[]; + +// @public (undocumented) +export const AcsVerificationMapper: coreClient.CompositeMapper; + +// @public +export interface AcsVerificationRequestVerificationOptionalParams extends coreClient.OperationOptions { + channel?: string; + identity?: string; +} + +// @public +export type AcsVerificationRequestVerificationResponse = VerificationResponse; + +// @public +export interface AcsVerificationVerifyIdentityOptionalParams extends coreClient.OperationOptions { + verificationCode?: string; +} + +// @public +export type AcsVerificationVerifyIdentityResponse = VerificationResponse; + +// @public (undocumented) +export const ConstantsMapper: coreClient.CompositeMapper; + +// @public +export class RecipientVerificationClient { + constructor(connectionString: string, options?: RecipientVerificationClientOptions); + constructor(endpoint: string, credential: KeyCredential, options?: RecipientVerificationClientOptions); + constructor(endpoint: string, credential: TokenCredential, options?: RecipientVerificationClientOptions); + deleteVerification(verificationId: string, options?: AcsVerificationDeleteVerificationOptionalParams): Promise; + getVerificationConstants(options?: AcsVerificationGetVerificationConstantsOptionalParams): Promise; + getVerifications(options?: AcsVerificationGetVerificationsOptionalParams): Promise; + requestVerification(options?: AcsVerificationRequestVerificationOptionalParams): Promise; + verifyIdentity(verificationId: string, options?: AcsVerificationVerifyIdentityOptionalParams): Promise; +} + +// @public +export interface RecipientVerificationClientOptions extends CommonClientOptions { +} + +// @public (undocumented) +export const VerificationCodeRequestMapper: coreClient.CompositeMapper; + +// @public +export interface VerificationConstantsResponse { + currentNumberOfVerifications?: number; + maxRetriesAllowed?: number; + maxVerificationsAllowed?: number; +} + +// @public (undocumented) +export const VerificationRequestMapper: coreClient.CompositeMapper; + +// @public +export interface VerificationResponse { + isVerified?: boolean; + verificationId?: string; +} + +// @public (undocumented) +export const VerificationResponseMapper: coreClient.CompositeMapper; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/sdk/communication/communication-recipient-verification/sample.env b/sdk/communication/communication-recipient-verification/sample.env new file mode 100644 index 000000000000..ecc5467f2006 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/sample.env @@ -0,0 +1,3 @@ +# Used in most samples. Retrieve these values from a Communication Services instance +# in the Azure Portal. +COMMUNICATION_SAMPLES_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" diff --git a/sdk/communication/communication-recipient-verification/samples-dev/deleteVerification.ts b/sdk/communication/communication-recipient-verification/samples-dev/deleteVerification.ts new file mode 100644 index 000000000000..88a2138b0f93 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples-dev/deleteVerification.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Delete a verification for a resource + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +export async function main() { + console.log("\n== Delete Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // id that is used to reference users phone number + const verificationId = "4d313ff0-3aeb-477e-8c15-7c9a893e8999"; + + // delete verification for a resource + await client.deleteVerification(verificationId); +} + +main().catch((error) => { + console.log("The sample deleteVerification encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples-dev/getAllVerifications.ts b/sdk/communication/communication-recipient-verification/samples-dev/getAllVerifications.ts new file mode 100644 index 000000000000..efc613a46482 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples-dev/getAllVerifications.ts @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Get all verifications for a resource + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +export async function main() { + console.log("\n== Get All Verifications Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // get all verifications for a resource + var verifications = await client.getVerifications(); + + // print all verifications + for await (const verification of verifications) { + console.log(verification); + } +} + +main().catch((error) => { + console.log("The sample getAllVerifications encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples-dev/getVerificationConstants.ts b/sdk/communication/communication-recipient-verification/samples-dev/getVerificationConstants.ts new file mode 100644 index 000000000000..35ddcd9cecb8 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples-dev/getVerificationConstants.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Get verification constants for a resource + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +export async function main() { + console.log("\n== Get Verification Constants Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // get constants for the resource + var constants = await client.getVerificationConstants(); + + // print constant values + console.log(constants); +} + +main().catch((error) => { + console.log("The sample getVerificationConstants encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples-dev/requestVerification.ts b/sdk/communication/communication-recipient-verification/samples-dev/requestVerification.ts new file mode 100644 index 000000000000..3916eb31be81 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples-dev/requestVerification.ts @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Request identity verification + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +export async function main() { + console.log("\n== Request Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // body of the request + const verificationRequest = { + identity: "+11234567890", + channel: "sms", + }; + + // get the verification status + var status = await client.requestVerification(verificationRequest); + + // print the status of the phone number + console.log(status); +} + +main().catch((error) => { + console.log("The sample requestVerification encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples-dev/verifyVerification.ts b/sdk/communication/communication-recipient-verification/samples-dev/verifyVerification.ts new file mode 100644 index 000000000000..48d82b54787b --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples-dev/verifyVerification.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Verifying idenity with verification code + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + console.log("\n== Request Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // id that is used to reference users phone number + const verificationId = "4d313ff0-3aeb-477e-8c15-7c9a893e8999"; + + // body of the request + const verificationRequest = { + verificationCode: "1234567", + }; + + // verifying your phone number + const status = await client.verifyIdentity(verificationId, verificationRequest); + console.log(status); +} + +main().catch((error) => { + console.log("The sample verifyVerification encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/README.md b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/README.md new file mode 100644 index 000000000000..62f3e9878473 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/README.md @@ -0,0 +1,70 @@ +--- +page_type: sample +languages: + - javascript +products: + - azure + - azure-communication-services +urlFragment: communication-recipient-verification-javascript-beta +--- + +# Azure Communication Services - Recipient Verification client library samples for JavaScript (Beta) + +These sample programs show how to use the JavaScript client libraries for Azure Communication Services - Recipient Verification in some common scenarios. + +| **File Name** | **Description** | +| ------------------------------------------------------- | ----------------------------------------- | +| [deleteVerification.js][deleteverification] | Delete a verification for a resource | +| [getAllVerifications.js][getallverifications] | Get all verifications for a resource | +| [getVerificationConstants.js][getverificationconstants] | Get verification constants for a resource | +| [requestVerification.js][requestverification] | Request identity verification | +| [verifyVerification.js][verifyverification] | Verifying idenity with verification code | + +## Prerequisites + +The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). + +You need [an Azure subscription][freesub] and the following Azure resources to run these sample programs: + +- [Azure Communication Services account][createinstance_azurecommunicationservicesaccount] + +Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. + +Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. + +## Setup + +To run the samples using the published version of the package: + +1. Install the dependencies using `npm`: + +```bash +npm install +``` + +2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. + +3. Run whichever samples you like (note that some samples may require additional setup, see the table above): + +```bash +node deleteVerification.js +``` + +Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): + +```bash +npx cross-env COMMUNICATION_SAMPLES_CONNECTION_STRING="" VERIFICATION_ID="" node deleteVerification.js +``` + +## Next Steps + +Here are some [samples] to look at. + +[deleteverification]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/deleteVerification.js +[getallverifications]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/getAllVerifications.js +[getverificationconstants]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/getVerificationConstants.js +[requestverification]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/requestVerification.js +[verifyverification]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/verifyVerification.js +[freesub]: https://azure.microsoft.com/free/ +[createinstance_azurecommunicationservicesaccount]: https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource +[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-recipient-verification/README.md diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/deleteVerification.js b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/deleteVerification.js new file mode 100644 index 000000000000..dc057b8b865b --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/deleteVerification.js @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Delete a verification for a resource + */ + +const { + RecipientVerificationClient, +} = require("@azure-tools/communication-recipient-verification"); + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + console.log("\n== Delete Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // id that is used to reference users phone number + const verificationId = process.env.VERIFICATION_ID; + + // delete verification for a resource + await client.deleteVerification(verificationId); +} + +main().catch((error) => { + console.log("The sample deleteVerification encountered an error:", error); + process.exit(1); +}); + +module.exports = { main }; diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/getAllVerifications.js b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/getAllVerifications.js new file mode 100644 index 000000000000..b8e5033c91d7 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/getAllVerifications.js @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Get all verifications for a resource + */ + +const { + RecipientVerificationClient, +} = require("@azure-tools/communication-recipient-verification"); + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + console.log("\n== Get All Verifications Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // get all verifications for a resource + var verifications = await client.getVerifications(); + + // print all verifications + for await (const verification of verifications) { + console.log(verification); + } +} + +main().catch((error) => { + console.log("The sample getAllVerifications encountered an error:", error); + process.exit(1); +}); + +module.exports = { main }; diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/getVerificationConstants.js b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/getVerificationConstants.js new file mode 100644 index 000000000000..8ea070d9a1f2 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/getVerificationConstants.js @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Get verification constants for a resource + */ + +const { + RecipientVerificationClient, +} = require("@azure-tools/communication-recipient-verification"); + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + console.log("\n== Get Verification Constants Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // get constants for the resource + var constants = await client.getVerificationConstants(); + + // print constant values + console.log(constants); +} + +main().catch((error) => { + console.log("The sample getVerificationConstants encountered an error:", error); + process.exit(1); +}); + +module.exports = { main }; diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/package.json b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/package.json new file mode 100644 index 000000000000..1418f7d2ad58 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/package.json @@ -0,0 +1,29 @@ +{ + "name": "@azure-samples/communication-recipient-verification-js-beta", + "private": true, + "version": "1.0.0", + "description": "Azure Communication Services - Recipient Verification client library samples for JavaScript (Beta)", + "engines": { + "node": ">=14.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Azure/azure-sdk-for-js.git", + "directory": "sdk/communication/communication-recipient-verification" + }, + "keywords": [ + "azure", + "cloud", + "communication" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-recipient-verification", + "dependencies": { + "@azure-tools/communication-recipient-verification": "next", + "dotenv": "latest" + } +} diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/requestVerification.js b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/requestVerification.js new file mode 100644 index 000000000000..bf90c5afe205 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/requestVerification.js @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Request identity verification + */ + +const { + RecipientVerificationClient, +} = require("@azure-tools/communication-recipient-verification"); + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + console.log("\n== Request Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // body of the request + const verificationRequest = { + identity: "+1123456789", + channel: "sms", + }; + + // get the verification status + var status = await client.requestVerification(verificationRequest); + + // print the status of the phone number + console.log(status); +} + +main().catch((error) => { + console.log("The sample requestVerification encountered an error:", error); + process.exit(1); +}); + +module.exports = { main }; diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/sample.env b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/sample.env new file mode 100644 index 000000000000..9692f1d54e30 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/sample.env @@ -0,0 +1,4 @@ +# Used in most samples. Retrieve these values from a Communication Services instance +# in the Azure Portal. +COMMUNICATION_SAMPLES_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" +VERIFICATION_ID="4d313ff0-3aeb-477e-8c15-7c9a893e8999" diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/verifyVerification.js b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/verifyVerification.js new file mode 100644 index 000000000000..9c14654be6f5 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/javascript/verifyVerification.js @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Verifying idenity with verification code + */ + +const { + RecipientVerificationClient, +} = require("@azure-tools/communication-recipient-verification"); + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + console.log("\n== Request Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // id that is used to reference users phone number + const verificationId = process.env.VERIFICATION_ID; + + // body of the request + const verificationRequest = { + verificationCode: "1234567", + }; + + // verifying your phone number + const status = await client.verifyIdentity(verificationId, verificationRequest); + console.log(status); +} + +main().catch((error) => { + console.log("The sample verifyVerification encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/README.md b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/README.md new file mode 100644 index 000000000000..e3366730d750 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/README.md @@ -0,0 +1,83 @@ +--- +page_type: sample +languages: + - typescript +products: + - azure + - azure-communication-services +urlFragment: communication-recipient-verification-typescript-beta +--- + +# Azure Communication Services - Recipient Verification client library samples for TypeScript (Beta) + +These sample programs show how to use the TypeScript client libraries for Azure Communication Services - Recipient Verification in some common scenarios. + +| **File Name** | **Description** | +| ------------------------------------------------------- | ----------------------------------------- | +| [deleteVerification.ts][deleteverification] | Delete a verification for a resource | +| [getAllVerifications.ts][getallverifications] | Get all verifications for a resource | +| [getVerificationConstants.ts][getverificationconstants] | Get verification constants for a resource | +| [requestVerification.ts][requestverification] | Request identity verification | +| [verifyVerification.ts][verifyverification] | Verifying idenity with verification code | + +## Prerequisites + +The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). + +Before running the samples in Node, they must be compiled to JavaScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using: + +```bash +npm install -g typescript +``` + +You need [an Azure subscription][freesub] and the following Azure resources to run these sample programs: + +- [Azure Communication Services account][createinstance_azurecommunicationservicesaccount] + +Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. + +Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. + +## Setup + +To run the samples using the published version of the package: + +1. Install the dependencies using `npm`: + +```bash +npm install +``` + +2. Compile the samples: + +```bash +npm run build +``` + +3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. + +4. Run whichever samples you like (note that some samples may require additional setup, see the table above): + +```bash +node dist/deleteVerification.js +``` + +Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): + +```bash +npx cross-env COMMUNICATION_SAMPLES_CONNECTION_STRING="" VERIFICATION_ID="" node dist/deleteVerification.js +``` + +## Next Steps + +Here are some [samples] to look at. + +[deleteverification]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/deleteVerification.ts +[getallverifications]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/getAllVerifications.ts +[getverificationconstants]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/getVerificationConstants.ts +[requestverification]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/requestVerification.ts +[verifyverification]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/verifyVerification.ts +[freesub]: https://azure.microsoft.com/free/ +[createinstance_azurecommunicationservicesaccount]: https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource +[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-recipient-verification/README.md +[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/package.json b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/package.json new file mode 100644 index 000000000000..91b2b73ddefb --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/package.json @@ -0,0 +1,38 @@ +{ + "name": "@azure-samples/communication-recipient-verification-ts-beta", + "private": true, + "version": "1.0.0", + "description": "Azure Communication Services - Recipient Verification client library samples for TypeScript (Beta)", + "engines": { + "node": ">=14.0.0" + }, + "scripts": { + "build": "tsc", + "prebuild": "rimraf dist/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Azure/azure-sdk-for-js.git", + "directory": "sdk/communication/communication-recipient-verification" + }, + "keywords": [ + "azure", + "cloud", + "communication" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-recipient-verification", + "dependencies": { + "@azure-tools/communication-recipient-verification": "next", + "dotenv": "latest" + }, + "devDependencies": { + "@types/node": "^14.0.0", + "typescript": "~4.8.0", + "rimraf": "latest" + } +} diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/sample.env b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/sample.env new file mode 100644 index 000000000000..9692f1d54e30 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/sample.env @@ -0,0 +1,4 @@ +# Used in most samples. Retrieve these values from a Communication Services instance +# in the Azure Portal. +COMMUNICATION_SAMPLES_CONNECTION_STRING="endpoint=https://.communication.azure.net/;accessKey=" +VERIFICATION_ID="4d313ff0-3aeb-477e-8c15-7c9a893e8999" diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/deleteVerification.ts b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/deleteVerification.ts new file mode 100644 index 000000000000..5c0cccf8b68e --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/deleteVerification.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Delete a verification for a resource + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +export async function main() { + console.log("\n== Delete Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // id that is used to reference users phone number + const verificationId = process.env.VERIFICATION_ID; + + // delete verification for a resource + await client.deleteVerification(verificationId); +} + +main().catch((error) => { + console.log("The sample deleteVerification encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/getAllVerifications.ts b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/getAllVerifications.ts new file mode 100644 index 000000000000..efc613a46482 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/getAllVerifications.ts @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Get all verifications for a resource + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +export async function main() { + console.log("\n== Get All Verifications Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // get all verifications for a resource + var verifications = await client.getVerifications(); + + // print all verifications + for await (const verification of verifications) { + console.log(verification); + } +} + +main().catch((error) => { + console.log("The sample getAllVerifications encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/getVerificationConstants.ts b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/getVerificationConstants.ts new file mode 100644 index 000000000000..35ddcd9cecb8 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/getVerificationConstants.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Get verification constants for a resource + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +export async function main() { + console.log("\n== Get Verification Constants Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // get constants for the resource + var constants = await client.getVerificationConstants(); + + // print constant values + console.log(constants); +} + +main().catch((error) => { + console.log("The sample getVerificationConstants encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/requestVerification.ts b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/requestVerification.ts new file mode 100644 index 000000000000..3916eb31be81 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/requestVerification.ts @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Request identity verification + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +export async function main() { + console.log("\n== Request Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // body of the request + const verificationRequest = { + identity: "+11234567890", + channel: "sms", + }; + + // get the verification status + var status = await client.requestVerification(verificationRequest); + + // print the status of the phone number + console.log(status); +} + +main().catch((error) => { + console.log("The sample requestVerification encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/verifyVerification.ts b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/verifyVerification.ts new file mode 100644 index 000000000000..daa9f919d820 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/src/verifyVerification.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * @summary Verifying idenity with verification code + */ + +import { RecipientVerificationClient } from "@azure-tools/communication-recipient-verification"; + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + console.log("\n== Request Verification Sample ==\n"); + + // You will need to set this environment variable or edit the following values + const connectionString = + process.env.COMMUNICATION_SAMPLES_CONNECTION_STRING || + "endpoint=https://resourceName.communication.azure.net/;accessKey=test-key"; + + // create new client + const client = new RecipientVerificationClient(connectionString); + + // id that is used to reference users phone number + const verificationId = process.env.VERIFICATION_ID; + + // body of the request + const verificationRequest = { + verificationCode: "1682793", + }; + + // verifying your phone number + const status = await client.verifyIdentity(verificationId, verificationRequest); + console.log(status); +} + +main().catch((error) => { + console.log("The sample verifyVerification encountered an error:", error); + process.exit(1); +}); diff --git a/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/tsconfig.json b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/tsconfig.json new file mode 100644 index 000000000000..e26ce2a6d8f7 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/samples/v1-beta/typescript/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "moduleResolution": "node", + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "alwaysStrict": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": [ + "src/**.ts" + ] +} diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/index.ts b/sdk/communication/communication-recipient-verification/src/generated/src/index.ts new file mode 100644 index 000000000000..2901f8b7b697 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/index.ts @@ -0,0 +1,11 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +export * from "./models"; +export { RecipientVerificationClient } from "./recipientVerificationClient"; +export * from "./operationsInterfaces"; diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/models/index.ts b/sdk/communication/communication-recipient-verification/src/generated/src/models/index.ts new file mode 100644 index 000000000000..695865e3a038 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/models/index.ts @@ -0,0 +1,139 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import * as coreClient from "@azure/core-client"; + +/** Model response returned for users. */ +export interface AcsVerification { + /** Immutable Id of the resource. */ + immutableId?: string; + /** VerificationId of the number assigned to the verified recipient. */ + verificationId?: string; + /** Status of the Verification (Pending or Verified). */ + status?: string; + /** Subscription Id of the resource. */ + subscriptionId?: string; + /** The phone number that was used to verify. */ + identity?: string; + /** Verification Id for the 3rd party verification service. */ + challengeId?: string; + /** Number of times the verification code has been sent. */ + retries?: number; + /** Number of times the user has tried to validate the code. */ + attempts?: number; +} + +/** The Communication Services error. */ +export interface CommunicationErrorResponse { + /** The Communication Services error. */ + error: CommunicationError; +} + +/** The Communication Services error. */ +export interface CommunicationError { + /** The error code. */ + code: string; + /** The error message. */ + message: string; + /** + * The error target. + * NOTE: This property will not be serialized. It can only be populated by the server. + */ + readonly target?: string; + /** + * Further details about specific errors that led to this error. + * NOTE: This property will not be serialized. It can only be populated by the server. + */ + readonly details?: CommunicationError[]; + /** + * The inner error if any. + * NOTE: This property will not be serialized. It can only be populated by the server. + */ + readonly innerError?: CommunicationError; +} + +/** Model to get the verification code. */ +export interface VerificationRequest { + /** The phone number that was used to verify. */ + identity?: string; + /** Prefered verification channel. */ + channel?: string; +} + +/** Model that contains the verification code. */ +export interface VerificationResponse { + /** VerificationId of the number assigned to the verified recipient. */ + verificationId?: string; + /** Verification status of the number. */ + isVerified?: boolean; +} + +/** Model that contains the verification code. */ +export interface VerificationCodeRequest { + /** The verification code returned. */ + verificationCode?: string; +} + +/** Model verified recipients. */ +export interface VerificationConstantsResponse { + /** Max retries allowed for resource. */ + maxRetriesAllowed?: number; + /** Max verified numbers allowed for resource. */ + maxVerificationsAllowed?: number; + /** Current number of verified numbers for the resource. */ + currentNumberOfVerifications?: number; +} + +/** Optional parameters. */ +export interface AcsVerificationGetVerificationsOptionalParams + extends coreClient.OperationOptions {} + +/** Contains response data for the getVerifications operation. */ +export type AcsVerificationGetVerificationsResponse = AcsVerification[]; + +/** Optional parameters. */ +export interface AcsVerificationRequestVerificationOptionalParams + extends coreClient.OperationOptions { + /** The phone number that was used to verify. */ + identity?: string; + /** Prefered verification channel. */ + channel?: string; +} + +/** Contains response data for the requestVerification operation. */ +export type AcsVerificationRequestVerificationResponse = VerificationResponse; + +/** Optional parameters. */ +export interface AcsVerificationVerifyIdentityOptionalParams + extends coreClient.OperationOptions { + /** The verification code returned. */ + verificationCode?: string; +} + +/** Contains response data for the verifyIdentity operation. */ +export type AcsVerificationVerifyIdentityResponse = VerificationResponse; + +/** Optional parameters. */ +export interface AcsVerificationDeleteVerificationOptionalParams + extends coreClient.OperationOptions {} + +/** Optional parameters. */ +export interface AcsVerificationGetVerificationConstantsOptionalParams + extends coreClient.OperationOptions {} + +/** Contains response data for the getVerificationConstants operation. */ +export type AcsVerificationGetVerificationConstantsResponse = VerificationConstantsResponse; + +/** Optional parameters. */ +export interface RecipientVerificationClientOptionalParams + extends coreClient.ServiceClientOptions { + /** Api Version */ + apiVersion?: string; + /** Overrides client endpoint. */ + endpoint?: string; +} diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/models/mappers.ts b/sdk/communication/communication-recipient-verification/src/generated/src/models/mappers.ts new file mode 100644 index 000000000000..6c21dfa9687d --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/models/mappers.ts @@ -0,0 +1,216 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import * as coreClient from "@azure/core-client"; + +export const AcsVerification: coreClient.CompositeMapper = { + type: { + name: "Composite", + className: "AcsVerification", + modelProperties: { + immutableId: { + serializedName: "ImmutableId", + type: { + name: "String" + } + }, + verificationId: { + serializedName: "VerificationId", + type: { + name: "String" + } + }, + status: { + serializedName: "Status", + type: { + name: "String" + } + }, + subscriptionId: { + serializedName: "SubscriptionId", + type: { + name: "String" + } + }, + identity: { + serializedName: "Identity", + type: { + name: "String" + } + }, + challengeId: { + serializedName: "ChallengeId", + type: { + name: "String" + } + }, + retries: { + serializedName: "Retries", + type: { + name: "Number" + } + }, + attempts: { + serializedName: "Attempts", + type: { + name: "Number" + } + } + } + } +}; + +export const CommunicationErrorResponse: coreClient.CompositeMapper = { + type: { + name: "Composite", + className: "CommunicationErrorResponse", + modelProperties: { + error: { + serializedName: "error", + type: { + name: "Composite", + className: "CommunicationError" + } + } + } + } +}; + +export const CommunicationError: coreClient.CompositeMapper = { + type: { + name: "Composite", + className: "CommunicationError", + modelProperties: { + code: { + serializedName: "code", + required: true, + type: { + name: "String" + } + }, + message: { + serializedName: "message", + required: true, + type: { + name: "String" + } + }, + target: { + serializedName: "target", + readOnly: true, + type: { + name: "String" + } + }, + details: { + serializedName: "details", + readOnly: true, + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "CommunicationError" + } + } + } + }, + innerError: { + serializedName: "innererror", + type: { + name: "Composite", + className: "CommunicationError" + } + } + } + } +}; + +export const VerificationRequest: coreClient.CompositeMapper = { + type: { + name: "Composite", + className: "VerificationRequest", + modelProperties: { + identity: { + serializedName: "Identity", + type: { + name: "String" + } + }, + channel: { + serializedName: "Channel", + type: { + name: "String" + } + } + } + } +}; + +export const VerificationResponse: coreClient.CompositeMapper = { + type: { + name: "Composite", + className: "VerificationResponse", + modelProperties: { + verificationId: { + serializedName: "VerificationId", + type: { + name: "String" + } + }, + isVerified: { + serializedName: "IsVerified", + type: { + name: "Boolean" + } + } + } + } +}; + +export const VerificationCodeRequest: coreClient.CompositeMapper = { + type: { + name: "Composite", + className: "VerificationCodeRequest", + modelProperties: { + verificationCode: { + serializedName: "VerificationCode", + type: { + name: "String" + } + } + } + } +}; + +export const VerificationConstantsResponse: coreClient.CompositeMapper = { + type: { + name: "Composite", + className: "VerificationConstantsResponse", + modelProperties: { + maxRetriesAllowed: { + serializedName: "MaxRetriesAllowed", + type: { + name: "Number" + } + }, + maxVerificationsAllowed: { + serializedName: "MaxVerificationsAllowed", + type: { + name: "Number" + } + }, + currentNumberOfVerifications: { + serializedName: "CurrentNumberOfVerifications", + type: { + name: "Number" + } + } + } + } +}; diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/models/parameters.ts b/sdk/communication/communication-recipient-verification/src/generated/src/models/parameters.ts new file mode 100644 index 000000000000..568ac3090e44 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/models/parameters.ts @@ -0,0 +1,91 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { + OperationParameter, + OperationURLParameter, + OperationQueryParameter +} from "@azure/core-client"; +import { + VerificationRequest as VerificationRequestMapper, + VerificationCodeRequest as VerificationCodeRequestMapper +} from "../models/mappers"; + +export const accept: OperationParameter = { + parameterPath: "accept", + mapper: { + defaultValue: "application/json", + isConstant: true, + serializedName: "Accept", + type: { + name: "String" + } + } +}; + +export const endpoint: OperationURLParameter = { + parameterPath: "endpoint", + mapper: { + serializedName: "endpoint", + required: true, + type: { + name: "String" + } + }, + skipEncoding: true +}; + +export const apiVersion: OperationQueryParameter = { + parameterPath: "apiVersion", + mapper: { + defaultValue: "2022-11-15", + isConstant: true, + serializedName: "api-version", + type: { + name: "String" + } + } +}; + +export const contentType: OperationParameter = { + parameterPath: ["options", "contentType"], + mapper: { + defaultValue: "application/json", + isConstant: true, + serializedName: "Content-Type", + type: { + name: "String" + } + } +}; + +export const identity: OperationParameter = { + parameterPath: ["options", "identity"], + mapper: VerificationRequestMapper +}; + +export const channel: OperationParameter = { + parameterPath: ["options", "channel"], + mapper: VerificationRequestMapper +}; + +export const verificationCode: OperationParameter = { + parameterPath: ["options", "verificationCode"], + mapper: VerificationCodeRequestMapper +}; + +export const verificationId: OperationURLParameter = { + parameterPath: "verificationId", + mapper: { + serializedName: "verificationId", + required: true, + type: { + name: "Uuid" + } + } +}; diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/operations/acsVerificationOperations.ts b/sdk/communication/communication-recipient-verification/src/generated/src/operations/acsVerificationOperations.ts new file mode 100644 index 000000000000..44ddfdccaaa0 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/operations/acsVerificationOperations.ts @@ -0,0 +1,237 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { tracingClient } from "../tracing"; +import { AcsVerificationOperations } from "../operationsInterfaces"; +import * as coreClient from "@azure/core-client"; +import * as Mappers from "../models/mappers"; +import * as Parameters from "../models/parameters"; +import { RecipientVerificationClient } from "../recipientVerificationClient"; +import { + AcsVerificationGetVerificationsOptionalParams, + AcsVerificationGetVerificationsResponse, + AcsVerificationRequestVerificationOptionalParams, + AcsVerificationRequestVerificationResponse, + AcsVerificationVerifyIdentityOptionalParams, + AcsVerificationVerifyIdentityResponse, + AcsVerificationDeleteVerificationOptionalParams, + AcsVerificationGetVerificationConstantsOptionalParams, + AcsVerificationGetVerificationConstantsResponse +} from "../models"; + +/** Class containing AcsVerificationOperations operations. */ +export class AcsVerificationOperationsImpl + implements AcsVerificationOperations { + private readonly client: RecipientVerificationClient; + + /** + * Initialize a new instance of the class AcsVerificationOperations class. + * @param client Reference to the service client + */ + constructor(client: RecipientVerificationClient) { + this.client = client; + } + + /** + * Gets the array of verified phone numbers for the current resource. + * @param options The options parameters. + */ + async getVerifications( + options?: AcsVerificationGetVerificationsOptionalParams + ): Promise { + return tracingClient.withSpan( + "RecipientVerificationClient.getVerifications", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + getVerificationsOperationSpec + ) as Promise; + } + ); + } + + /** + * Request the identity for the verification. + * @param options The options parameters. + */ + async requestVerification( + options?: AcsVerificationRequestVerificationOptionalParams + ): Promise { + return tracingClient.withSpan( + "RecipientVerificationClient.requestVerification", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + requestVerificationOperationSpec + ) as Promise; + } + ); + } + + /** + * Verify that the user received the correct verification code. + * @param verificationId Verification Id. Must be a valid GUID + * @param options The options parameters. + */ + async verifyIdentity( + verificationId: string, + options?: AcsVerificationVerifyIdentityOptionalParams + ): Promise { + return tracingClient.withSpan( + "RecipientVerificationClient.verifyIdentity", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { verificationId, options }, + verifyIdentityOperationSpec + ) as Promise; + } + ); + } + + /** + * Deleting a verification. + * @param verificationId Verification Id. Must be a valid GUID + * @param options The options parameters. + */ + async deleteVerification( + verificationId: string, + options?: AcsVerificationDeleteVerificationOptionalParams + ): Promise { + return tracingClient.withSpan( + "RecipientVerificationClient.deleteVerification", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { verificationId, options }, + deleteVerificationOperationSpec + ) as Promise; + } + ); + } + + /** + * Getting all the constants for the resource. + * @param options The options parameters. + */ + async getVerificationConstants( + options?: AcsVerificationGetVerificationConstantsOptionalParams + ): Promise { + return tracingClient.withSpan( + "RecipientVerificationClient.getVerificationConstants", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + getVerificationConstantsOperationSpec + ) as Promise; + } + ); + } +} +// Operation Specifications +const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); + +const getVerificationsOperationSpec: coreClient.OperationSpec = { + path: "/verifications", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: { + type: { + name: "Sequence", + element: { type: { name: "Composite", className: "AcsVerification" } } + } + } + }, + default: { + bodyMapper: Mappers.CommunicationErrorResponse + } + }, + queryParameters: [Parameters.apiVersion], + urlParameters: [Parameters.endpoint], + headerParameters: [Parameters.accept], + serializer +}; +const requestVerificationOperationSpec: coreClient.OperationSpec = { + path: "/verifications", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: Mappers.VerificationResponse + }, + default: { + bodyMapper: Mappers.CommunicationErrorResponse + } + }, + requestBody: { + parameterPath: { + identity: ["options", "identity"], + channel: ["options", "channel"] + }, + mapper: Mappers.VerificationRequest + }, + queryParameters: [Parameters.apiVersion], + urlParameters: [Parameters.endpoint], + headerParameters: [Parameters.accept, Parameters.contentType], + mediaType: "json", + serializer +}; +const verifyIdentityOperationSpec: coreClient.OperationSpec = { + path: "/verifications/{verificationId}/check", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: Mappers.VerificationResponse + }, + default: { + bodyMapper: Mappers.CommunicationErrorResponse + } + }, + requestBody: { + parameterPath: { verificationCode: ["options", "verificationCode"] }, + mapper: Mappers.VerificationCodeRequest + }, + queryParameters: [Parameters.apiVersion], + urlParameters: [Parameters.endpoint, Parameters.verificationId], + headerParameters: [Parameters.accept, Parameters.contentType], + mediaType: "json", + serializer +}; +const deleteVerificationOperationSpec: coreClient.OperationSpec = { + path: "/verifications/{verificationId}/", + httpMethod: "DELETE", + responses: { + 200: {}, + default: { + bodyMapper: Mappers.CommunicationErrorResponse + } + }, + queryParameters: [Parameters.apiVersion], + urlParameters: [Parameters.endpoint, Parameters.verificationId], + headerParameters: [Parameters.accept], + serializer +}; +const getVerificationConstantsOperationSpec: coreClient.OperationSpec = { + path: "/verifications/configuration", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.VerificationConstantsResponse + }, + default: { + bodyMapper: Mappers.CommunicationErrorResponse + } + }, + queryParameters: [Parameters.apiVersion], + urlParameters: [Parameters.endpoint], + headerParameters: [Parameters.accept], + serializer +}; diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/operations/index.ts b/sdk/communication/communication-recipient-verification/src/generated/src/operations/index.ts new file mode 100644 index 000000000000..0ab635719a40 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/operations/index.ts @@ -0,0 +1,9 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +export * from "./acsVerificationOperations"; diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/operationsInterfaces/acsVerificationOperations.ts b/sdk/communication/communication-recipient-verification/src/generated/src/operationsInterfaces/acsVerificationOperations.ts new file mode 100644 index 000000000000..4279f2fd11bd --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/operationsInterfaces/acsVerificationOperations.ts @@ -0,0 +1,62 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { + AcsVerificationGetVerificationsOptionalParams, + AcsVerificationGetVerificationsResponse, + AcsVerificationRequestVerificationOptionalParams, + AcsVerificationRequestVerificationResponse, + AcsVerificationVerifyIdentityOptionalParams, + AcsVerificationVerifyIdentityResponse, + AcsVerificationDeleteVerificationOptionalParams, + AcsVerificationGetVerificationConstantsOptionalParams, + AcsVerificationGetVerificationConstantsResponse +} from "../models"; + +/** Interface representing a AcsVerificationOperations. */ +export interface AcsVerificationOperations { + /** + * Gets the array of verified phone numbers for the current resource. + * @param options The options parameters. + */ + getVerifications( + options?: AcsVerificationGetVerificationsOptionalParams + ): Promise; + /** + * Request the identity for the verification. + * @param options The options parameters. + */ + requestVerification( + options?: AcsVerificationRequestVerificationOptionalParams + ): Promise; + /** + * Verify that the user received the correct verification code. + * @param verificationId Verification Id. Must be a valid GUID + * @param options The options parameters. + */ + verifyIdentity( + verificationId: string, + options?: AcsVerificationVerifyIdentityOptionalParams + ): Promise; + /** + * Deleting a verification. + * @param verificationId Verification Id. Must be a valid GUID + * @param options The options parameters. + */ + deleteVerification( + verificationId: string, + options?: AcsVerificationDeleteVerificationOptionalParams + ): Promise; + /** + * Getting all the constants for the resource. + * @param options The options parameters. + */ + getVerificationConstants( + options?: AcsVerificationGetVerificationConstantsOptionalParams + ): Promise; +} diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/operationsInterfaces/index.ts b/sdk/communication/communication-recipient-verification/src/generated/src/operationsInterfaces/index.ts new file mode 100644 index 000000000000..0ab635719a40 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/operationsInterfaces/index.ts @@ -0,0 +1,9 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +export * from "./acsVerificationOperations"; diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/recipientVerificationClient.ts b/sdk/communication/communication-recipient-verification/src/generated/src/recipientVerificationClient.ts new file mode 100644 index 000000000000..9c5090c801ad --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/recipientVerificationClient.ts @@ -0,0 +1,121 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import * as coreClient from "@azure/core-client"; +import * as coreRestPipeline from "@azure/core-rest-pipeline"; +import { + PipelineRequest, + PipelineResponse, + SendRequest +} from "@azure/core-rest-pipeline"; +import { AcsVerificationOperationsImpl } from "./operations"; +import { AcsVerificationOperations } from "./operationsInterfaces"; +import { RecipientVerificationClientOptionalParams } from "./models"; + +export class RecipientVerificationClient extends coreClient.ServiceClient { + endpoint: string; + apiVersion: string; + + /** + * Initializes a new instance of the RecipientVerificationClient class. + * @param endpoint The communication resource, for example https://resourcename.communication.azure.com + * @param options The parameter options + */ + constructor( + endpoint: string, + options?: RecipientVerificationClientOptionalParams + ) { + if (endpoint === undefined) { + throw new Error("'endpoint' cannot be null"); + } + + // Initializing default values for options + if (!options) { + options = {}; + } + const defaults: RecipientVerificationClientOptionalParams = { + requestContentType: "application/json; charset=utf-8" + }; + + const packageDetails = `azsdk-js-communication-recipient-verification/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + + const optionsWithDefaults = { + ...defaults, + ...options, + userAgentOptions: { + userAgentPrefix + }, + baseUri: options.endpoint ?? options.baseUri ?? "{endpoint}" + }; + super(optionsWithDefaults); + + if (options?.pipeline && options.pipeline.getOrderedPolicies().length > 0) { + const pipelinePolicies: coreRestPipeline.PipelinePolicy[] = options.pipeline.getOrderedPolicies(); + const bearerTokenAuthenticationPolicyFound = pipelinePolicies.some( + (pipelinePolicy) => + pipelinePolicy.name === + coreRestPipeline.bearerTokenAuthenticationPolicyName + ); + if (!bearerTokenAuthenticationPolicyFound) { + this.pipeline.removePolicy({ + name: coreRestPipeline.bearerTokenAuthenticationPolicyName + }); + this.pipeline.addPolicy( + coreRestPipeline.bearerTokenAuthenticationPolicy({ + scopes: `${optionsWithDefaults.baseUri}/.default`, + challengeCallbacks: { + authorizeRequestOnChallenge: + coreClient.authorizeRequestOnClaimChallenge + } + }) + ); + } + } + // Parameter assignments + this.endpoint = endpoint; + + // Assigning values to Constant parameters + this.apiVersion = options.apiVersion || "2022-11-15"; + this.acsVerificationOperations = new AcsVerificationOperationsImpl(this); + this.addCustomApiVersionPolicy(options.apiVersion); + } + + /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */ + private addCustomApiVersionPolicy(apiVersion?: string) { + if (!apiVersion) { + return; + } + const apiVersionPolicy = { + name: "CustomApiVersionPolicy", + async sendRequest( + request: PipelineRequest, + next: SendRequest + ): Promise { + const param = request.url.split("?"); + if (param.length > 1) { + const newParams = param[1].split("&").map((item) => { + if (item.indexOf("api-version") > -1) { + return "api-version=" + apiVersion; + } else { + return item; + } + }); + request.url = param[0] + "?" + newParams.join("&"); + } + return next(request); + } + }; + this.pipeline.addPolicy(apiVersionPolicy); + } + + acsVerificationOperations: AcsVerificationOperations; +} diff --git a/sdk/communication/communication-recipient-verification/src/generated/src/tracing.ts b/sdk/communication/communication-recipient-verification/src/generated/src/tracing.ts new file mode 100644 index 000000000000..6ab5b9f479f3 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/generated/src/tracing.ts @@ -0,0 +1,15 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createTracingClient } from "@azure/core-tracing"; + +export const tracingClient = createTracingClient({ + namespace: "Microsoft.Communication", + packageName: "@azure/communication-recipient-verification", + packageVersion: "1.0.0-beta.1" +}); diff --git a/sdk/communication/communication-recipient-verification/src/index.ts b/sdk/communication/communication-recipient-verification/src/index.ts new file mode 100644 index 000000000000..38485eb5bb2e --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/index.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export * from "./models"; +export * from "./mappers"; +export * from "./recipientVerificationClient"; diff --git a/sdk/communication/communication-recipient-verification/src/mappers.ts b/sdk/communication/communication-recipient-verification/src/mappers.ts new file mode 100644 index 000000000000..8709c2ccd75a --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/mappers.ts @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { AcsVerification as AcsVerificationMapper } from "./generated/src/models/mappers"; +export { VerificationConstantsResponse as ConstantsMapper } from "./generated/src/models/mappers"; +export { VerificationCodeRequest as VerificationCodeRequestMapper } from "./generated/src/models/mappers"; +export { VerificationResponse as VerificationResponseMapper } from "./generated/src/models/mappers"; +export { VerificationRequest as VerificationRequestMapper } from "./generated/src/models/mappers"; diff --git a/sdk/communication/communication-recipient-verification/src/models.ts b/sdk/communication/communication-recipient-verification/src/models.ts new file mode 100644 index 000000000000..5a8b6c303c61 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/models.ts @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + AcsVerificationGetVerificationsOptionalParams, + AcsVerificationGetVerificationsResponse, + AcsVerificationRequestVerificationOptionalParams, + AcsVerificationRequestVerificationResponse, + AcsVerificationVerifyIdentityOptionalParams, + AcsVerificationVerifyIdentityResponse, + AcsVerificationDeleteVerificationOptionalParams, + AcsVerificationGetVerificationConstantsOptionalParams, + AcsVerificationGetVerificationConstantsResponse, + AcsVerification, + VerificationConstantsResponse, + VerificationResponse, +} from "./generated/src/models"; diff --git a/sdk/communication/communication-recipient-verification/src/recipientVerificationClient.ts b/sdk/communication/communication-recipient-verification/src/recipientVerificationClient.ts new file mode 100644 index 000000000000..54175ec1344b --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/recipientVerificationClient.ts @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/// + +import { + AcsVerificationGetVerificationsOptionalParams, + AcsVerificationRequestVerificationOptionalParams, + AcsVerificationRequestVerificationResponse, + AcsVerificationVerifyIdentityOptionalParams, + AcsVerificationVerifyIdentityResponse, + AcsVerificationDeleteVerificationOptionalParams, + AcsVerificationGetVerificationConstantsOptionalParams, +} from "./models"; +import { CommonClientOptions, InternalClientPipelineOptions } from "@azure/core-client"; +import { KeyCredential, TokenCredential, isTokenCredential } from "@azure/core-auth"; +import { AcsVerification, VerificationConstantsResponse } from "./generated/src/models"; +import { createCommunicationAuthPolicy } from "@azure/communication-common"; +import { isKeyCredential, parseClientArguments } from "@azure/communication-common"; +import { RecipientVerificationClient as RecipientVerificationGeneratedClient } from "./generated/src"; +import { logger } from "./utils"; +import { tracingClient } from "./generated/src/tracing"; + +/** + * Client options used to configure the RecipientVerificationGeneratedClient API requests. + */ +export interface RecipientVerificationClientOptions extends CommonClientOptions {} + +const isRecipientVerificationClientOptions = ( + options: any +): options is RecipientVerificationClientOptions => + options && !isKeyCredential(options) && !isTokenCredential(options); + +/** + * Client class for interacting with Azure Communication Services Recipient Verification. + */ +export class RecipientVerificationClient { + /** + * A reference to the auto-generated RecipientVerification HTTP client. + */ + private readonly client: RecipientVerificationGeneratedClient; + + /** + * Initializes a new instance of the RecipientVerificationClient class using a connection string. + * + * @param connectionString - Connection string to connect to an Azure Communication Service resource. (eg: endpoint=https://contoso.eastus.communications.azure.net/;accesskey=secret) + * @param options - Optional. Options to configure the HTTP pipeline. + */ + public constructor(connectionString: string, options?: RecipientVerificationClientOptions); + + /** + * Initializes a new instance of the RecipientVerificationClient class using an Azure KeyCredential. + * + * @param endpoint - The endpoint of the service (eg: https://contoso.eastus.communications.azure.net) + * @param credential - An object that is used to authenticate requests to the service. Use the Azure KeyCredential or `@azure/identity` to create a credential. + * @param options - Optional. Options to configure the HTTP pipeline. + */ + public constructor( + endpoint: string, + credential: KeyCredential, + options?: RecipientVerificationClientOptions + ); + + /** + * Initializes a new instance of the RecipientVerificationClient class using an Azure KeyCredential. + * + * @param endpoint - The endpoint of the service (eg: https://contoso.eastus.communications.azure.net) + * @param credential - An object that is used to authenticate requests to the service. Use the Azure KeyCredential or `@azure/identity` to create a credential. + * @param options - Optional. Options to configure the HTTP pipeline. + */ + public constructor( + endpoint: string, + credential: TokenCredential, + options?: RecipientVerificationClientOptions + ); + + public constructor( + connectionStringOrUrl: string, + credentialOrOptions?: KeyCredential | TokenCredential | RecipientVerificationClientOptions, + maybeOptions: RecipientVerificationClientOptions = {} + ) { + const { url, credential } = parseClientArguments(connectionStringOrUrl, credentialOrOptions); + const options = isRecipientVerificationClientOptions(credentialOrOptions) + ? credentialOrOptions + : maybeOptions; + + const internalPipelineOptions: InternalClientPipelineOptions = { + ...options, + ...{ + loggingOptions: { + logger: logger.info, + }, + }, + }; + + this.client = new RecipientVerificationGeneratedClient(url, internalPipelineOptions); + const authPolicy = createCommunicationAuthPolicy(credential); + this.client.pipeline.addPolicy(authPolicy); + } + + /** + * Returns list of verified/pending phone numbers. + * + * @param options - Additional request options. + */ + public getVerifications( + options: AcsVerificationGetVerificationsOptionalParams = {} + ): Promise { + return tracingClient.withSpan( + "RecipientVerification.getVerifications", + options, + (updatedOptions) => { + return this.client.acsVerificationOperations.getVerifications(updatedOptions); + } + ); + } + + /** + * Removes a pending/verified number. + * + * @param verificationId - Id that is used to reference users phone number. + * @param options - Additional request options. + */ + public deleteVerification( + verificationId: string, + options: AcsVerificationDeleteVerificationOptionalParams = {} + ): Promise { + return tracingClient.withSpan( + "RecipientVerification.deleteVerification", + options, + (updatedOptions) => { + return this.client.acsVerificationOperations.deleteVerification( + verificationId, + updatedOptions + ); + } + ); + } + + /** + * Verifies a users phone number. + * + * @param verificationId - Id that is used to reference users phone number. + * @param options - Additional request options. + */ + public verifyIdentity( + verificationId: string, + options: AcsVerificationVerifyIdentityOptionalParams = {} + ): Promise { + return tracingClient.withSpan( + "RecipientVerification.verifyIdentity", + options, + (updatedOptions) => { + return this.client.acsVerificationOperations.verifyIdentity(verificationId, updatedOptions); + } + ); + } + + /** + * Returns information about a resource in relation to recipient verification. + * + * @param options - Additional request options. + */ + public getVerificationConstants( + options: AcsVerificationGetVerificationConstantsOptionalParams = {} + ): Promise { + return tracingClient.withSpan( + "RecipientVerification.getVerificationConstants", + options, + (updatedOptions) => { + return this.client.acsVerificationOperations.getVerificationConstants(updatedOptions); + } + ); + } + + /** + * Sends a code to users phone number that will be used for verification. + * + * @param options - Additional request options. + */ + public requestVerification( + options: AcsVerificationRequestVerificationOptionalParams = {} + ): Promise { + return tracingClient.withSpan( + "RecipientVerification.requestVerification", + options, + (updatedOptions) => { + return this.client.acsVerificationOperations.requestVerification(updatedOptions); + } + ); + } +} diff --git a/sdk/communication/communication-recipient-verification/src/utils/constants.ts b/sdk/communication/communication-recipient-verification/src/utils/constants.ts new file mode 100644 index 000000000000..47dc16dd0f7c --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/utils/constants.ts @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export const SDK_VERSION: string = "1.0.0-beta.1"; diff --git a/sdk/communication/communication-recipient-verification/src/utils/index.ts b/sdk/communication/communication-recipient-verification/src/utils/index.ts new file mode 100644 index 000000000000..996de929a1d3 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/utils/index.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export * from "./logger"; +export * from "./constants"; diff --git a/sdk/communication/communication-recipient-verification/src/utils/logger.ts b/sdk/communication/communication-recipient-verification/src/utils/logger.ts new file mode 100644 index 000000000000..0d985492b9cc --- /dev/null +++ b/sdk/communication/communication-recipient-verification/src/utils/logger.ts @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; + +/** + * The \@azure\/logger configuration for this package. + */ +export const logger = createClientLogger("communication-verified-recipients"); diff --git a/sdk/communication/communication-recipient-verification/swagger/README.md b/sdk/communication/communication-recipient-verification/swagger/README.md new file mode 100644 index 000000000000..88efefaf7df0 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/swagger/README.md @@ -0,0 +1,50 @@ +# Azure Communication Services Recipient Verification Module + +> see https://aka.ms/autorest + +## Configuration + +```yaml +package-name: "@azure/communication-recipient-verification" +description: Allows users to verify the phone number of recipients before sending messages or making calls to the phone number. +package-version: 1.0.0-beta.1 +license-header: MICROSOFT_MIT_NO_VERSION +output-folder: ../src/generated +input-file: ./swagger.json +model-date-time-as-string: false +optional-response-headers: true +payload-flattening-threshold: 10 +add-credentials: false +skip-enum-validation: true +v3: true +title: Recipient Verification Client +use-extension: + "@autorest/typescript": "6.0.0-rc.1" +tracing-info: + namespace: "Microsoft.Communication" + packagePrefix: "Azure.Communication" + +typescript: + generate-metadata: false + azure-arm: false +``` + +## Customizations + +### Disable extensible enums + +```yaml +directive: + - from: swagger-document + where: $.definitions[*].properties[*]["x-ms-enum"] + transform: > + if ($.modelAsString) { + $.modelAsString = false + } + - from: swagger-document + where: $.definitions[*].properties[*].items["x-ms-enum"] + transform: > + if ($.modelAsString) { + $.modelAsString = false + } +``` diff --git a/sdk/communication/communication-recipient-verification/swagger/swagger.json b/sdk/communication/communication-recipient-verification/swagger/swagger.json new file mode 100644 index 000000000000..822d81f6fcc0 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/swagger/swagger.json @@ -0,0 +1,404 @@ +{ + "swagger": "2.0", + "info": { + "title": "RecipientVerificationClient", + "description": "The recipient verification client library allows users to verify the phone number of recipients before sending messages or making calls to the phone number.", + "version": "2022-11-15" + }, + "paths": { + "/verifications": { + "get": { + "tags": [ + "ACS Verifications" + ], + "summary": "Gets the array of verified phone numbers for the current resource.", + "operationId": "AcsVerification_GetVerifications", + "produces": [ + "application/json" + ], + "parameters": [ + { + "$ref": "#/parameters/ApiVersionParameter" + } + ], + "responses": { + "200": { + "description": "Success", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/AcsVerification" + } + } + }, + "default": { + "description": "Failure", + "schema": { + "$ref": "#/definitions/CommunicationErrorResponse" + } + } + }, + "x-ms-examples": { + "List verified numbers": { + "$ref": "./examples/GetACSVerifications.json" + } + } + }, + "post": { + "tags": [ + "ACS Verifications" + ], + "summary": "Request the identity for the verification.", + "operationId": "ACSVerification_RequestVerification", + "produces": [ + "application/json" + ], + "parameters": [ + { + "$ref": "#/parameters/ApiVersionParameter" + }, + { + "in": "body", + "name": "body", + "description": "Data that contains the number and verification channel.", + "schema": { + "$ref": "#/definitions/VerificationRequest" + } + } + ], + "responses": { + "200": { + "description": "Success", + "schema": { + "$ref": "#/definitions/VerificationResponse" + } + }, + "default": { + "description": "Failure", + "schema": { + "$ref": "#/definitions/CommunicationErrorResponse" + } + } + }, + "x-ms-examples": { + "Request identity verification": { + "$ref": "./examples/RequestVerification.json" + } + } + } + }, + "/verifications/{verificationId}/check": { + "post": { + "tags": [ + "ACS Verifications" + ], + "summary": "Verify that the user received the correct verification code.", + "operationId": "ACSVerification_VerifyIdentity", + "produces": [ + "application/json" + ], + "parameters": [ + { + "in": "path", + "name": "verificationId", + "description": "Verification Id. Must be a valid GUID", + "required": true, + "type": "string", + "format": "uuid" + }, + { + "$ref": "#/parameters/ApiVersionParameter" + }, + { + "in": "body", + "name": "body", + "description": "Data that contains the verification code.", + "schema": { + "$ref": "#/definitions/VerificationCodeRequest" + } + } + ], + "responses": { + "200": { + "description": "Success", + "schema": { + "$ref": "#/definitions/VerificationResponse" + } + }, + "default": { + "description": "Failure", + "schema": { + "$ref": "#/definitions/CommunicationErrorResponse" + } + } + }, + "x-ms-examples": { + "Validate verification code": { + "$ref": "./examples/VerifyIdentity.json" + } + } + } + }, + "/verifications/{verificationId}/": { + "delete": { + "tags": [ + "ACS Verifications" + ], + "summary": "Deleting a verification.", + "operationId": "AcsVerification_DeleteVerification", + "produces": [ + "application/json" + ], + "parameters": [ + { + "in": "path", + "name": "verificationId", + "description": "Verification Id. Must be a valid GUID", + "required": true, + "type": "string", + "format": "uuid" + }, + { + "$ref": "#/parameters/ApiVersionParameter" + } + ], + "responses": { + "200": { + "description": "Success" + }, + "default": { + "description": "Failure", + "schema": { + "$ref": "#/definitions/CommunicationErrorResponse" + } + } + }, + "x-ms-examples": { + "Delete verified number": { + "$ref": "./examples/DeleteVerificationAsync.json" + } + } + } + }, + "/verifications/configuration": { + "get": { + "tags": [ + "ACS Verifications" + ], + "summary": "Getting all the constants for the resource.", + "operationId": "ACSVerification_GetVerificationConstants", + "produces": [ + "application/json" + ], + "parameters": [ + { + "$ref": "#/parameters/ApiVersionParameter" + } + ], + "responses": { + "200": { + "description": "Success", + "schema": { + "$ref": "#/definitions/VerificationConstantsResponse" + } + }, + "default": { + "description": "Failure", + "schema": { + "$ref": "#/definitions/CommunicationErrorResponse" + } + } + }, + "x-ms-examples": { + "Getting resource constants": { + "$ref": "./examples/GetVerifiedRecipientsConstants.json" + } + } + } + } + }, + "definitions": { + "AcsVerification": { + "description": "Model response returned for users.", + "type": "object", + "properties": { + "ImmutableId": { + "description": "Immutable Id of the resource.", + "type": "string" + }, + "VerificationId": { + "description": "VerificationId of the number assigned to the verified recipient.", + "type": "string" + }, + "Status": { + "description": "Status of the Verification (Pending or Verified). ", + "type": "string" + }, + "SubscriptionId": { + "description": "Subscription Id of the resource.", + "type": "string" + }, + "Identity": { + "description": "The phone number that was used to verify.", + "type": "string" + }, + "ChallengeId": { + "description": "Verification Id for the 3rd party verification service.", + "type": "string" + }, + "Retries": { + "description": "Number of times the verification code has been sent.", + "type": "integer" + }, + "Attempts": { + "description": "Number of times the user has tried to validate the code.", + "type": "integer" + } + } + }, + "VerificationCodeRequest":{ + "description": "Model that contains the verification code.", + "type": "object", + "properties": { + "VerificationCode": { + "description": "The verification code returned.", + "type": "string" + } + } + }, + "VerificationResponse":{ + "description": "Model that contains the verification code.", + "type": "object", + "properties": { + "VerificationId": { + "description": "VerificationId of the number assigned to the verified recipient.", + "type": "string" + }, + "IsVerified": { + "description": "Verification status of the number.", + "type": "boolean" + } + } + }, + "VerificationRequest":{ + "description": "Model to get the verification code.", + "type": "object", + "properties": { + "Identity": { + "description": "The phone number that was used to verify.", + "type": "string" + }, + "Channel": { + "description": "Prefered verification channel.", + "type": "string" + } + } + }, + "VerificationConstantsResponse":{ + "description": "Model verified recipients.", + "type": "object", + "properties": { + "MaxRetriesAllowed": { + "description": "Max retries allowed for resource.", + "type": "integer" + }, + "MaxVerificationsAllowed": { + "description": "Max verified numbers allowed for resource.", + "type": "integer" + }, + "CurrentNumberOfVerifications": { + "description": "Current number of verified numbers for the resource.", + "type": "integer" + } + } + }, + "CommunicationErrorResponse": { + "description": "The Communication Services error.", + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "description": "The Communication Services error.", + "$ref": "#/definitions/CommunicationError" + } + } + }, + "CommunicationError": { + "description": "The Communication Services error.", + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "The error code." + }, + "message": { + "type": "string", + "description": "The error message." + }, + "target": { + "type": "string", + "readOnly": true, + "description": "The error target." + }, + "details": { + "type": "array", + "items": { + "$ref": "#/definitions/CommunicationError" + }, + "readOnly": true, + "description": "Further details about specific errors that led to this error." + }, + "innererror": { + "x-ms-client-name": "innerError", + "readOnly": true, + "$ref": "#/definitions/CommunicationError", + "description": "The inner error if any." + } + } + } + }, + "parameters": { + "ApiVersionParameter": { + "in": "query", + "name": "api-version", + "description": "Version of API to invoke", + "required": true, + "type": "string" + }, + "Endpoint": { + "in": "path", + "name": "endpoint", + "description": "The communication resource, for example https://resourcename.communication.azure.com", + "required": true, + "type": "string", + "x-ms-skip-url-encoding": true, + "x-ms-parameter-location": "client" + } + }, + "securityDefinitions": { + "azure_auth": { + "type": "oauth2", + "flow": "implicit", + "authorizationUrl": "https://login.microsoftonline.com/common/oauth2/authorize", + "scopes": { + "user_impersonation": "impersonate your user account" + }, + "description": "Azure Active Directory OAuth2 Flow" + } + }, + "x-ms-parameterized-host": { + "hostTemplate": "{endpoint}", + "useSchemePrefix": false, + "parameters": [ + { + "$ref": "#/parameters/Endpoint" + } + ] + } +} diff --git a/sdk/communication/communication-recipient-verification/test/public/ctor.spec.ts b/sdk/communication/communication-recipient-verification/test/public/ctor.spec.ts new file mode 100644 index 000000000000..480fc2048b2b --- /dev/null +++ b/sdk/communication/communication-recipient-verification/test/public/ctor.spec.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { AzureKeyCredential } from "@azure/core-auth"; +import { Context } from "mocha"; +import { RecipientVerificationClient } from "../../src"; +import { assert } from "chai"; +import { createMockToken } from "./utils/recordedClient"; + +describe("RecipientVerificationClient - constructor", function () { + const endpoint = "https://contoso.spool.azure.local"; + const accessKey = "banana"; + + it("successfully instantiates with valid connection string", function () { + const client = new RecipientVerificationClient(`endpoint=${endpoint};accesskey=${accessKey}`); + assert.instanceOf(client, RecipientVerificationClient); + }); + + it("throws with invalid connection string", function () { + assert.throws(() => { + new RecipientVerificationClient(`endpoints=${endpoint};accesskey=${accessKey}`); + }); + }); + + it("successfully instantiates with with endpoint and access key", function () { + const client = new RecipientVerificationClient(endpoint, new AzureKeyCredential(accessKey)); + assert.instanceOf(client, RecipientVerificationClient); + }); + + it("successfully instantiates with with endpoint and managed identity", function (this: Context) { + const client = new RecipientVerificationClient(endpoint, createMockToken()); + assert.instanceOf(client, RecipientVerificationClient); + }); +}); diff --git a/sdk/communication/communication-recipient-verification/test/public/getVerificationConstants.spec.ts b/sdk/communication/communication-recipient-verification/test/public/getVerificationConstants.spec.ts new file mode 100644 index 000000000000..d6e450b72c8c --- /dev/null +++ b/sdk/communication/communication-recipient-verification/test/public/getVerificationConstants.spec.ts @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Context } from "mocha"; +import { Recorder } from "@azure-tools/test-recorder"; +import { RecipientVerificationClient } from "../../src"; +import { assert } from "chai"; +import { createRecordedClient } from "./utils/recordedClient"; + +describe(`RecipientVerificationClient - Get verification constants`, function () { + let recorder: Recorder; + let client: RecipientVerificationClient; + + beforeEach(async function (this: Context) { + ({ client, recorder } = await createRecordedClient(this)); + }); + + afterEach(async function (this: Context) { + if (!this.currentTest?.isPending()) { + await recorder.stop(); + } + }); + + it("get verification constants", async function () { + const verificationConstants = await client.getVerificationConstants(); + assert.isNotNull(verificationConstants.currentNumberOfVerifications); + assert.isNotNull(verificationConstants.maxRetriesAllowed); + assert.isNotNull(verificationConstants.maxVerificationsAllowed); + }).timeout(10000); +}); diff --git a/sdk/communication/communication-recipient-verification/test/public/listVerifications.spec.ts b/sdk/communication/communication-recipient-verification/test/public/listVerifications.spec.ts new file mode 100644 index 000000000000..bd5c4b414754 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/test/public/listVerifications.spec.ts @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Context } from "mocha"; +import { Recorder } from "@azure-tools/test-recorder"; +import { RecipientVerificationClient } from "../../src"; +import { assert } from "chai"; +import { createRecordedClient } from "./utils/recordedClient"; + +describe(`RecipientVerificationClient - List all verifications`, function () { + let recorder: Recorder; + let client: RecipientVerificationClient; + + beforeEach(async function (this: Context) { + ({ client, recorder } = await createRecordedClient(this)); + }); + + afterEach(async function (this: Context) { + if (!this.currentTest?.isPending()) { + await recorder.stop(); + } + }); + + it("get list of all verifications", async function () { + // print all verifications + for (const verification of await client.getVerifications()) { + assert.isNotNull(verification.immutableId); + } + }).timeout(10000); +}); diff --git a/sdk/communication/communication-recipient-verification/test/public/utils/recordedClient.ts b/sdk/communication/communication-recipient-verification/test/public/utils/recordedClient.ts new file mode 100644 index 000000000000..ca45f983f28b --- /dev/null +++ b/sdk/communication/communication-recipient-verification/test/public/utils/recordedClient.ts @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +import * as dotenv from "dotenv"; + +import { ClientSecretCredential, DefaultAzureCredential, TokenCredential } from "@azure/identity"; +import { + Recorder, + RecorderStartOptions, + assertEnvironmentVariable, + env, + isPlaybackMode, +} from "@azure-tools/test-recorder"; +import { Context } from "mocha"; +import { RecipientVerificationClient } from "../../../src"; +import { isNode } from "@azure/test-utils"; +import { parseConnectionString } from "@azure/communication-common"; + +if (isNode) { + dotenv.config(); +} + +export interface RecordedClient { + client: T; + recorder: Recorder; +} + +const envSetupForPlayback: { [k: string]: string } = { + COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING: "endpoint=https://endpoint/;accesskey=banana", + AZURE_CLIENT_ID: "SomeClientId", + AZURE_CLIENT_SECRET: "azure_client_secret", + AZURE_TENANT_ID: "SomeTenantId", +}; + +export const recorderOptions: RecorderStartOptions = { + envSetupForPlayback, + sanitizerOptions: { + connectionStringSanitizers: [ + { + actualConnString: env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING, + fakeConnString: envSetupForPlayback["COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING"], + }, + ], + generalSanitizers: [ + { + regex: true, + target: `[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}`, + value: "9d787bd6-07fc-4c7b-8e57-17f1fee41298", + }, + ], + }, +}; + +export async function createRecordedClient( + context: Context +): Promise> { + const recorder = new Recorder(context.currentTest); + await recorder.start(recorderOptions); + await recorder.setMatcher("CustomDefaultMatcher", { + excludedHeaders: [ + "Accept-Language", // This is env-dependent + "x-ms-content-sha256", // This is dependent on the current datetime + ], + }); + + // casting is a workaround to enable min-max testing + return { + client: new RecipientVerificationClient( + assertEnvironmentVariable("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING"), + recorder.configureClientOptions({}) + ), + recorder, + }; +} + +export function createMockToken(): { + getToken: (_scopes: string) => Promise<{ token: string; expiresOnTimestamp: number }>; +} { + return { + getToken: async (_scopes: string) => { + return { token: "testToken", expiresOnTimestamp: 11111 }; + }, + }; +} + +export async function createRecordedClientWithToken( + context: Context +): Promise | undefined> { + const recorder = new Recorder(context.currentTest); + await recorder.start(recorderOptions); + + let credential: TokenCredential; + const endpoint = parseConnectionString( + assertEnvironmentVariable("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING") + ).endpoint; + + if (isPlaybackMode()) { + credential = createMockToken(); + + // casting is a workaround to enable min-max testing + return { + client: new RecipientVerificationClient( + endpoint, + credential, + recorder.configureClientOptions({}) + ), + recorder, + }; + } + + if (isNode) { + credential = new DefaultAzureCredential(); + } else { + credential = new ClientSecretCredential( + assertEnvironmentVariable("AZURE_TENANT_ID"), + assertEnvironmentVariable("AZURE_CLIENT_ID"), + assertEnvironmentVariable("AZURE_CLIENT_SECRET") + ); + } + + // casting is a workaround to enable min-max testing + return { + client: new RecipientVerificationClient( + endpoint, + credential, + recorder.configureClientOptions({}) + ), + recorder, + }; +} + +export const testPollerOptions = { + pollInterval: isPlaybackMode() ? 0 : undefined, +}; diff --git a/sdk/communication/communication-recipient-verification/tests.yml b/sdk/communication/communication-recipient-verification/tests.yml new file mode 100644 index 000000000000..583800bb0d51 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/tests.yml @@ -0,0 +1,20 @@ +trigger: none + +stages: + - template: /eng/pipelines/templates/stages/archetype-sdk-tests.yml + parameters: + PackageName: "@azure-tools/communication-recipient-verification" + ServiceDirectory: communication + CloudConfig: + Public: + SubscriptionConfigurations: + - $(sub-config-azure-cloud-test-resources) + - $(sub-config-communication-services-cloud-test-resources-common) + - $(sub-config-communication-services-cloud-test-resources-js) + Int: + SubscriptionConfigurations: + - $(sub-config-communication-int-test-resources-common) + - $(sub-config-communication-int-test-resources-js) + MatrixFilters: + - TestType=^(?!(browser|sample)).* + Clouds: Public,Int diff --git a/sdk/communication/communication-recipient-verification/tsconfig.json b/sdk/communication/communication-recipient-verification/tsconfig.json new file mode 100644 index 000000000000..d331e3cf6706 --- /dev/null +++ b/sdk/communication/communication-recipient-verification/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.package", + "compilerOptions": { + "outDir": "./dist-esm", + "declarationDir": "./types", + "paths": { + "@azure-tools/communication-recipient-verification": ["./src/index"] + } + }, + "include": ["src/**/*.ts", "test/**/*.ts", "samples-dev/**/*.ts"] +}