diff --git a/apps/browser/src/auth/popup/login.component.ts b/apps/browser/src/auth/popup/login.component.ts index 539ef43a4aa..5b8a77b799b 100644 --- a/apps/browser/src/auth/popup/login.component.ts +++ b/apps/browser/src/auth/popup/login.component.ts @@ -118,7 +118,9 @@ export class LoginComponent extends BaseLoginComponent { "&state=" + state + "&codeChallenge=" + - codeChallenge + codeChallenge + + "&email=" + + encodeURIComponent(this.formGroup.controls.email.value) ); } } diff --git a/apps/web/src/app/core/event.service.ts b/apps/web/src/app/core/event.service.ts index 4556140afbb..6cf0c052d5e 100644 --- a/apps/web/src/app/core/event.service.ts +++ b/apps/web/src/app/core/event.service.ts @@ -397,6 +397,19 @@ export class EventService { this.getShortId(ev.providerOrganizationId) ); break; + // Org Domain claiming events + case EventType.OrganizationDomain_Added: + msg = humanReadableMsg = this.i18nService.t("addedDomain", ev.domainName); + break; + case EventType.OrganizationDomain_Removed: + msg = humanReadableMsg = this.i18nService.t("removedDomain", ev.domainName); + break; + case EventType.OrganizationDomain_Verified: + msg = humanReadableMsg = this.i18nService.t("domainVerifiedEvent", ev.domainName); + break; + case EventType.OrganizationDomain_NotVerified: + msg = humanReadableMsg = this.i18nService.t("domainNotVerifiedEvent", ev.domainName); + break; default: break; } @@ -446,6 +459,8 @@ export class EventService { return ["bwi-globe", this.i18nService.t("webVault") + " - Edge"]; case DeviceType.IEBrowser: return ["bwi-globe", this.i18nService.t("webVault") + " - IE"]; + case DeviceType.Server: + return ["bwi-server", this.i18nService.t("server")]; case DeviceType.UnknownBrowser: return [ "bwi-globe", diff --git a/apps/web/src/app/organizations/manage/events.component.ts b/apps/web/src/app/organizations/manage/events.component.ts index 3104bed7593..e1c0d46c827 100644 --- a/apps/web/src/app/organizations/manage/events.component.ts +++ b/apps/web/src/app/organizations/manage/events.component.ts @@ -19,6 +19,11 @@ import { EventResponse } from "@bitwarden/common/models/response/event.response" import { BaseEventsComponent } from "../../common/base.events.component"; import { EventService } from "../../core"; +const EVENT_SYSTEM_USER_TO_TRANSLATION: Record = { + [EventSystemUser.SCIM]: null, // SCIM acronym not able to be translated so just display SCIM + [EventSystemUser.DomainVerification]: "domainVerification", +}; + @Component({ selector: "app-org-events", templateUrl: "events.component.html", @@ -134,9 +139,17 @@ export class EventsComponent extends BaseEventsComponent implements OnInit, OnDe } if (r.systemUser != null) { - return { - name: EventSystemUser[r.systemUser], - }; + const systemUserI18nKey: string = EVENT_SYSTEM_USER_TO_TRANSLATION[r.systemUser]; + + if (systemUserI18nKey) { + return { + name: this.i18nService.t(systemUserI18nKey), + }; + } else { + return { + name: EventSystemUser[r.systemUser], + }; + } } return null; diff --git a/apps/web/src/app/organizations/settings/settings.component.html b/apps/web/src/app/organizations/settings/settings.component.html index c2bd1ec19a5..3fbbc3b42c1 100644 --- a/apps/web/src/app/organizations/settings/settings.component.html +++ b/apps/web/src/app/organizations/settings/settings.component.html @@ -44,6 +44,14 @@ > {{ "exportVault" | i18n }} + + {{ "domainVerification" | i18n }} + -
+ diff --git a/apps/web/src/auth/sso.component.ts b/apps/web/src/auth/sso.component.ts index 14fe1bb3752..63dc54cec9a 100644 --- a/apps/web/src/auth/sso.component.ts +++ b/apps/web/src/auth/sso.component.ts @@ -8,10 +8,16 @@ import { CryptoFunctionService } from "@bitwarden/common/abstractions/cryptoFunc import { EnvironmentService } from "@bitwarden/common/abstractions/environment.service"; import { I18nService } from "@bitwarden/common/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/abstractions/log.service"; +import { OrgDomainApiServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain-api.service.abstraction"; +import { OrganizationDomainSsoDetailsResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain-sso-details.response"; import { PasswordGenerationService } from "@bitwarden/common/abstractions/passwordGeneration.service"; import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service"; import { StateService } from "@bitwarden/common/abstractions/state.service"; +import { ValidationService } from "@bitwarden/common/abstractions/validation.service"; import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; +import { LoginService } from "@bitwarden/common/auth/abstractions/login.service"; +import { HttpStatusCode } from "@bitwarden/common/enums/http-status-code.enum"; +import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; @Component({ selector: "app-sso", @@ -30,7 +36,10 @@ export class SsoComponent extends BaseSsoComponent { cryptoFunctionService: CryptoFunctionService, environmentService: EnvironmentService, passwordGenerationService: PasswordGenerationService, - logService: LogService + logService: LogService, + private orgDomainApiService: OrgDomainApiServiceAbstraction, + private loginService: LoginService, + private validationService: ValidationService ) { super( authService, @@ -51,11 +60,37 @@ export class SsoComponent extends BaseSsoComponent { async ngOnInit() { super.ngOnInit(); + // eslint-disable-next-line rxjs-angular/prefer-takeuntil, rxjs/no-async-subscribe this.route.queryParams.pipe(first()).subscribe(async (qParams) => { if (qParams.identifier != null) { + // SSO Org Identifier in query params takes precedence over claimed domains this.identifier = qParams.identifier; } else { + // Note: this flow is written for web but both browser and desktop + // redirect here on SSO button click. + + // Check if email matches any claimed domains + if (qParams.email) { + // show loading spinner + this.loggingIn = true; + try { + const response: OrganizationDomainSsoDetailsResponse = + await this.orgDomainApiService.getClaimedOrgDomainByEmail(qParams.email); + + if (response?.ssoAvailable) { + this.identifier = response.organizationIdentifier; + await this.submit(); + return; + } + } catch (error) { + this.handleGetClaimedDomainByEmailError(error); + } + + this.loggingIn = false; + } + + // Fallback to state svc if domain is unclaimed const storedIdentifier = await this.stateService.getSsoOrgIdentifier(); if (storedIdentifier != null) { this.identifier = storedIdentifier; @@ -64,6 +99,24 @@ export class SsoComponent extends BaseSsoComponent { }); } + private handleGetClaimedDomainByEmailError(error: any): void { + if (error instanceof ErrorResponse) { + const errorResponse: ErrorResponse = error as ErrorResponse; + switch (errorResponse.statusCode) { + case HttpStatusCode.NotFound: + if (errorResponse?.message?.includes("Claimed org domain not found")) { + // Do nothing. This is a valid case. + return; + } + break; + + default: + this.validationService.showError(errorResponse); + break; + } + } + } + async submit() { await this.stateService.setSsoOrganizationIdentifier(this.identifier); if (this.clientId === "browser") { diff --git a/apps/web/src/images/domain-verification/domain.svg b/apps/web/src/images/domain-verification/domain.svg new file mode 100644 index 00000000000..66b0ece2b10 --- /dev/null +++ b/apps/web/src/images/domain-verification/domain.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/src/locales/en/messages.json b/apps/web/src/locales/en/messages.json index 9ccd70e3242..875c9efb302 100644 --- a/apps/web/src/locales/en/messages.json +++ b/apps/web/src/locales/en/messages.json @@ -6039,6 +6039,135 @@ "memberAccessAll": { "message": "This member can access and modify all items." }, + "domainVerification": { + "message": "Domain verification" + }, + "newDomain": { + "message": "New domain" + }, + "noDomains": { + "message": "No domains" + }, + "noDomainsSubText": { + "message": "Connecting a domain allows members to skip the SSO identifier field during Login with SSO." + }, + "verifyDomain": { + "message": "Verify domain" + }, + "reverifyDomain": { + "message": "Reverify domain" + }, + "copyDnsTxtRecord": { + "message": "Copy DNS TXT record" + }, + "dnsTxtRecord": { + "message": "DNS TXT record" + }, + "dnsTxtRecordInputHint": { + "message": "Copy and paste the TXT record into your DNS Provider." + }, + "domainNameInputHint": { + "message": "Example: mydomain.com. Subdomains require separate entries to be verified." + }, + "automaticDomainVerification": { + "message": "Automatic Domain Verification" + }, + "automaticDomainVerificationProcess": { + "message": "Bitwarden will attempt to verify the domain 3 times during the first 72 hours. If the domain can’t be verified, check the DNS record in your host and manually verify. The domain will be removed from your organization in 7 days if it is not verified" + }, + "invalidDomainNameMessage": { + "message": "Input is not a valid format. Format: mydomain.com. Subdomains require separate entries to be verified." + }, + "removeDomain": { + "message": "Remove domain" + }, + "removeDomainWarning": { + "message": "Removing a domain cannot be undone. Are you sure you want to continue?" + }, + "domainRemoved": { + "message": "Domain removed" + }, + "domainSaved": { + "message": "Domain saved" + }, + "domainVerified": { + "message": "Domain verified" + }, + "duplicateDomainError": { + "message": "You can't claim the same domain twice." + }, + "domainNotAvailable": { + "message": "Someone else is using $DOMAIN$. Use a different domain to continue.", + "placeholders": { + "DOMAIN": { + "content": "$1", + "example": "bitwarden.com" + } + } + }, + "domainNotVerified": { + "message": "$DOMAIN$ not verified. Check your DNS record.", + "placeholders": { + "DOMAIN": { + "content": "$1", + "example": "bitwarden.com" + } + } + }, + "domainStatusVerified": { + "message": "Verified" + }, + "domainStatusUnverified": { + "message": "Unverified" + }, + "domainNameTh": { + "message": "Name" + }, + "domainStatusTh": { + "message": "Status" + }, + "lastChecked": { + "message": "Last checked" + }, + "domainFormInvalid": { + "message": "There are form errors that need your attention" + }, + "addedDomain": { + "message": "Added domain $DOMAIN$", + "placeholders": { + "DOMAIN": { + "content": "$1", + "example": "bitwarden.com" + } + } + }, + "removedDomain": { + "message": "Removed domain $DOMAIN$", + "placeholders": { + "DOMAIN": { + "content": "$1", + "example": "bitwarden.com" + } + } + }, + "domainVerifiedEvent": { + "message": "$DOMAIN$ verified", + "placeholders": { + "DOMAIN": { + "content": "$1", + "example": "bitwarden.com" + } + } + }, + "domainNotVerifiedEvent": { + "message": "$DOMAIN$ not verified", + "placeholders": { + "DOMAIN": { + "content": "$1", + "example": "bitwarden.com" + } + } + }, "membersColumnHeader": { "message": "Member/Group" }, @@ -6114,6 +6243,9 @@ } } }, + "server": { + "message": "Server" + }, "exportData": { "message": "Export data" }, diff --git a/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/domain-add-edit-dialog.component.html b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/domain-add-edit-dialog.component.html new file mode 100644 index 00000000000..38d1de2ccb4 --- /dev/null +++ b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/domain-add-edit-dialog.component.html @@ -0,0 +1,75 @@ +
+ + + {{ "newDomain" | i18n }} + {{ "verifyDomain" | i18n }} + + {{ + data.orgDomain.domainName + }} + + {{ + "domainStatusUnverified" | i18n + }} + {{ + "domainStatusVerified" | i18n + }} + +
+ + {{ "domainName" | i18n }} + + {{ "domainNameInputHint" | i18n }} + + + + {{ "dnsTxtRecord" | i18n }} + + {{ "dnsTxtRecordInputHint" | i18n }} + + + + + {{ "automaticDomainVerificationProcess" | i18n }} + +
+
+ + + + +
+
+
diff --git a/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/domain-add-edit-dialog.component.ts b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/domain-add-edit-dialog.component.ts new file mode 100644 index 00000000000..1bf22a1df4b --- /dev/null +++ b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/domain-add-edit-dialog.component.ts @@ -0,0 +1,270 @@ +import { DialogRef, DIALOG_DATA } from "@angular/cdk/dialog"; +import { Component, Inject, OnDestroy, OnInit } from "@angular/core"; +import { FormBuilder, FormControl, FormGroup, ValidatorFn, Validators } from "@angular/forms"; +import { Subject, takeUntil } from "rxjs"; + +import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "@bitwarden/common/abstractions/cryptoFunction.service"; +import { I18nService } from "@bitwarden/common/abstractions/i18n.service"; +import { OrgDomainApiServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain-api.service.abstraction"; +import { OrgDomainServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain.service.abstraction"; +import { OrganizationDomainResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain.response"; +import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service"; +import { ValidationService } from "@bitwarden/common/abstractions/validation.service"; +import { HttpStatusCode } from "@bitwarden/common/enums/http-status-code.enum"; +import { Utils } from "@bitwarden/common/misc/utils"; +import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; +import { OrganizationDomainRequest } from "@bitwarden/common/services/organization-domain/requests/organization-domain.request"; + +import { domainNameValidator } from "./validators/domain-name.validator"; +import { uniqueInArrayValidator } from "./validators/unique-in-array.validator"; +export interface DomainAddEditDialogData { + organizationId: string; + orgDomain: OrganizationDomainResponse; + existingDomainNames: Array; +} + +@Component({ + selector: "app-domain-add-edit-dialog", + templateUrl: "domain-add-edit-dialog.component.html", +}) +export class DomainAddEditDialogComponent implements OnInit, OnDestroy { + private componentDestroyed$: Subject = new Subject(); + + domainForm: FormGroup = this.formBuilder.group({ + domainName: [ + "", + [ + Validators.required, + domainNameValidator(this.i18nService.t("invalidDomainNameMessage")), + uniqueInArrayValidator( + this.data.existingDomainNames, + this.i18nService.t("duplicateDomainError") + ), + ], + ], + txt: [{ value: null, disabled: true }], + }); + + get domainNameCtrl(): FormControl { + return this.domainForm.controls.domainName as FormControl; + } + get txtCtrl(): FormControl { + return this.domainForm.controls.txt as FormControl; + } + + rejectedDomainNameValidator: ValidatorFn = null; + + rejectedDomainNames: Array = []; + + constructor( + public dialogRef: DialogRef, + @Inject(DIALOG_DATA) public data: DomainAddEditDialogData, + private formBuilder: FormBuilder, + private cryptoFunctionService: CryptoFunctionServiceAbstraction, + private platformUtilsService: PlatformUtilsService, + private i18nService: I18nService, + private orgDomainApiService: OrgDomainApiServiceAbstraction, + private orgDomainService: OrgDomainServiceAbstraction, + private validationService: ValidationService + ) {} + + //#region Angular Method Implementations + + async ngOnInit(): Promise { + // If we have data.orgDomain, then editing, otherwise creating new domain + await this.populateForm(); + } + + ngOnDestroy(): void { + this.componentDestroyed$.next(); + this.componentDestroyed$.complete(); + } + + //#endregion + + //#region Form methods + + async populateForm(): Promise { + if (this.data.orgDomain) { + // Edit + this.domainForm.patchValue(this.data.orgDomain); + this.domainForm.disable(); + } else { + // Add + + // Figuring out the proper length of our DNS TXT Record value was fun. + // DNS-Based Service Discovery RFC: https://www.ietf.org/rfc/rfc6763.txt; see section 6.1 + // Google uses 43 chars for their TXT record value: https://support.google.com/a/answer/2716802 + // So, chose a magic # of 33 bytes to achieve at least that once converted to base 64 (47 char length). + const generatedTxt = `bw=${Utils.fromBufferToB64( + await this.cryptoFunctionService.randomBytes(33) + )}`; + this.txtCtrl.setValue(generatedTxt); + } + + this.setupFormListeners(); + } + + setupFormListeners(): void { + // suppresses touched state on change for reactive form controls + // Manually set touched to show validation errors as the user stypes + this.domainForm.valueChanges.pipe(takeUntil(this.componentDestroyed$)).subscribe(() => { + this.domainForm.markAllAsTouched(); + }); + } + + copyDnsTxt(): void { + this.orgDomainService.copyDnsTxt(this.txtCtrl.value); + } + + //#endregion + + //#region Async Form Actions + saveDomain = async (): Promise => { + if (this.domainForm.invalid) { + this.platformUtilsService.showToast("error", null, this.i18nService.t("domainFormInvalid")); + return; + } + + this.domainNameCtrl.disable(); + + const request: OrganizationDomainRequest = new OrganizationDomainRequest( + this.txtCtrl.value, + this.domainNameCtrl.value + ); + + try { + this.data.orgDomain = await this.orgDomainApiService.post(this.data.organizationId, request); + this.platformUtilsService.showToast("success", null, this.i18nService.t("domainSaved")); + await this.verifyDomain(); + } catch (e) { + this.handleDomainSaveError(e); + } + }; + + private handleDomainSaveError(e: any): void { + if (e instanceof ErrorResponse) { + const errorResponse: ErrorResponse = e as ErrorResponse; + switch (errorResponse.statusCode) { + case HttpStatusCode.Conflict: + if (errorResponse.message.includes("The domain is not available to be claimed")) { + // If user has attempted to claim a different rejected domain first: + if (this.rejectedDomainNameValidator) { + // Remove the validator: + this.domainNameCtrl.removeValidators(this.rejectedDomainNameValidator); + this.domainNameCtrl.updateValueAndValidity(); + } + + // Update rejected domain names and add new unique in validator + // which will prevent future known bad domain name submissions. + this.rejectedDomainNames.push(this.domainNameCtrl.value); + + this.rejectedDomainNameValidator = uniqueInArrayValidator( + this.rejectedDomainNames, + this.i18nService.t("domainNotAvailable", this.domainNameCtrl.value) + ); + + this.domainNameCtrl.addValidators(this.rejectedDomainNameValidator); + this.domainNameCtrl.updateValueAndValidity(); + + // Give them another chance to enter a new domain name: + this.domainForm.enable(); + } else { + this.validationService.showError(errorResponse); + } + + break; + + default: + this.validationService.showError(errorResponse); + break; + } + } else { + this.validationService.showError(e); + } + } + + verifyDomain = async (): Promise => { + if (this.domainForm.invalid) { + // Note: shouldn't be possible, but going to leave this to be safe. + this.platformUtilsService.showToast("error", null, this.i18nService.t("domainFormInvalid")); + return; + } + + try { + this.data.orgDomain = await this.orgDomainApiService.verify( + this.data.organizationId, + this.data.orgDomain.id + ); + + if (this.data.orgDomain.verifiedDate) { + this.platformUtilsService.showToast("success", null, this.i18nService.t("domainVerified")); + this.dialogRef.close(); + } else { + this.domainNameCtrl.setErrors({ + errorPassthrough: { + message: this.i18nService.t("domainNotVerified", this.domainNameCtrl.value), + }, + }); + // For the case where user opens dialog and reverifies when domain name formControl disabled. + // The input directive only shows error if touched, so must manually mark as touched. + this.domainNameCtrl.markAsTouched(); + // Update this item so the last checked date gets updated. + await this.updateOrgDomain(); + } + } catch (e) { + this.handleVerifyDomainError(e, this.domainNameCtrl.value); + // Update this item so the last checked date gets updated. + await this.updateOrgDomain(); + } + }; + + private handleVerifyDomainError(e: any, domainName: string): void { + if (e instanceof ErrorResponse) { + const errorResponse: ErrorResponse = e as ErrorResponse; + switch (errorResponse.statusCode) { + case HttpStatusCode.Conflict: + if (errorResponse.message.includes("The domain is not available to be claimed")) { + this.domainNameCtrl.setErrors({ + errorPassthrough: { + message: this.i18nService.t("domainNotAvailable", domainName), + }, + }); + } + break; + + default: + this.validationService.showError(errorResponse); + break; + } + } + } + + private async updateOrgDomain() { + // Update this item so the last checked date gets updated. + await this.orgDomainApiService.getByOrgIdAndOrgDomainId( + this.data.organizationId, + this.data.orgDomain.id + ); + } + + deleteDomain = async (): Promise => { + const confirmed = await this.platformUtilsService.showDialog( + this.i18nService.t("removeDomainWarning"), + this.i18nService.t("removeDomain"), + this.i18nService.t("yes"), + this.i18nService.t("no"), + "warning" + ); + if (!confirmed) { + return; + } + + await this.orgDomainApiService.delete(this.data.organizationId, this.data.orgDomain.id); + this.platformUtilsService.showToast("success", null, this.i18nService.t("domainRemoved")); + + this.dialogRef.close(); + }; + + //#endregion +} diff --git a/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/validators/domain-name.validator.ts b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/validators/domain-name.validator.ts new file mode 100644 index 00000000000..e49ca16e193 --- /dev/null +++ b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/validators/domain-name.validator.ts @@ -0,0 +1,47 @@ +import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms"; + +export function domainNameValidator(errorMessage: string): ValidatorFn { + return (control: AbstractControl): ValidationErrors | null => { + const value = control.value; + + if (!value) { + return null; + } + + // Domain labels (sections) are only allowed to be 63 chars in length max + // 1st and last chars cannot be hyphens per RFC 3696 (https://www.rfc-editor.org/rfc/rfc3696#section-2) + // We do not want any prefixes per industry standards. + + // Must support top-level domains and any number of subdomains. + // / # start regex + // ^ # start of string + // (?!(http(s)?:\/\/|www\.)) # negative lookahead to check if input doesn't match "http://", "https://" or "www." + // [a-zA-Z0-9] # first character must be a letter or a number + // [a-zA-Z0-9-]{0,61} # domain name can have 0 to 61 characters that are letters, numbers, or hyphens + // [a-zA-Z0-9] # domain name must end with a letter or a number + // (?: # start of non-capturing group (subdomain sections are optional) + // \. # subdomain must have a period + // [a-zA-Z0-9] # first character of subdomain must be a letter or a number + // [a-zA-Z0-9-]{0,61} # subdomain can have 0 to 61 characters that are letters, numbers, or hyphens + // [a-zA-Z0-9] # subdomain must end with a letter or a number + // )* # end of non-capturing group (subdomain sections are optional) + // \. # domain name must have a period + // [a-zA-Z]{2,} # domain name must have at least two letters (the domain extension) + // $/ # end of string + + const validDomainNameRegex = + /^(?!(http(s)?:\/\/|www\.))[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])*\.[a-zA-Z]{2,}$/; + + const invalid = !validDomainNameRegex.test(control.value); + + if (invalid) { + return { + invalidDomainName: { + message: errorMessage, + }, + }; + } + + return null; + }; +} diff --git a/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/validators/unique-in-array.validator.ts b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/validators/unique-in-array.validator.ts new file mode 100644 index 00000000000..4659a265959 --- /dev/null +++ b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-add-edit-dialog/validators/unique-in-array.validator.ts @@ -0,0 +1,23 @@ +import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms"; +export function uniqueInArrayValidator(values: Array, errorMessage: string): ValidatorFn { + return (control: AbstractControl): ValidationErrors | null => { + const value = control.value; + + if (!value) { + return null; + } + + const lowerTrimmedValue = value.toLowerCase().trim(); + + // check if the entered value is unique + if (values.some((val) => val.toLowerCase().trim() === lowerTrimmedValue)) { + return { + nonUniqueValue: { + message: errorMessage, + }, + }; + } + + return null; + }; +} diff --git a/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-verification.component.html b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-verification.component.html new file mode 100644 index 00000000000..94ddad3c175 --- /dev/null +++ b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-verification.component.html @@ -0,0 +1,105 @@ +
+

{{ "domainVerification" | i18n }}

+ + +
+ + + + {{ "loading" | i18n }} + + + + +
+ + + + {{ "name" | i18n }} + {{ "status" | i18n }} + {{ "lastChecked" | i18n }} + {{ "options" | i18n }} + + + + + + {{ + orgDomain.domainName + }} + + + {{ + "domainStatusUnverified" | i18n + }} + {{ + "domainStatusVerified" | i18n + }} + + + {{ orgDomain.lastCheckedDate | date: "medium" }} + + + + + + + + + + + + + +
+ +
+ + +
+ {{ "noDomains" | i18n }} +
+ +
+ + {{ "noDomainsSubText" | i18n }} + +
+ + +
+ + diff --git a/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-verification.component.ts b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-verification.component.ts new file mode 100644 index 00000000000..300e90dc21e --- /dev/null +++ b/bitwarden_license/bit-web/src/app/organizations/manage/domain-verification/domain-verification.component.ts @@ -0,0 +1,179 @@ +import { Component, OnDestroy, OnInit } from "@angular/core"; +import { ActivatedRoute, Params } from "@angular/router"; +import { concatMap, Observable, Subject, take, takeUntil } from "rxjs"; + +import { I18nService } from "@bitwarden/common/abstractions/i18n.service"; +import { OrgDomainApiServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain-api.service.abstraction"; +import { OrgDomainServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain.service.abstraction"; +import { OrganizationDomainResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain.response"; +import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service"; +import { ValidationService } from "@bitwarden/common/abstractions/validation.service"; +import { HttpStatusCode } from "@bitwarden/common/enums/http-status-code.enum"; +import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; +import { DialogService } from "@bitwarden/components"; + +import { + DomainAddEditDialogComponent, + DomainAddEditDialogData, +} from "./domain-add-edit-dialog/domain-add-edit-dialog.component"; + +@Component({ + selector: "app-org-manage-domain-verification", + templateUrl: "domain-verification.component.html", +}) +export class DomainVerificationComponent implements OnInit, OnDestroy { + private componentDestroyed$ = new Subject(); + + loading = true; + + organizationId: string; + orgDomains$: Observable; + + constructor( + private route: ActivatedRoute, + private platformUtilsService: PlatformUtilsService, + private i18nService: I18nService, + private orgDomainApiService: OrgDomainApiServiceAbstraction, + private orgDomainService: OrgDomainServiceAbstraction, + private dialogService: DialogService, + private validationService: ValidationService + ) {} + + // eslint-disable-next-line @typescript-eslint/no-empty-function + async ngOnInit() { + this.orgDomains$ = this.orgDomainService.orgDomains$; + + // Note: going to use concatMap as async subscribe blocks don't work as you expect and + // as such, ESLint rejects it + // ex: https://stackoverflow.com/a/71056380 + this.route.params + .pipe( + concatMap(async (params: Params) => { + this.organizationId = params.organizationId; + await this.load(); + }), + takeUntil(this.componentDestroyed$) + ) + .subscribe(); + } + + async load() { + await this.orgDomainApiService.getAllByOrgId(this.organizationId); + + this.loading = false; + } + + addDomain() { + const domainAddEditDialogData: DomainAddEditDialogData = { + organizationId: this.organizationId, + orgDomain: null, + existingDomainNames: this.getExistingDomainNames(), + }; + + this.dialogService.open(DomainAddEditDialogComponent, { + data: domainAddEditDialogData, + }); + } + + editDomain(orgDomain: OrganizationDomainResponse) { + const domainAddEditDialogData: DomainAddEditDialogData = { + organizationId: this.organizationId, + orgDomain: orgDomain, + existingDomainNames: this.getExistingDomainNames(), + }; + + this.dialogService.open(DomainAddEditDialogComponent, { + data: domainAddEditDialogData, + }); + } + + private getExistingDomainNames(): Array { + let existingDomainNames: string[]; + // eslint-disable-next-line rxjs-angular/prefer-takeuntil + this.orgDomains$.pipe(take(1)).subscribe((orgDomains: Array) => { + existingDomainNames = orgDomains.map((o) => o.domainName); + }); + return existingDomainNames; + } + + //#region Options + + copyDnsTxt(dnsTxt: string): void { + this.orgDomainService.copyDnsTxt(dnsTxt); + } + + async verifyDomain(orgDomainId: string, domainName: string): Promise { + try { + const orgDomain: OrganizationDomainResponse = await this.orgDomainApiService.verify( + this.organizationId, + orgDomainId + ); + + if (orgDomain.verifiedDate) { + this.platformUtilsService.showToast("success", null, this.i18nService.t("domainVerified")); + } else { + this.platformUtilsService.showToast( + "error", + null, + this.i18nService.t("domainNotVerified", domainName) + ); + // Update this item so the last checked date gets updated. + await this.updateOrgDomain(orgDomainId); + } + } catch (e) { + this.handleVerifyDomainError(e, domainName); + // Update this item so the last checked date gets updated. + await this.updateOrgDomain(orgDomainId); + } + } + + private async updateOrgDomain(orgDomainId: string) { + // Update this item so the last checked date gets updated. + await this.orgDomainApiService.getByOrgIdAndOrgDomainId(this.organizationId, orgDomainId); + } + + private handleVerifyDomainError(e: any, domainName: string): void { + if (e instanceof ErrorResponse) { + const errorResponse: ErrorResponse = e as ErrorResponse; + switch (errorResponse.statusCode) { + case HttpStatusCode.Conflict: + if (errorResponse.message.includes("The domain is not available to be claimed")) { + this.platformUtilsService.showToast( + "error", + null, + this.i18nService.t("domainNotAvailable", domainName) + ); + } + break; + + default: + this.validationService.showError(errorResponse); + break; + } + } + } + + async deleteDomain(orgDomainId: string): Promise { + const confirmed = await this.platformUtilsService.showDialog( + this.i18nService.t("removeDomainWarning"), + this.i18nService.t("removeDomain"), + this.i18nService.t("yes"), + this.i18nService.t("no"), + "warning" + ); + if (!confirmed) { + return; + } + + await this.orgDomainApiService.delete(this.organizationId, orgDomainId); + + this.platformUtilsService.showToast("success", null, this.i18nService.t("domainRemoved")); + } + + //#endregion + + ngOnDestroy(): void { + this.componentDestroyed$.next(); + this.componentDestroyed$.complete(); + } +} diff --git a/bitwarden_license/bit-web/src/app/organizations/organizations-routing.module.ts b/bitwarden_license/bit-web/src/app/organizations/organizations-routing.module.ts index 7215102e956..f3b3826bb80 100644 --- a/bitwarden_license/bit-web/src/app/organizations/organizations-routing.module.ts +++ b/bitwarden_license/bit-web/src/app/organizations/organizations-routing.module.ts @@ -10,6 +10,7 @@ import { SettingsComponent } from "@bitwarden/web-vault/app/organizations/settin import { SsoComponent } from "../auth/sso.component"; +import { DomainVerificationComponent } from "./manage/domain-verification/domain-verification.component"; import { ScimComponent } from "./manage/scim.component"; const routes: Routes = [ @@ -26,6 +27,14 @@ const routes: Routes = [ organizationPermissions: canAccessSettingsTab, }, children: [ + { + path: "domain-verification", + component: DomainVerificationComponent, + canActivate: [OrganizationPermissionsGuard], + data: { + organizationPermissions: (org: Organization) => org.canManageDomainVerification, + }, + }, { path: "sso", component: SsoComponent, diff --git a/bitwarden_license/bit-web/src/app/organizations/organizations.module.ts b/bitwarden_license/bit-web/src/app/organizations/organizations.module.ts index fd33bca0b06..09d14015a6f 100644 --- a/bitwarden_license/bit-web/src/app/organizations/organizations.module.ts +++ b/bitwarden_license/bit-web/src/app/organizations/organizations.module.ts @@ -5,11 +5,19 @@ import { SharedModule } from "@bitwarden/web-vault/app/shared/shared.module"; import { SsoComponent } from "../auth/sso.component"; import { InputCheckboxComponent } from "./components/input-checkbox.component"; +import { DomainAddEditDialogComponent } from "./manage/domain-verification/domain-add-edit-dialog/domain-add-edit-dialog.component"; +import { DomainVerificationComponent } from "./manage/domain-verification/domain-verification.component"; import { ScimComponent } from "./manage/scim.component"; import { OrganizationsRoutingModule } from "./organizations-routing.module"; @NgModule({ imports: [SharedModule, OrganizationsRoutingModule], - declarations: [InputCheckboxComponent, SsoComponent, ScimComponent], + declarations: [ + InputCheckboxComponent, + SsoComponent, + ScimComponent, + DomainVerificationComponent, + DomainAddEditDialogComponent, + ], }) export class OrganizationsModule {} diff --git a/libs/angular/src/auth/components/login.component.ts b/libs/angular/src/auth/components/login.component.ts index 17210287778..88c0a356fa8 100644 --- a/libs/angular/src/auth/components/login.component.ts +++ b/libs/angular/src/auth/components/login.component.ts @@ -221,7 +221,9 @@ export class LoginComponent extends CaptchaProtectedComponent implements OnInit "&state=" + state + "&codeChallenge=" + - codeChallenge + codeChallenge + + "&email=" + + encodeURIComponent(this.formGroup.controls.email.value) ); } diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index 12fb2c11d76..b67a3f1bf19 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -22,6 +22,11 @@ import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/abstrac import { LogService } from "@bitwarden/common/abstractions/log.service"; import { MessagingService as MessagingServiceAbstraction } from "@bitwarden/common/abstractions/messaging.service"; import { NotificationsService as NotificationsServiceAbstraction } from "@bitwarden/common/abstractions/notifications.service"; +import { OrgDomainApiServiceAbstraction } from "@bitwarden/common/abstractions/organization-domain/org-domain-api.service.abstraction"; +import { + OrgDomainServiceAbstraction, + OrgDomainInternalServiceAbstraction, +} from "@bitwarden/common/abstractions/organization-domain/org-domain.service.abstraction"; import { OrganizationUserService } from "@bitwarden/common/abstractions/organization-user/organization-user.service"; import { OrganizationApiServiceAbstraction } from "@bitwarden/common/abstractions/organization/organization-api.service.abstraction"; import { @@ -91,6 +96,8 @@ import { ExportService } from "@bitwarden/common/services/export.service"; import { FileUploadService } from "@bitwarden/common/services/fileUpload.service"; import { FormValidationErrorsService } from "@bitwarden/common/services/formValidationErrors.service"; import { NotificationsService } from "@bitwarden/common/services/notifications.service"; +import { OrgDomainApiService } from "@bitwarden/common/services/organization-domain/org-domain-api.service"; +import { OrgDomainService } from "@bitwarden/common/services/organization-domain/org-domain.service"; import { OrganizationUserServiceImplementation } from "@bitwarden/common/services/organization-user/organization-user.service.implementation"; import { OrganizationApiService } from "@bitwarden/common/services/organization/organization-api.service"; import { OrganizationService } from "@bitwarden/common/services/organization/organization.service"; @@ -610,6 +617,20 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction"; useClass: LoginService, deps: [StateServiceAbstraction], }, + { + provide: OrgDomainServiceAbstraction, + useClass: OrgDomainService, + deps: [PlatformUtilsServiceAbstraction, I18nServiceAbstraction], + }, + { + provide: OrgDomainInternalServiceAbstraction, + useExisting: OrgDomainServiceAbstraction, + }, + { + provide: OrgDomainApiServiceAbstraction, + useClass: OrgDomainApiService, + deps: [OrgDomainServiceAbstraction, ApiServiceAbstraction], + }, ], }) export class JslibServicesModule {} diff --git a/libs/common/spec/services/organization-domain/org-domain-api.service.spec.ts b/libs/common/spec/services/organization-domain/org-domain-api.service.spec.ts new file mode 100644 index 00000000000..d6299652f3d --- /dev/null +++ b/libs/common/spec/services/organization-domain/org-domain-api.service.spec.ts @@ -0,0 +1,173 @@ +import { mock, mockReset } from "jest-mock-extended"; +import { lastValueFrom } from "rxjs"; + +import { ApiService } from "@bitwarden/common/abstractions/api.service"; +import { I18nService } from "@bitwarden/common/abstractions/i18n.service"; +import { OrganizationDomainResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain.response"; +import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service"; +import { OrgDomainApiService } from "@bitwarden/common/services/organization-domain/org-domain-api.service"; +import { OrgDomainService } from "@bitwarden/common/services/organization-domain/org-domain.service"; + +const mockedGetAllByOrgIdResponse: any = { + data: [ + { + id: "ca01a674-7f2f-45f2-8245-af6d016416b7", + organizationId: "cb903acf-2361-4072-ae32-af6c014943b6", + txt: "bw=EUX6UKR8A68igAJkmodwkzMiqB00u7Iyq1QqALu6jFID", + domainName: "test.com", + creationDate: "2022-12-16T21:36:28.68Z", + nextRunDate: "2022-12-17T09:36:28.68Z", + jobRunCount: 0, + verifiedDate: null as any, + lastCheckedDate: "2022-12-16T21:36:28.7633333Z", + object: "organizationDomain", + }, + { + id: "adbd44c5-90d5-4537-97e6-af6d01644870", + organizationId: "cb903acf-2361-4072-ae32-af6c014943b6", + txt: "bw=Ql4fCfDacmcjwyAP9BPmvhSMTCz4PkEDm4uQ3fH01pD4", + domainName: "test2.com", + creationDate: "2022-12-16T21:37:10.9566667Z", + nextRunDate: "2022-12-17T09:37:10.9566667Z", + jobRunCount: 0, + verifiedDate: "totally verified", + lastCheckedDate: "2022-12-16T21:37:11.1933333Z", + object: "organizationDomain", + }, + { + id: "05cf3ab8-bcfe-4b95-92e8-af6d01680942", + organizationId: "cb903acf-2361-4072-ae32-af6c014943b6", + txt: "bw=EQNUs77BWQHbfSiyc/9nT3wCen9z2yMn/ABCz0cNKaTx", + domainName: "test3.com", + creationDate: "2022-12-16T21:50:50.96Z", + nextRunDate: "2022-12-17T09:50:50.96Z", + jobRunCount: 0, + verifiedDate: null, + lastCheckedDate: "2022-12-16T21:50:51.0933333Z", + object: "organizationDomain", + }, + ], + continuationToken: null as any, + object: "list", +}; + +const mockedOrgDomainServerResponse = { + id: "ca01a674-7f2f-45f2-8245-af6d016416b7", + organizationId: "cb903acf-2361-4072-ae32-af6c014943b6", + txt: "bw=EUX6UKR8A68igAJkmodwkzMiqB00u7Iyq1QqALu6jFID", + domainName: "test.com", + creationDate: "2022-12-16T21:36:28.68Z", + nextRunDate: "2022-12-17T09:36:28.68Z", + jobRunCount: 0, + verifiedDate: null as any, + lastCheckedDate: "2022-12-16T21:36:28.7633333Z", + object: "organizationDomain", +}; + +const mockedOrgDomainResponse = new OrganizationDomainResponse(mockedOrgDomainServerResponse); + +describe("Org Domain API Service", () => { + let orgDomainApiService: OrgDomainApiService; + + const apiService = mock(); + + let orgDomainService: OrgDomainService; + + const platformUtilService = mock(); + const i18nService = mock(); + + beforeEach(() => { + orgDomainService = new OrgDomainService(platformUtilService, i18nService); + mockReset(apiService); + + orgDomainApiService = new OrgDomainApiService(orgDomainService, apiService); + }); + + it("instantiates", () => { + expect(orgDomainApiService).not.toBeFalsy(); + }); + + it("getAllByOrgId retrieves all org domains and calls orgDomainSvc replace", () => { + apiService.send.mockResolvedValue(mockedGetAllByOrgIdResponse); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0); + + const orgDomainSvcReplaceSpy = jest.spyOn(orgDomainService, "replace"); + + orgDomainApiService + .getAllByOrgId("fakeOrgId") + .then((orgDomainResponses: Array) => { + expect(orgDomainResponses).toHaveLength(3); + + expect(orgDomainSvcReplaceSpy).toHaveBeenCalled(); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(3); + }); + }); + + it("getByOrgIdAndOrgDomainId retrieves single org domain and calls orgDomainSvc upsert", () => { + apiService.send.mockResolvedValue(mockedOrgDomainServerResponse); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0); + + const orgDomainSvcUpsertSpy = jest.spyOn(orgDomainService, "upsert"); + + orgDomainApiService + .getByOrgIdAndOrgDomainId("fakeOrgId", "fakeDomainId") + .then((orgDomain: OrganizationDomainResponse) => { + expect(orgDomain.id).toEqual(mockedOrgDomainServerResponse.id); + + expect(orgDomainSvcUpsertSpy).toHaveBeenCalled(); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(1); + }); + }); + + it("post success should call orgDomainSvc upsert", () => { + apiService.send.mockResolvedValue(mockedOrgDomainServerResponse); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0); + + const orgDomainSvcUpsertSpy = jest.spyOn(orgDomainService, "upsert"); + + orgDomainApiService + .post("fakeOrgId", mockedOrgDomainResponse) + .then((orgDomain: OrganizationDomainResponse) => { + expect(orgDomain.id).toEqual(mockedOrgDomainServerResponse.id); + + expect(orgDomainSvcUpsertSpy).toHaveBeenCalled(); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(1); + }); + }); + + it("verify success should call orgDomainSvc upsert", () => { + apiService.send.mockResolvedValue(mockedOrgDomainServerResponse); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0); + + const orgDomainSvcUpsertSpy = jest.spyOn(orgDomainService, "upsert"); + + orgDomainApiService + .verify("fakeOrgId", "fakeOrgId") + .then((orgDomain: OrganizationDomainResponse) => { + expect(orgDomain.id).toEqual(mockedOrgDomainServerResponse.id); + + expect(orgDomainSvcUpsertSpy).toHaveBeenCalled(); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(1); + }); + }); + + it("delete success should call orgDomainSvc delete", () => { + apiService.send.mockResolvedValue(true); + orgDomainService.upsert([mockedOrgDomainResponse]); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(1); + + const orgDomainSvcDeleteSpy = jest.spyOn(orgDomainService, "delete"); + + orgDomainApiService.delete("fakeOrgId", "fakeOrgId").then(() => { + expect(orgDomainSvcDeleteSpy).toHaveBeenCalled(); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0); + }); + }); + + // TODO: add Get Domain SSO method: Retrieves SSO provider information given a domain name + // when added on back end +}); diff --git a/libs/common/spec/services/organization-domain/org-domain.service.spec.ts b/libs/common/spec/services/organization-domain/org-domain.service.spec.ts new file mode 100644 index 00000000000..e4e61d4e227 --- /dev/null +++ b/libs/common/spec/services/organization-domain/org-domain.service.spec.ts @@ -0,0 +1,168 @@ +import { mock, mockReset } from "jest-mock-extended"; +import { lastValueFrom } from "rxjs"; + +import { I18nService } from "@bitwarden/common/abstractions/i18n.service"; +import { OrganizationDomainResponse } from "@bitwarden/common/abstractions/organization-domain/responses/organization-domain.response"; +import { PlatformUtilsService } from "@bitwarden/common/abstractions/platformUtils.service"; +import { OrgDomainService } from "@bitwarden/common/services/organization-domain/org-domain.service"; + +const mockedUnverifiedDomainServerResponse = { + creationDate: "2022-12-13T23:16:43.7066667Z", + domainName: "bacon.com", + id: "12eac4ea-9ed8-4dd4-85da-af6a017f9f97", + jobRunCount: 0, + lastCheckedDate: "2022-12-13T23:16:43.8033333Z", + nextRunDate: "2022-12-14T11:16:43.7066667Z", + object: "organizationDomain", + organizationId: "e4bffa5e-6602-4bc7-a83f-af55016566ef", + txt: "bw=eRBGgwJhZk0Kmpd8qPdSrrkSsTD006B+JgmMztk4XjDX", + verifiedDate: null as any, +}; + +const mockedVerifiedDomainServerResponse = { + creationDate: "2022-12-13T23:16:43.7066667Z", + domainName: "cat.com", + id: "58715f70-8650-4a42-9d4a-af6a0188151b", + jobRunCount: 0, + lastCheckedDate: "2022-12-13T23:16:43.8033333Z", + nextRunDate: "2022-12-14T11:16:43.7066667Z", + object: "organizationDomain", + organizationId: "e4bffa5e-6602-4bc7-a83f-af55016566ef", + txt: "bw=eRBGgwJhZk0Kmpd8qPdSrrkSsTD006B+JgmMztk4XjDX", + verifiedDate: "2022-12-13T23:16:43.7066667Z", +}; + +const mockedExtraDomainServerResponse = { + creationDate: "2022-12-13T23:16:43.7066667Z", + domainName: "dog.com", + id: "fac7cdb6-283e-4805-aa55-af6b016bf699", + jobRunCount: 0, + lastCheckedDate: "2022-12-13T23:16:43.8033333Z", + nextRunDate: "2022-12-14T11:16:43.7066667Z", + object: "organizationDomain", + organizationId: "e4bffa5e-6602-4bc7-a83f-af55016566ef", + txt: "bw=eRBGgwJhZk0Kmpd8qPdSrrkSsTD006B+JgmMztk4XjDX", + verifiedDate: null as any, +}; + +const mockedUnverifiedOrgDomainResponse = new OrganizationDomainResponse( + mockedUnverifiedDomainServerResponse +); +const mockedVerifiedOrgDomainResponse = new OrganizationDomainResponse( + mockedVerifiedDomainServerResponse +); + +const mockedExtraOrgDomainResponse = new OrganizationDomainResponse( + mockedExtraDomainServerResponse +); + +describe("Org Domain Service", () => { + let orgDomainService: OrgDomainService; + + const platformUtilService = mock(); + const i18nService = mock(); + + beforeEach(() => { + mockReset(platformUtilService); + mockReset(i18nService); + + orgDomainService = new OrgDomainService(platformUtilService, i18nService); + }); + + it("instantiates", () => { + expect(orgDomainService).not.toBeFalsy(); + }); + + it("orgDomains$ public observable exists and instantiates w/ empty array", () => { + expect(orgDomainService.orgDomains$).toBeDefined(); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toEqual([]); + }); + + it("replace and clear work", () => { + const newOrgDomains = [mockedUnverifiedOrgDomainResponse, mockedVerifiedOrgDomainResponse]; + + orgDomainService.replace(newOrgDomains); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toEqual(newOrgDomains); + + orgDomainService.clearCache(); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toEqual([]); + }); + + it("get successfully retrieves org domain by id", () => { + const orgDomains = [mockedUnverifiedOrgDomainResponse, mockedVerifiedOrgDomainResponse]; + orgDomainService.replace(orgDomains); + + expect(orgDomainService.get(mockedVerifiedOrgDomainResponse.id)).toEqual( + mockedVerifiedOrgDomainResponse + ); + + expect(orgDomainService.get(mockedUnverifiedOrgDomainResponse.id)).toEqual( + mockedUnverifiedOrgDomainResponse + ); + }); + + it("upsert both updates an existing org domain and adds a new one", () => { + const orgDomains = [mockedUnverifiedOrgDomainResponse, mockedVerifiedOrgDomainResponse]; + orgDomainService.replace(orgDomains); + + const changedOrgDomain = new OrganizationDomainResponse(mockedVerifiedDomainServerResponse); + changedOrgDomain.domainName = "changed domain name"; + + expect(mockedVerifiedOrgDomainResponse.domainName).not.toEqual(changedOrgDomain.domainName); + + orgDomainService.upsert([changedOrgDomain]); + + expect(orgDomainService.get(mockedVerifiedOrgDomainResponse.id).domainName).toEqual( + changedOrgDomain.domainName + ); + + const newOrgDomain = new OrganizationDomainResponse({ + creationDate: "2022-12-13T23:16:43.7066667Z", + domainName: "cat.com", + id: "magical-cat-id-number-999", + jobRunCount: 0, + lastCheckedDate: "2022-12-13T23:16:43.8033333Z", + nextRunDate: "2022-12-14T11:16:43.7066667Z", + object: "organizationDomain", + organizationId: "e4bffa5e-6602-4bc7-a83f-af55016566ef", + txt: "bw=eRBGgwJhZk0Kmpd8qPdSrrkSsTD006B+JgmMztk4XjDX", + verifiedDate: null as any, + }); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(2); + + orgDomainService.upsert([newOrgDomain]); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(3); + + expect(orgDomainService.get(newOrgDomain.id)).toEqual(newOrgDomain); + }); + + it("delete successfully removes multiple org domains", () => { + const orgDomains = [ + mockedUnverifiedOrgDomainResponse, + mockedVerifiedOrgDomainResponse, + mockedExtraOrgDomainResponse, + ]; + orgDomainService.replace(orgDomains); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(3); + + orgDomainService.delete([mockedUnverifiedOrgDomainResponse.id]); + + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(2); + expect(orgDomainService.get(mockedUnverifiedOrgDomainResponse.id)).toEqual(undefined); + + orgDomainService.delete([mockedVerifiedOrgDomainResponse.id, mockedExtraOrgDomainResponse.id]); + expect(lastValueFrom(orgDomainService.orgDomains$)).resolves.toHaveLength(0); + expect(orgDomainService.get(mockedVerifiedOrgDomainResponse.id)).toEqual(undefined); + expect(orgDomainService.get(mockedExtraOrgDomainResponse.id)).toEqual(undefined); + }); + + it("copyDnsTxt copies DNS TXT to clipboard and shows toast", () => { + orgDomainService.copyDnsTxt("fakeTxt"); + expect(jest.spyOn(platformUtilService, "copyToClipboard")).toHaveBeenCalled(); + expect(jest.spyOn(platformUtilService, "showToast")).toHaveBeenCalled(); + }); +}); diff --git a/libs/common/src/abstractions/organization-domain/org-domain-api.service.abstraction.ts b/libs/common/src/abstractions/organization-domain/org-domain-api.service.abstraction.ts new file mode 100644 index 00000000000..afb3703581d --- /dev/null +++ b/libs/common/src/abstractions/organization-domain/org-domain-api.service.abstraction.ts @@ -0,0 +1,19 @@ +import { OrganizationDomainRequest } from "../../services/organization-domain/requests/organization-domain.request"; + +import { OrganizationDomainSsoDetailsResponse } from "./responses/organization-domain-sso-details.response"; +import { OrganizationDomainResponse } from "./responses/organization-domain.response"; + +export abstract class OrgDomainApiServiceAbstraction { + getAllByOrgId: (orgId: string) => Promise>; + getByOrgIdAndOrgDomainId: ( + orgId: string, + orgDomainId: string + ) => Promise; + post: ( + orgId: string, + orgDomain: OrganizationDomainRequest + ) => Promise; + verify: (orgId: string, orgDomainId: string) => Promise; + delete: (orgId: string, orgDomainId: string) => Promise; + getClaimedOrgDomainByEmail: (email: string) => Promise; +} diff --git a/libs/common/src/abstractions/organization-domain/org-domain.service.abstraction.ts b/libs/common/src/abstractions/organization-domain/org-domain.service.abstraction.ts new file mode 100644 index 00000000000..ba8a7a2dd2d --- /dev/null +++ b/libs/common/src/abstractions/organization-domain/org-domain.service.abstraction.ts @@ -0,0 +1,20 @@ +import { Observable } from "rxjs"; + +import { OrganizationDomainResponse } from "./responses/organization-domain.response"; + +export abstract class OrgDomainServiceAbstraction { + orgDomains$: Observable; + + get: (orgDomainId: string) => OrganizationDomainResponse; + + copyDnsTxt: (dnsTxt: string) => void; +} + +// Note: this separate class is designed to hold methods that are not +// meant to be used in components (e.g., data write methods) +export abstract class OrgDomainInternalServiceAbstraction extends OrgDomainServiceAbstraction { + upsert: (orgDomains: OrganizationDomainResponse[]) => void; + replace: (orgDomains: OrganizationDomainResponse[]) => void; + clearCache: () => void; + delete: (orgDomainIds: string[]) => void; +} diff --git a/libs/common/src/abstractions/organization-domain/responses/organization-domain-sso-details.response.ts b/libs/common/src/abstractions/organization-domain/responses/organization-domain-sso-details.response.ts new file mode 100644 index 00000000000..8b2f458f72c --- /dev/null +++ b/libs/common/src/abstractions/organization-domain/responses/organization-domain-sso-details.response.ts @@ -0,0 +1,20 @@ +import { BaseResponse } from "../../../models/response/base.response"; + +export class OrganizationDomainSsoDetailsResponse extends BaseResponse { + id: string; + organizationIdentifier: string; + ssoAvailable: boolean; + domainName: string; + ssoRequired: boolean; + verifiedDate?: Date; + + constructor(response: any) { + super(response); + this.id = this.getResponseProperty("id"); + this.organizationIdentifier = this.getResponseProperty("organizationIdentifier"); + this.ssoAvailable = this.getResponseProperty("ssoAvailable"); + this.domainName = this.getResponseProperty("domainName"); + this.ssoRequired = this.getResponseProperty("ssoRequired"); + this.verifiedDate = this.getResponseProperty("verifiedDate"); + } +} diff --git a/libs/common/src/abstractions/organization-domain/responses/organization-domain.response.ts b/libs/common/src/abstractions/organization-domain/responses/organization-domain.response.ts new file mode 100644 index 00000000000..0ab7538e4e7 --- /dev/null +++ b/libs/common/src/abstractions/organization-domain/responses/organization-domain.response.ts @@ -0,0 +1,26 @@ +import { BaseResponse } from "../../../models/response/base.response"; + +export class OrganizationDomainResponse extends BaseResponse { + id: string; + organizationId: string; + txt: string; + domainName: string; + creationDate: string; + nextRunDate: string; + jobRunCount: number; + verifiedDate?: string; + lastCheckedDate?: string; + + constructor(response: any) { + super(response); + this.id = this.getResponseProperty("id"); + this.organizationId = this.getResponseProperty("organizationId"); + this.txt = this.getResponseProperty("txt"); + this.domainName = this.getResponseProperty("domainName"); + this.creationDate = this.getResponseProperty("creationDate"); + this.nextRunDate = this.getResponseProperty("nextRunDate"); + this.jobRunCount = this.getResponseProperty("jobRunCount"); + this.verifiedDate = this.getResponseProperty("verifiedDate"); + this.lastCheckedDate = this.getResponseProperty("lastCheckedDate"); + } +} diff --git a/libs/common/src/enums/deviceType.ts b/libs/common/src/enums/deviceType.ts index 707f83d84a1..d5ab33bbdd0 100644 --- a/libs/common/src/enums/deviceType.ts +++ b/libs/common/src/enums/deviceType.ts @@ -20,4 +20,6 @@ export enum DeviceType { VivaldiBrowser = 18, VivaldiExtension = 19, SafariExtension = 20, + SDK = 21, + Server = 22, } diff --git a/libs/common/src/enums/event-system-user.ts b/libs/common/src/enums/event-system-user.ts index cd9a73dd8f9..757b1d9d7b8 100644 --- a/libs/common/src/enums/event-system-user.ts +++ b/libs/common/src/enums/event-system-user.ts @@ -1,4 +1,5 @@ // Note: the enum key is used to describe the EventSystemUser in the UI. Be careful about changing it. export enum EventSystemUser { SCIM = 1, + DomainVerification = 2, } diff --git a/libs/common/src/enums/eventType.ts b/libs/common/src/enums/eventType.ts index 5d1e4785fbe..e7baa2e71d4 100644 --- a/libs/common/src/enums/eventType.ts +++ b/libs/common/src/enums/eventType.ts @@ -72,4 +72,9 @@ export enum EventType { ProviderOrganization_Added = 1901, ProviderOrganization_Removed = 1902, ProviderOrganization_VaultAccessed = 1903, + + OrganizationDomain_Added = 1904, + OrganizationDomain_Removed = 1905, + OrganizationDomain_Verified = 1906, + OrganizationDomain_NotVerified = 1907, } diff --git a/libs/common/src/enums/http-status-code.enum.ts b/libs/common/src/enums/http-status-code.enum.ts new file mode 100644 index 00000000000..602d7fde1b7 --- /dev/null +++ b/libs/common/src/enums/http-status-code.enum.ts @@ -0,0 +1,403 @@ +/** + * Hypertext Transfer Protocol (HTTP) response status codes. + * + * @see {@link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes} + * src: https://gist.github.com/RWOverdijk/6cef816cfdf5722228e01cc05fd4b094 + */ +export enum HttpStatusCode { + /** + * The server has received the request headers and the client should proceed to send the request body + * (in the case of a request for which a body needs to be sent; for example, a POST request). + * Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient. + * To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request + * and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates the request should not be continued. + */ + Continue = 100, + + /** + * The requester has asked the server to switch protocols and the server has agreed to do so. + */ + SwitchingProtocols = 101, + + /** + * A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request. + * This code indicates that the server has received and is processing the request, but no response is available yet. + * This prevents the client from timing out and assuming the request was lost. + */ + Processing = 102, + + // ********************************************************************************************************** + //#region 200s - SUCCESS + // ********************************************************************************************************** + + /** + * Standard response for successful HTTP requests. + * The actual response will depend on the request method used. + * In a GET request, the response will contain an entity corresponding to the requested resource. + * In a POST request, the response will contain an entity describing or containing the result of the action. + */ + Ok = 200, + + /** + * The request has been fulfilled, resulting in the creation of a new resource. + */ + Created = 201, + + /** + * The request has been accepted for processing, but the processing has not been completed. + * The request might or might not be eventually acted upon, and may be disallowed when processing occurs. + */ + Accepted = 202, + + /** + * SINCE HTTP/1.1 + * The server is a transforming proxy that received a 200 OK from its origin, + * but is returning a modified version of the origin's response. + */ + NonAuthoritativeInformation = 203, + + /** + * The server successfully processed the request and is not returning any content. + */ + NoContent = 204, + + /** + * The server successfully processed the request, but is not returning any content. + * Unlike a 204 response, this response requires that the requester reset the document view. + */ + ResetContent = 205, + + /** + * The server is delivering only part of the resource (byte serving) due to a range header sent by the client. + * The range header is used by HTTP clients to enable resuming of interrupted downloads, + * or split a download into multiple simultaneous streams. + */ + PartialContent = 206, + + /** + * The message body that follows is an XML message and can contain a number of separate response codes, + * depending on how many sub-requests were made. + */ + MultiStatus = 207, + + /** + * The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response, + * and are not being included again. + */ + AlreadyReported = 208, + + /** + * The server has fulfilled a request for the resource, + * and the response is a representation of the result of one or more instance-manipulations applied to the current instance. + */ + ImUsed = 226, + + // #endregion + + // ********************************************************************************************************** + //#region 300s - Redirections + // ********************************************************************************************************** + + /** + * Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation). + * For example, this code could be used to present multiple video format options, + * to list files with different filename extensions, or to suggest word-sense disambiguation. + */ + MultipleChoices = 300, + + /** + * This and all future requests should be directed to the given URI. + */ + MovedPermanently = 301, + + /** + * This is an example of industry practice contradicting the standard. + * The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect + * (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 + * with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 + * to distinguish between the two behaviours. However, some Web applications and frameworks + * use the 302 status code as if it were the 303. + */ + Found = 302, + + /** + * SINCE HTTP/1.1 + * The response to the request can be found under another URI using a GET method. + * When received in response to a POST (or PUT/DELETE), the client should presume that + * the server has received the data and should issue a redirect with a separate GET message. + */ + SeeOther = 303, + + /** + * Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match. + * In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy. + */ + NotModified = 304, + + /** + * SINCE HTTP/1.1 + * The requested resource is available only through a proxy, the address for which is provided in the response. + * Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons. + */ + UseProxy = 305, + + /** + * No longer used. Originally meant "Subsequent requests should use the specified proxy." + */ + SwitchProxy = 306, + + /** + * SINCE HTTP/1.1 + * In this case, the request should be repeated with another URI; however, future requests should still use the original URI. + * In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request. + * For example, a POST request should be repeated using another POST request. + */ + TemporaryRedirect = 307, + + /** + * The request and all future requests should be repeated using another URI. + * 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change. + * So, for example, submitting a form to a permanently redirected resource may continue smoothly. + */ + PermanentRedirect = 308, + + // #endregion + + // ********************************************************************************************************** + // #region - 400s - Client / User messed up + // ********************************************************************************************************** + + /** + * The server cannot or will not process the request due to an apparent client error + * (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing). + */ + BadRequest = 400, + + /** + * Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet + * been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the + * requested resource. See Basic access authentication and Digest access authentication. 401 semantically means + * "unauthenticated",i.e. the user does not have the necessary credentials. + */ + Unauthorized = 401, + + /** + * Reserved for future use. The original intention was that this code might be used as part of some form of digital + * cash or micro payment scheme, but that has not happened, and this code is not usually used. + * Google Developers API uses this status if a particular developer has exceeded the daily limit on requests. + */ + PaymentRequired = 402, + + /** + * The request was valid, but the server is refusing action. + * The user might not have the necessary permissions for a resource. + */ + Forbidden = 403, + + /** + * The requested resource could not be found but may be available in the future. + * Subsequent requests by the client are permissible. + */ + NotFound = 404, + + /** + * A request method is not supported for the requested resource; + * for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource. + */ + MethodNotAllowed = 405, + + /** + * The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request. + */ + NotAcceptable = 406, + + /** + * The client must first authenticate itself with the proxy. + */ + ProxyAuthenticationRequired = 407, + + /** + * The server timed out waiting for the request. + * According to HTTP specifications: + * "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time." + */ + RequestTimeout = 408, + + /** + * Indicates that the request could not be processed because of conflict in the request, + * such as an edit conflict between multiple simultaneous updates. + */ + Conflict = 409, + + /** + * Indicates that the resource requested is no longer available and will not be available again. + * This should be used when a resource has been intentionally removed and the resource should be purged. + * Upon receiving a 410 status code, the client should not request the resource in the future. + * Clients such as search engines should remove the resource from their indices. + * Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead. + */ + Gone = 410, + + /** + * The request did not specify the length of its content, which is required by the requested resource. + */ + LengthRequired = 411, + + /** + * The server does not meet one of the preconditions that the requester put on the request. + */ + PreconditionFailed = 412, + + /** + * The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large". + */ + PayloadTooLarge = 413, + + /** + * The URI provided was too long for the server to process. Often the result of too much data being encoded as a query-string of a GET request, + * in which case it should be converted to a POST request. + * Called "Request-URI Too Long" previously. + */ + UriTooLong = 414, + + /** + * The request entity has a media type which the server or resource does not support. + * For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format. + */ + UnsupportedMediaType = 415, + + /** + * The client has asked for a portion of the file (byte serving), but the server cannot supply that portion. + * For example, if the client asked for a part of the file that lies beyond the end of the file. + * Called "Requested Range Not Satisfiable" previously. + */ + RangeNotSatisfiable = 416, + + /** + * The server cannot meet the requirements of the Expect request-header field. + */ + ExpectationFailed = 417, + + /** + * This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, + * and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by + * teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including Google.com. + */ + IAmATeapot = 418, + + /** + * The request was directed at a server that is not able to produce a response (for example because a connection reuse). + */ + MisdirectedRequest = 421, + + /** + * The request was well-formed but was unable to be followed due to semantic errors. + */ + UnprocessableEntity = 422, + + /** + * The resource that is being accessed is locked. + */ + Locked = 423, + + /** + * The request failed due to failure of a previous request (e.g., a PROPPATCH). + */ + FailedDependency = 424, + + /** + * The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field. + */ + UpgradeRequired = 426, + + /** + * The origin server requires the request to be conditional. + * Intended to prevent "the 'lost update' problem, where a client + * GETs a resource's state, modifies it, and PUTs it back to the server, + * when meanwhile a third party has modified the state on the server, leading to a conflict." + */ + PreconditionRequired = 428, + + /** + * The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes. + */ + TooManyRequests = 429, + + /** + * The server is unwilling to process the request because either an individual header field, + * or all the header fields collectively, are too large. + */ + RequestHeaderFieldsTooLarge = 431, + + /** + * A server operator has received a legal demand to deny access to a resource or to a set of resources + * that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451. + */ + UnavailableForLegalReasons = 451, + + // #endregion + + // ********************************************************************************************************** + // #region - 500s - Serve messed up + // ********************************************************************************************************** + + /** + * A generic error message, given when an unexpected condition was encountered and no more specific message is suitable. + */ + InternalServerError = 500, + + /** + * The server either does not recognize the request method, or it lacks the ability to fulfill the request. + * Usually this implies future availability (e.g., a new feature of a web-service API). + */ + NotImplemented = 501, + + /** + * The server was acting as a gateway or proxy and received an invalid response from the upstream server. + */ + BadGateway = 502, + + /** + * The server is currently unavailable (because it is overloaded or down for maintenance). + * Generally, this is a temporary state. + */ + ServiceUnavailable = 503, + + /** + * The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. + */ + GatewayTimeout = 504, + + /** + * The server does not support the HTTP protocol version used in the request + */ + HttpVersionNotSupported = 505, + + /** + * Transparent content negotiation for the request results in a circular reference. + */ + VariantAlsoNegotiates = 506, + + /** + * The server is unable to store the representation needed to complete the request. + */ + InsufficientStorage = 507, + + /** + * The server detected an infinite loop while processing the request. + */ + LoopDetected = 508, + + /** + * Further extensions to the request are required for the server to fulfill it. + */ + NotExtended = 510, + + /** + * The client needs to authenticate to gain network access. + * Intended for use by intercepting proxies used to control access to the network (e.g., "captive portals" used + * to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot). + */ + NetworkAuthenticationRequired = 511, + // #endregion +} diff --git a/libs/common/src/models/domain/domain-base.ts b/libs/common/src/models/domain/domain-base.ts index f4ece329a06..4c4bffd4cd5 100644 --- a/libs/common/src/models/domain/domain-base.ts +++ b/libs/common/src/models/domain/domain-base.ts @@ -3,6 +3,7 @@ import { View } from "../view/view"; import { EncString } from "./enc-string"; import { SymmetricCryptoKey } from "./symmetric-crypto-key"; +// https://contributing.bitwarden.com/architecture/clients/data-model#domain export default class Domain { protected buildDomainModel( domain: D, diff --git a/libs/common/src/models/domain/organization.ts b/libs/common/src/models/domain/organization.ts index e4e5e746275..96b197d3ee6 100644 --- a/libs/common/src/models/domain/organization.ts +++ b/libs/common/src/models/domain/organization.ts @@ -172,6 +172,10 @@ export class Organization { return (this.isAdmin || this.permissions.manageSso) && this.useSso; } + get canManageDomainVerification() { + return (this.isAdmin || this.permissions.manageSso) && this.useSso; + } + get canManageScim() { return (this.isAdmin || this.permissions.manageScim) && this.useScim; } diff --git a/libs/common/src/models/response/event.response.ts b/libs/common/src/models/response/event.response.ts index 10897494ab7..27fc223ab6d 100644 --- a/libs/common/src/models/response/event.response.ts +++ b/libs/common/src/models/response/event.response.ts @@ -22,6 +22,7 @@ export class EventResponse extends BaseResponse { ipAddress: string; installationId: string; systemUser: EventSystemUser; + domainName: string; constructor(response: any) { super(response); @@ -42,5 +43,6 @@ export class EventResponse extends BaseResponse { this.ipAddress = this.getResponseProperty("IpAddress"); this.installationId = this.getResponseProperty("InstallationId"); this.systemUser = this.getResponseProperty("SystemUser"); + this.domainName = this.getResponseProperty("DomainName"); } } diff --git a/libs/common/src/services/organization-domain/org-domain-api.service.ts b/libs/common/src/services/organization-domain/org-domain-api.service.ts new file mode 100644 index 00000000000..62b379ac2d3 --- /dev/null +++ b/libs/common/src/services/organization-domain/org-domain-api.service.ts @@ -0,0 +1,112 @@ +import { ApiService } from "../../abstractions/api.service"; +import { OrgDomainApiServiceAbstraction } from "../../abstractions/organization-domain/org-domain-api.service.abstraction"; +import { OrgDomainInternalServiceAbstraction } from "../../abstractions/organization-domain/org-domain.service.abstraction"; +import { OrganizationDomainSsoDetailsResponse } from "../../abstractions/organization-domain/responses/organization-domain-sso-details.response"; +import { OrganizationDomainResponse } from "../../abstractions/organization-domain/responses/organization-domain.response"; +import { ListResponse } from "../../models/response/list.response"; + +import { OrganizationDomainSsoDetailsRequest } from "./requests/organization-domain-sso-details.request"; +import { OrganizationDomainRequest } from "./requests/organization-domain.request"; + +export class OrgDomainApiService implements OrgDomainApiServiceAbstraction { + constructor( + private orgDomainService: OrgDomainInternalServiceAbstraction, + private apiService: ApiService + ) {} + + async getAllByOrgId(orgId: string): Promise> { + const listResponse: ListResponse = await this.apiService.send( + "GET", + `/organizations/${orgId}/domain`, + null, + true, + true + ); + + const orgDomains = listResponse.data.map( + (resultOrgDomain: any) => new OrganizationDomainResponse(resultOrgDomain) + ); + + this.orgDomainService.replace(orgDomains); + + return orgDomains; + } + + async getByOrgIdAndOrgDomainId( + orgId: string, + orgDomainId: string + ): Promise { + const result = await this.apiService.send( + "GET", + `/organizations/${orgId}/domain/${orgDomainId}`, + null, + true, + true + ); + + const response = new OrganizationDomainResponse(result); + + this.orgDomainService.upsert([response]); + + return response; + } + + async post( + orgId: string, + orgDomainReq: OrganizationDomainRequest + ): Promise { + const result = await this.apiService.send( + "POST", + `/organizations/${orgId}/domain`, + orgDomainReq, + true, + true + ); + + const response = new OrganizationDomainResponse(result); + + this.orgDomainService.upsert([response]); + + return response; + } + + async verify(orgId: string, orgDomainId: string): Promise { + const result = await this.apiService.send( + "POST", + `/organizations/${orgId}/domain/${orgDomainId}/verify`, + null, + true, + true + ); + + const response = new OrganizationDomainResponse(result); + + this.orgDomainService.upsert([response]); + + return response; + } + + async delete(orgId: string, orgDomainId: string): Promise { + await this.apiService.send( + "DELETE", + `/organizations/${orgId}/domain/${orgDomainId}`, + null, + true, + false + ); + this.orgDomainService.delete([orgDomainId]); + } + + async getClaimedOrgDomainByEmail(email: string): Promise { + const result = await this.apiService.send( + "POST", + `/organizations/domain/sso/details`, + new OrganizationDomainSsoDetailsRequest(email), + false, // anonymous + true + ); + const response = new OrganizationDomainSsoDetailsResponse(result); + + return response; + } +} diff --git a/libs/common/src/services/organization-domain/org-domain.service.ts b/libs/common/src/services/organization-domain/org-domain.service.ts new file mode 100644 index 00000000000..617bd3698d6 --- /dev/null +++ b/libs/common/src/services/organization-domain/org-domain.service.ts @@ -0,0 +1,73 @@ +import { BehaviorSubject } from "rxjs"; + +import { I18nService } from "../../abstractions/i18n.service"; +import { OrgDomainInternalServiceAbstraction } from "../../abstractions/organization-domain/org-domain.service.abstraction"; +import { OrganizationDomainResponse } from "../../abstractions/organization-domain/responses/organization-domain.response"; +import { PlatformUtilsService } from "../../abstractions/platformUtils.service"; + +export class OrgDomainService implements OrgDomainInternalServiceAbstraction { + protected _orgDomains$: BehaviorSubject = new BehaviorSubject([]); + + orgDomains$ = this._orgDomains$.asObservable(); + + constructor( + private platformUtilsService: PlatformUtilsService, + private i18nService: I18nService + ) {} + + get(orgDomainId: string): OrganizationDomainResponse { + const orgDomains: OrganizationDomainResponse[] = this._orgDomains$.getValue(); + + return orgDomains.find((orgDomain) => orgDomain.id === orgDomainId); + } + + copyDnsTxt(dnsTxt: string): void { + this.platformUtilsService.copyToClipboard(dnsTxt); + this.platformUtilsService.showToast( + "success", + null, + this.i18nService.t("valueCopied", this.i18nService.t("dnsTxtRecord")) + ); + } + + upsert(orgDomains: OrganizationDomainResponse[]): void { + const existingOrgDomains: OrganizationDomainResponse[] = this._orgDomains$.getValue(); + + orgDomains.forEach((orgDomain: OrganizationDomainResponse) => { + // Determine if passed in orgDomain exists in existing array: + const index = existingOrgDomains.findIndex( + (existingOrgDomain) => existingOrgDomain.id === orgDomain.id + ); + if (index !== -1) { + existingOrgDomains[index] = orgDomain; + } else { + existingOrgDomains.push(orgDomain); + } + }); + + this._orgDomains$.next(existingOrgDomains); + } + + replace(orgDomains: OrganizationDomainResponse[]): void { + this._orgDomains$.next(orgDomains); + } + + clearCache(): void { + this._orgDomains$.next([]); + } + + delete(orgDomainIds: string[]): void { + const existingOrgDomains: OrganizationDomainResponse[] = this._orgDomains$.getValue(); + + orgDomainIds.forEach((orgDomainId: string) => { + const index = existingOrgDomains.findIndex( + (existingOrgDomain) => existingOrgDomain.id === orgDomainId + ); + if (index !== -1) { + existingOrgDomains.splice(index, 1); + } + }); + + this._orgDomains$.next(existingOrgDomains); + } +} diff --git a/libs/common/src/services/organization-domain/requests/organization-domain-sso-details.request.ts b/libs/common/src/services/organization-domain/requests/organization-domain-sso-details.request.ts new file mode 100644 index 00000000000..55e6ab8e833 --- /dev/null +++ b/libs/common/src/services/organization-domain/requests/organization-domain-sso-details.request.ts @@ -0,0 +1,3 @@ +export class OrganizationDomainSsoDetailsRequest { + constructor(public email: string) {} +} diff --git a/libs/common/src/services/organization-domain/requests/organization-domain.request.ts b/libs/common/src/services/organization-domain/requests/organization-domain.request.ts new file mode 100644 index 00000000000..fb515e3cbc9 --- /dev/null +++ b/libs/common/src/services/organization-domain/requests/organization-domain.request.ts @@ -0,0 +1,9 @@ +export class OrganizationDomainRequest { + txt: string; + domainName: string; + + constructor(txt: string, domainName: string) { + this.txt = txt; + this.domainName = domainName; + } +} diff --git a/libs/components/src/async-actions/bit-submit.directive.ts b/libs/components/src/async-actions/bit-submit.directive.ts index 82b459c2d56..1afaf11b907 100644 --- a/libs/components/src/async-actions/bit-submit.directive.ts +++ b/libs/components/src/async-actions/bit-submit.directive.ts @@ -20,6 +20,8 @@ export class BitSubmitDirective implements OnInit, OnDestroy { @Input("bitSubmit") protected handler: FunctionReturningAwaitable; + @Input() allowDisabledFormSubmit?: boolean = false; + readonly loading$ = this._loading$.asObservable(); readonly disabled$ = this._disabled$.asObservable(); @@ -56,9 +58,13 @@ export class BitSubmitDirective implements OnInit, OnDestroy { } ngOnInit(): void { - this.formGroupDirective.statusChanges - .pipe(takeUntil(this.destroy$)) - .subscribe((c) => this._disabled$.next(c === "DISABLED")); + this.formGroupDirective.statusChanges.pipe(takeUntil(this.destroy$)).subscribe((c) => { + if (this.allowDisabledFormSubmit) { + this._disabled$.next(false); + } else { + this._disabled$.next(c === "DISABLED"); + } + }); } get disabled() { diff --git a/libs/components/src/async-actions/form-button.directive.ts b/libs/components/src/async-actions/form-button.directive.ts index c41b24da4e2..a21dea00f78 100644 --- a/libs/components/src/async-actions/form-button.directive.ts +++ b/libs/components/src/async-actions/form-button.directive.ts @@ -17,6 +17,9 @@ import { BitSubmitDirective } from "./bit-submit.directive"; * - Disables the button while the `bitSubmit` directive is processing an async submit action. * - Disables the button while a `bitAction` directive on another button is being processed. * - Disables form submission while the `bitAction` directive is processing an async action. + * + * Note: you must use a directive that implements the ButtonLikeAbstraction (bitButton or bitIconButton for example) + * along with this one in order to avoid provider errors. */ @Directive({ selector: "button[bitFormButton]", diff --git a/libs/components/src/async-actions/in-forms.stories.mdx b/libs/components/src/async-actions/in-forms.stories.mdx index 6a07fcda6ee..07db5f4e2a0 100644 --- a/libs/components/src/async-actions/in-forms.stories.mdx +++ b/libs/components/src/async-actions/in-forms.stories.mdx @@ -105,7 +105,7 @@ class Component { ### 2. Add directive to the `form` element -The `bitSubmit` directive is required beacuse of its coordinating role inside of a form. +The `bitSubmit` directive is required because of its coordinating role inside of a form. ```html
...
@@ -121,3 +121,11 @@ Add `bitButton`, `bitFormButton`, `bitAction` directives to the button. Make sur ``` + +## `[bitSubmit]` Disabled Form Submit + +If you need your form to be able to submit even when the form is disabled, then add `[allowDisabledFormSubmit]="true"` to your `
` + +```html +...
+``` diff --git a/libs/components/src/input/input.directive.ts b/libs/components/src/input/input.directive.ts index ed7faeac829..2c4cb61eb2b 100644 --- a/libs/components/src/input/input.directive.ts +++ b/libs/components/src/input/input.directive.ts @@ -72,6 +72,8 @@ export class BitInputDirective implements BitFormFieldControl { @Input() hasPrefix = false; @Input() hasSuffix = false; + @Input() showErrorsWhenDisabled? = false; + get labelForId(): string { return this.id; } @@ -88,7 +90,15 @@ export class BitInputDirective implements BitFormFieldControl { } get hasError() { - return this.ngControl?.status === "INVALID" && this.ngControl?.touched && this.isActive; + if (this.showErrorsWhenDisabled) { + return ( + (this.ngControl?.status === "INVALID" || this.ngControl?.status === "DISABLED") && + this.ngControl?.touched && + this.ngControl?.errors != null + ); + } else { + return this.ngControl?.status === "INVALID" && this.ngControl?.touched && this.isActive; + } } get error(): [string, any] { diff --git a/libs/components/src/stories/input-docs.stories.mdx b/libs/components/src/stories/input-docs.stories.mdx new file mode 100644 index 00000000000..0ee23625ad1 --- /dev/null +++ b/libs/components/src/stories/input-docs.stories.mdx @@ -0,0 +1,48 @@ +import { Meta } from "@storybook/addon-docs"; + + + +# `bitInput` + +`bitInput` is an Angular directive to be used on ``, `