0

I have a LWC component that takes a users first, last names and title and then saves it in the Order record when you click the submit button. It is working as expected. The only problem is I am not sure how to make this form secure. In other words, a user could put special characters or have it a 100 letters, or do XSS attack. How do I ensure that the user input is safe in front end and apex? Here is my code:

LWC:

<div class="slds-grid slds-gutters ">
                <div class="slds-col slds-var-p-vertical_medium">
                    <div class="slds-form-element">
                        <label class="slds-form-element__label" for="text-input-id-46">
                            <abbr class="slds-required" title="required">* </abbr>First Name
                        </label>
                        <div class="slds-form-element__control">
                            <input type="text" placeholder="Enter First Name" required="" class="slds-input"
                                onchange={firstNameChange} value={firstName} />
                        </div>
                    </div>
                </div>

                <div class="slds-col slds-var-p-vertical_medium">
                    <div class="slds-form-element">
                        <label class="slds-form-element__label" for="text-input-id-46">
                            <abbr class="slds-required" title="required">* </abbr>Last Name
                        </label>
                        <div class="slds-form-element__control">
                            <input type="text" placeholder="Enter Last Name" required="" class="slds-input"
                                onchange={lastNameChange} value={lastName} />

                        </div>
                    </div>
                </div>
            </div>

            <div class="slds-form-element">
                <lightning-combobox name="Title" label="Title" value={title} placeholder="Select Title"
                    options={TitleOptions} onchange={titleChange}>
                </lightning-combobox>
            </div>
<div class="footer slds-text-align_center slds-p-bottom_medium slds-p-top_medium slds-m-top_x-large">
                <div class="slds-grid slds-gutters slds-grid_align-center">
                    <div class="slds-col app-grow_large">
                        <button class="slds-button slds-button_brand app-btn_large" onclick={confirmPlaceOrder}>Place Order</button>
                    </div>

JS:

firstNameChange(event) {
    this.firstName = event.target.value;
  }

  lastNameChange(event) {
    this.lastName = event.target.value;
  }

  titleChange(event) {
    //this.title = event.target.value;
    this.title = event.detail.value;
  }

  confirmPlaceOrder() {
    if (this.firstName == "" || this.lastName == "" || this.title == "") {
      const evt = new ShowToastEvent({
        title: "Error",
        message: "Please fill First name, Last name and Title",
        variant: "Error",
      });
      this.dispatchEvent(evt);
    } else {
      createOrder({
        firstName: this.firstName,
        lastName: this.lastName,
        title: this.title,
        
        
      })
        .then((result) => {
          this.resultValue = result;
          console.log(
            ":::this.resultValueOrder in create order::: " + this.resultValue
          );
          this.error = undefined;

          if (this.resultValue != "Error" || this.resultValue != null) {
            //just changed this
            const evt = new ShowToastEvent({
              title: "",
              message: "Order Successfully Done",
              variant: "success",
              mode: "dismissable",
            });
            this.dispatchEvent(evt);
            
            
          }

          if (this.resultValue == "Error") {
            const evt = new ShowToastEvent({
              title: "Error",
              message: "Please fill First name, Last name and Title",
              variant: "Error",
            });
            this.dispatchEvent(evt);
          }
        })
        .catch((error) => {
          this.error = error;
          console.log(":::Error::: " + this.error);

          const evt = new ShowToastEvent({
            title: "Error",
            message: this.error,
            variant: "Error",
          });
          this.dispatchEvent(evt);
        });
    }
  }

APEX:

@AuraEnabled
    global static String createOrder(String firstName, String lastName, String title, String accId, Decimal qty){
        
        if(firstName != '' && lastName != '' && title != ''){
            List<Order> ordList = new List<Order>();
            Id OrderrecordTypeId = Schema.SObjectType.Order.getRecordTypeInfosByName()
                  .get('Virtual Selling Order').getRecordTypeId();
            
            
            Order ord = new Order();
            
            ord.Type = 'Regular';
            ord.First_Name__c = firstName;
            ord.Last_Name__c = lastName;
            ord.Title__c = title;
            
            ordList.add(ord);
            SObjectAccessDecision decision = Security.stripInaccessible(AccessType.CREATABLE, ordList);
            insert decision.getRecords();
return decision.getRecords()[0].Id;
            
            
        }else {
            return 'Error';
        }
    }

Can someone please help me get started? Would there be changes to JS and apex? I am assuming the inputs would need to be checked in apex and js side?

Thank you

1 Answer 1

1

XSS isn't possible in LWC. Locker Service/Lightning Web Security ensures this.

To simplify your code, I strongly recommend that you use lightning-input instead of the verbose code you have now. This makes your validation easier, as outlined in the documentation:

handleClick(evt) {
    console.log('Current value of the input: ' + evt.target.value);

    const allValid = [
        ...this.template.querySelectorAll('lightning-input'),
    ].reduce((validSoFar, inputCmp) => {
        inputCmp.reportValidity();
        return validSoFar && inputCmp.checkValidity();
    }, true);
    if (allValid) {
        alert('All form entries look valid. Ready to submit!');
    } else {
        alert('Please update the invalid form entries and try again.');
    }
}

You can set maximum length, requiredness, etc, and it's all automated for you in a few lines of code.

As far as your Apex code, even though XSS isn't a major concern, you could use stripHtmlTags() or escapeHtml4() if you want to remove/encode HTML.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .