We are trying to create community users and contacts for our accounts through an apex class. In this class we use System.setPassword to set the password of the newly created users. We get no errors or exceptions when anonymously executing this class.
However, when we try to login this user using its credentials set in the program, the login fails. The login history of the user says Status = 'Invalid Password'.
Id profId = [SELECT Id FROM Profile WHERE Name = 'Community User' LIMIT 1].Id;
Account a = new Account(Name = 'testacccount');
insert a;
Contact c = new Contact(AccountId = a.Id,
FirstName = 'testfirst',
LastName = 'testlast',
Email = '[email protected]');
insert c;
User u = new User(ContactId = c.Id,
Alias = 'MSstA5',
FirstName = c.FirstName,
LastName = c.LastName,
Email = c.Email,
Username = c.Email,
ProfileId = profId,
EmailEncodingKey = 'ISO-8859-1',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'America/New_York');
insert u;
string passwordstring = 'qwer1234';
try {
System.setPassword(portalUser.id, passwordstring);
}
catch(Exception ex){
System.debug('User Passwpord EXC:' + ex.getMessage());
}
And another interesting thing is that if we set the password by directly executing the same code (mentioned below) in the anonymous execution window, the password is correctly set and user is able to login.
ID userid = '0050Q0000025BvSQAU';
string passwordstring = 'qwer1234';
try {
System.setPassword(userid, passwordstring);
}
catch(Exception ex){
System.debug('User Passwpord EXC:' + ex.getMessage());
}
So the ultimate problem is that I am unable to set the password for the user in the APEX class and login the user using the same password.
- I also waited for like 24 hours and then tried logging in but it did not work.
- I tried hard coding the password and then through a variable(like in the above code) as well.
- The following questions are also similar to my problem, System.SetPassword During User Creation Sets Password But User Cannot Login?, Issue creating user and setting password
Please help out in any way possible, thank you!