function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rajesh ShahRajesh Shah 

Login as another User in Apex Class

Hi,
 
In our S-Control, due a particular reason, we first login using another User.
The following is the code to do so
/*****************************************
var usrPwd = null;
  var usrName = null;
  var currentUrl = sforce.connection.serverUrl;
  var results = sforce.connection.query("Select Password__c,Username__c from Administrator__c");
  records = results.getArray("records");
  if (records.length > 0)
  {
   admName = records[0].get("Username__c");
   admPwd = records[0].get("Password__c");
  } 
    sforce.connection = new sforce.Connection();
  try
  {
   var loginResult = sforce.connection.login(usrName, usrPwd);
  }
  catch (error)
  {
   alert("Failed to Authenticate Administrator, + error);
   self.close();
  }
  sforce.connection.serverUrl = currentUrl;
*****************************************/ 
 
Now I need to migrate the same code to an Apex Class. I can query in an Apex Class but can I login as another User in apex Class in the same way as I am currently doing in S-Control code.
Thanks.
 
Regards,
Rajesh
Best Answer chosen by Admin (Salesforce Developers) 
Drew1815Drew1815
Since Apex code runs as System Admin, I am not sure you will need to login as another user. Are you logging in as another user to apply the proper sharing rules and data visibility? If so, you will want to use the "with sharing" keyword when defining the apex class that applies your logic. You can find the online documentation here:
http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_classes_keywords_sharing.htm

I hope that helps.