How to email SalesForce users temporary password by using API? - api

I am using SOAP Partner API and I have a Developer edition. I am creating users by using API. And upon creation of users I want to email these users temporary password which they can use to login to SalesForce.
This is my code:
SaveResult[] results = connection.create(new SObject[] { user });
if (results[0].isSuccess())
{
out.println("Created user: " + results[0].getId());
//connection.setPassword(results[0].getId(), "password");
ResetPasswordResult rpr = connection.resetPassword(results[0].getId());
String result = rpr.getPassword();
System.out.println("The temporary password for user ID " + results[0].getId()
+ " is " + result);
}
else
{
out.println("Error: " + results[0].getErrors()[0].getStatusCode() +
":" + results[0].getErrors()[0].getMessage());
}
This is the output I am getting in console:
The temporary password for user ID 005E0000000MwkZIAS is ucQD2PADs
However, the user is NOT receiving any password. :-(
Thanks,
Wap Rau

If you build & pass an EmailHeader in your soap request you can control what types of emails will get sent from your request.
It looks like you're using WSC, so you can add this call before calling resetPassword, which will enabled emails being sent to users. This should then send the standard reset password email.
connection.setEmailHeader(false, false, true);

use this class to send out an email. include the pwd variable in the string you want to send the user. there's an example that spells everything out
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound.htm

Related

jira api - how to update fields on a jira issue that is closed/published

the following code works fine on a jira issue that is in open. but when this is tried on a closed/published issue i get error. wanted to see if this is even possible to be done? manually on closed/published jira issue, we can update those fields
Client client = Client.create();
WebResource webResource = client.resource("https://jira.com/rest/api/latest/issue/JIRA_KEY1");
String data1 = "{\r\n" +
" \"fields\" : {\r\n" +
" \"customfield_10201\" : \"Value 1\"\r\n" +
" }\r\n" +
"}";
String auth = new String(Base64.encode("user" + ":" + "pass"));
ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json").accept("application/json").put(ClientResponse.class, data1);
Error received
Http Error : 400{"errorMessages":[],"errors":{"customfield_10201":"Field 'customfield_10201' cannot be set. It is not on the appropriate screen, or unknown."}}
There is probably a restriction that doesn't allow the value of that field to be changed once the issue is marked as complete.
Try opening that completed issue via the web interface and changing the field's value; if you can't do it via the web interface, then you can't do it the REST API.

The service is not available received when calling MS Graph API

We are doing a MS Graph API call to get the Sharepoint URL of a Team.
API URL: GET https://graph.microsoft.com/v1.0/groups/{GroupID}/sites/root/weburl
We get this :
Response:
{
"error": {
"code": "serviceNotAvailable",
"message": "The service is not available. Try the request again after a delay. There may be a Retry-After header.",
"innerError": {
"request-id": "9f23d067-e851-4c43-8701-abe137683b87",
"date": "2020-03-05T13:53:43"
}
}
}
What could be the issue?
I have been experiencing a similar problem in searching sites ( GET /sites?search=* ) with the Graph API since March 2nd. I have not been able to recover. I have experienced this over multiple O365 tenants, both free and licensed.
Microsoft docs say this error code is due to MSFT induced throttling, but my request rate is like 50 per hour.
This seems to be a Microsoft bug. I posted a stack overflow issue for this and #rafa-ayadi reported that MSFT was fixing it their side for one of his customers.
I bought an Azure Developer Support subscription for this issue, but MSFT closed it and referred me to Sharepoint Developer Support, for which I can find no link or pricing. So no luck yet in getting MSFT to acknowledge and fix for me.
/**
You need do authentication delegated. See the follow code:
First of all you need from portal.azure.com register app and get:
folder id it is tenantID
App Id. it is clientId
**/
URL urlObj = new
URL("https://login.microsoftonline.com/"+config.tenantID+"/oauth2/v2.0/token");
HttpURLConnection httpCon = (HttpURLConnection) urlObj.openConnection();
String urlParameters = "" + // para la v2.0
"grant_type"+"="+"password"+"&"+ /
"scope" + "=" + "https%3A%2F%2Fgraph.microsoft.com%2F.default" +"&" +
"client_id" + "=" + config.clientId +"&" +
"client_secret" + "=" + config.clientSecret +"&" +
"username" + "=" + config.username +"&" +
"password" + "=" + config.contrasena +"&";
byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpCon.setRequestProperty("Content-Length",String.valueOf(postDataLength));
httpCon.setRequestMethod("POST");
httpCon.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(httpCon.getOutputStream());
writer.write(urlParameters);
writer.flush();
int status = httpCon.getResponseCode();
BufferedReader in = new BufferedReader(new
InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
String body = getBody(content.toString());
String token = null;
final ObjectNode node = new ObjectMapper().readValue(body, ObjectNode.class);
if (node.has("access_token")) {
token = node.get("access_token").asText();
}
httpCon.disconnect();
return token;
My similar problem accessing any resource in the sites API was caused by having both the Groups.Create and Groups.ReadWrite.All permissions granted at the same time for application type access.
Removing Groups.Create allowed the all CRUD calls to be successful without serviceNotAvailable errors, even command line calls that just access sites.
Be sure to update admin grant and your token if you change the permissions for a test.
User #user13034886 mentioned the permission clash in another post.

How to modify admin password on vtiger?

I have to modify the password of an account on a vtiger crm. The problem is that I don't know the location of the database.
Anyone know the path of the database containing the credential of the users?
If your username starts with 'ad' like 'admin'. use the following mysql query
UPDATE vtiger_users SET user_password = '$1$ad000000$mnnPAFfqzJOuoYY7aB.mR0' WHERE user_name='admin';
This query will reset the password for user with admin username. The password will be set to password.
Vtiger use encrypt_password function in Users.php on line 264 to encrypt user password.
modules/Users/Users.php
It use crypt_type and username for encrypt new passwords. so Mysql query only work if your username starts with ad for example 'admin' , 'adam' and etc.
function encrypt_password($user_password, $crypt_type='') {
// encrypt the password.
$salt = substr($this->column_fields["user_name"], 0, 2);
// Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/4923
if($crypt_type == '') {
// Try to get the crypt_type which is in database for the user
$crypt_type = $this->get_user_crypt_type();
}
// For more details on salt format look at: http://in.php.net/crypt
if($crypt_type == 'MD5') {
$salt = '$1$' . $salt . '$';
} elseif($crypt_type == 'BLOWFISH') {
$salt = '$2$' . $salt . '$';
} elseif($crypt_type == 'PHP5.3MD5') {
//only change salt for php 5.3 or higher version for backward
//compactibility.
//crypt API is lot stricter in taking the value for salt.
$salt = '$1$' . str_pad($salt, 9, '0');
}
$encrypted_password = crypt($user_password, $salt);
return $encrypted_password;
}
You can use the following tools on Github. it can change all users password without login into crm and phpmyadmin and update vtiger user privileges file.
https://github.com/spadana2004/Vtiger-CRM-Reset-Password-Tools
Go to My preferences(right top of the browser). There you can change the password of the user.
In database you can't change bcoz there it will be converted to MD5. Then also for your kind information in database check the table vtiger_users for user detail.
update vtiger_users set user_password = 'adpexzg3FUZAk', crypt_type = '' where id = '1';
Login: admin
Password:admin
To make this really easy for admins I created a simple gist that will generate the sql query you need to run to reset a password with any username. Just put in the username and temp password, then run the script and use the SQL it provides. After that just login with that username and password. It is tested with and working on VTiger 7.2.
https://gist.github.com/mav2287/59d5587c7efabdbb105b739c4bc27cb5
<?php
// Put in your username as found in the "vtiger_users" table under the "username" column
$user_name = "";
// Set your TEMPORARY password. You NEED to reset your password after using this to reset it.
$user_password = "password";
// return the approiate stamtent
echo "Run the following SQL query to reset your password: \n";
echo "\"UPDATE vtiger_users SET user_password='".crypt($user_password, substr($user_name, 0, 2))."',crypt_type=''WHERE user_name='".$user_name."'\"";

Retrieving email-id from database and send mail to them

In yii i am creating sendemail functionality. I am using mailer extension and its working correctly after making all settings of SMTP. i had made method actionEmail in controller as-
public function actionEmail()
{
$model=new User;
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Host = "smtp.gmail.com";
$mailer->Port = 465;
$mailer->CharSet = 'UTF-8';
$mailer->Username = "abc#gmail.com";
$mailer->Password = "abc";
$mailer->From = "xyz#gmail.com";
$mailer->FromName = "Balaee.com";
$mailer->AddAddress('shilpa.kirad#shailani.com');
$mailer->Subject = "welcome to Balaee";
$mailer->IsHTML(true);
// $html = $this->renderPartial('myview',array('content'=>'Hello World'),true);
$mailer->Body = "Welcomeclick on link for other detail ".$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($mailer->Send()) {
echo "Please check mail";
//Yii::app()->user->setFlash('register','Thank you for contacting us. We will respond to you as soon as possible.');
// $this->refresh();
}
else {
echo "Fail to send your message!";
}
}
This method is implementing correctly.It is sending mail to address which is mentioned in mailer->AddAdress.But now i want to retrive email id's from database corresponding to specific user's id and send mail to him. i.e.I dont want to insert hard coded value for this field. So how can i do this. Please help me.
for fetch use id of user to get email address as
$user_model=User::model()->findByPk($id);
and set in email as
$mailer->AddAddress($user_model->email_id);
where id and email_id are the table column name.
check other ways .
http://www.yiiframework.com/doc/guide/1.1/en/database.dao
For this to be done, you can fetch email id from database using following query:
$email = SELECT email FROM USER WHERE user_id = "X";
Here X is user_id of user whom you want to send email.
And provide this $email in the receipient's email field. Thanks.

Error creating SalesForce users LICENSE_LIMIT_EXCEEDED:License Limit Exceeded

I want to create 5-6 SalesForce users programmatically in one go by using SOAP API. I am using Partner API and I have a Developer edition sandbox. I am retrieving users information from a database table and then by using API I want to create these 5-6 users at once. I can create one user however after creating another user it is throwing error LICENSE_LIMIT_EXCEEDED:License Limit Exceeded.
This is snapshot of my code which retrieves users information from database and then creates a user programmatically:
SObject user = new SObject();
user.setType("User");
while (rs.next()) {
user.setField("Alias", rs.getString("Alias"));
user.setField("Email", rs.getString("Email"));
user.setField("EmailEncodingKey", rs.getString("EmailEncodingKey"));
user.setField("LanguageLocaleKey", "En_US");
user.setField("LastName", rs.getString("LastName"));
user.setField("LocaleSidKey", rs.getString("LocaleSidKey"));
user.setField("TimeZoneSidKey", "America/Los_Angeles");
user.setField("Username", rs.getString("Username"));
user.setField("UserPermissionsCallCenterAutoLogin", "false");
user.setField("UserPermissionsMarketingUser", "false");
user.setField("UserPermissionsOfflineUser", "false");
user.setField("ProfileId", connection.getUserInfo().getProfileId());
SaveResult[] results = connection.create(new SObject[] { user });
System.out.println("Created user: " + results[0].getId());
if (results[0].isSuccess())
out.println("Created user: " + results[0].getId());
else
out.println("Error: " + results[0].getErrors()[0].getStatusCode() +
":" + results[0].getErrors()[0].getMessage());
}
QueryResult queryResults = connection
.query("SELECT Id, Name from User "
+ "ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (SObject s : queryResults.getRecords()) {
out.println("Id: " + s.getField("Id") + " - Name: "
+ s.getField("Name"));
}
}
Here I can create one user however after creating one user it is throwing error LICENSE_LIMIT_EXCEEDED:License Limit Exceeded.
These are the number of licenses available:
I can see that licenses remaining for SalesForce is 0. However, I just want to create some users that don't necessarily have to be SalesForce users. It can be any type of users which just should be able to login to my org. When I am trying to create some different type of users such as 'Chatter Free' which has 5000 licences by using user.setField("UserType", "CsnOnly") it is giving error INVALID_FIELD_FOR_INSERT_UPDATE:Unable to create/update fields: UserType
These are users in my SalesForce:
How to solve this problem? I just want to create some users from database which can then login to SalesForce. Its not necessary that they should be administrators. They can have minimum privileges but they should be able to login to SalesForce.
In a developer org, you won't be able to have more than two active users with Salesforce licenses. In order to create a user with a Chatter Free license, you should only need to assign them the profile of Chatter Free User - it will automatically set their license correctly based on the profile assigned to them (the UserType field is not editable).
Edit: to obtain the Chatter Free User's profile Id without hardcoding it (as it may change from org to org), you'll have to query it. I modified your code to include this query, as well as reworked it so that only a single callout to PartnerConnection.create is made (just a suggestion, as it will save overhead on your SOAP callouts):
QueryResult profileQuery = connection.query("select Id from Profile where Name = 'Chatter Free User' limit 1");
SObject chatterFreeProfile;
if ( profileQuery.getSize() > 0 ) {
chatterFreeProfile = profileQuery.getRecords()[0];
}
ArrayList<SObject> users = new ArrayList<SObject>();
while (rs.next()) {
SObject user = new SObject();
user.setType("User");
user.setField("Alias", rs.getString("Alias"));
user.setField("Email", rs.getString("Email"));
user.setField("EmailEncodingKey", rs.getString("EmailEncodingKey"));
user.setField("LanguageLocaleKey", "En_US");
user.setField("LastName", rs.getString("LastName"));
user.setField("LocaleSidKey", rs.getString("LocaleSidKey"));
user.setField("TimeZoneSidKey", "America/Los_Angeles");
user.setField("Username", rs.getString("Username"));
user.setField("UserPermissionsCallCenterAutoLogin", "false");
user.setField("UserPermissionsMarketingUser", "false");
user.setField("UserPermissionsOfflineUser", "false");
if ( chatterFreeProfile != null )
user.setField("ProfileId", chatterFreeProfile.getField("Id"));
else
user.setField("ProfileId", connection.getUserInfo().getProfileId());
users.add(user);
}
if ( users.size() > 0 ) {
SaveResult[] results = connection.create(users.toArray(new SObject[users.size()]));
for ( int i = 0; i < saveResults.length; i++ ) {
if (results[i].isSuccess())
out.println("Created user: " + results[i].getId());
else
out.println("Error: " + results[i].getErrors()[0].getStatusCode() + ":" + results[i].getErrors()[0].getMessage());
}
}
QueryResult queryResults = connection.query("SELECT Id, Name from User ORDER BY CreatedDate DESC LIMIT 5");
if ( queryResults.getSize() > 0 ) {
for ( SObject s : queryResults.getRecords() ) {
out.println("Id: " + s.getField("Id") + " - Name: " + s.getField("Name"));
}
}
You need to set ProfileId to a Profile associated with an available License Type, in your case to a Profile on the Chatter Free, Salesforce Platform, or one of your other available license types. Each Profile is tied to a particular UserLicense record, for example:
'SFDC' : Full Salesforce license
'CSN_User' : Chatter Free license
'AUL' : Salesforce Platform license
(To see more, do a Query All on the UserLicense object).
So you'll need to query for Profile records on available license types, and then associate this to your new users, e.g.
QueryResult profileQuery = connection.query(
"SELECT Id FROM Profile "
+ "WHERE UserLicense.Name = 'Chatter Free' LIMIT 1"
);
SObject chatterFreeProfile;
if ( profileQuery.getSize() > 0 ) {
chatterFreeProfile = profileQuery.getRecords()[0];
user.setField("ProfileId", chatterFreeProfile.getField("Id"));
}