3
\$\begingroup\$

I am trying to search account table by providing a search string. I am building a query based in different conditions and then adding the returned records in a list.

The functionality is working correctly but I want to know how an below method be further optimized.

 public PageReference search(){ clear(); runningUserId = Userinfo.getUserId(); String searchquery; Boolean existUser = AccSearchAccess__c.getValues(runningUserId) !=null? true : false; if(existUser){ searchquery='Select Name,Id,AccessLevel__c FROM Account where Name like \'%'+accountName+'%\''; } else{ set<id> accountIds = new set<id>(); List<WMAccess__c> wmaLst = [Select id,Account__c from WMAccess__c where WM_User__c = : UserInfo.getUserId()]; for(WMAccess__c wm : wmaLst){ accountIds.add(wm.Account__c); } if(!accountIds.isEmpty()){ searchquery='Select Name,Id,AccessLevel__c FROM Account where Name like \'%'+accountName+'%\' AND id IN:accountIds'; } } accList= Database.query(searchquery); if(accList.size()>0) for(Account acc : accList){ AccountWrapper aw = new AccountWrapper(acc, false); aw.accountId = acc.id; aw.accountName = acc.Name; aw.accountAccess = acc.AccessLevel__c; accountsList.add(aw); } return null; } 
\$\endgroup\$
3
  • \$\begingroup\$ Avoid building raw SQL Strings. use a PreparedStatement \$\endgroup\$ Commented Jul 25, 2016 at 10:58
  • \$\begingroup\$ @CrazyNinja - I further cleaned my code, but i didn't get what do you mean by PreparedStatement Could you please post a sample? \$\endgroup\$ Commented Jul 25, 2016 at 12:01
  • \$\begingroup\$ mkyong.com/jdbc/… \$\endgroup\$ Commented Jul 25, 2016 at 12:04

1 Answer 1

1
\$\begingroup\$

You have exposed an injection vulnerability.

'WHERE Name like \'%'+accountName+'%\'' 

Any time you merge user input into your query, you should call String.escapeSingleQuotes, or better yet, use a dynamic binding.

// OK searchQuery += 'WHERE Name LIKE \'%' + String.escapeSingleQuotes(accountName) + '%\''; // BETTER String fuzzySearchTerm = '%' + accountName + '%'; searchQuery += 'WHERE Name LIKE :fuzzySearchTerm'; 
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.