[SalesForce] Get Current User when using forcetk.js / JqueryMobile pack

Im currently having a play with the Salesforce JqueryMobile pack and have got stuck trying to get hold of the current user Id. (Pack: http://www2.developerforce.com/mobile/getting-started/html5/#jquery-heroku)

I should point out this is hosted externally to salesforce and using OAuth to connect.

The forcetk object contains a session_id that contains the main account id of the dev org I'm using but no details on who I am.

Its probably right in front of me but would appreciate any help / source code you guys have!

Best Answer

The way you can get userId, is via IdentityURL coming in the Oauth access/refresh token response.

Here is the sample JSON response:

{"id":"https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P",
"issued_at":"1278448101416","refresh_token":"5Aep8614iLM.Dq661ePDmPEgaAW9
Oh_L3JKkDpB4xReb54_pZebnUG0h6Sb4KUVDpNtWEofWM39yg==","instance_url":
"https://na1.salesforce.com","signature":"CMJ4l+CCaPQiKjoOEwEig9H4wqhpuLSk
4J2urAe+fVg=","access_token":"00Dx0000000BV7z!AR8AQP0jITN80ESEsj5EbaZTFG0R
NBaT1cyWk7TrqoDjoNIWQ2ME_sTZzBjfmOE6zMHq6y8PIW4eWze9JksNEkWUl.Cju7m4"}

If you notice the url for "id" key, its the identity url, and you can parse it to get both userId and orgId(if required). UserId is the one with prefix "005" i.e. 005x00000012Q9P

This is standard approach to save a webservice call to get userId, its used in salesforce mobile sdk as well, so you can be assured of the solution.

Now you need to figure out the place where your oauth flow, most probably you must be doing something like this

function onSalesforceOAuthLogin(event) {
logToConsole("onSalesforceOAuthLogin: Salesforce ready");
forcetkClient = new forcetk.Client(event.data.clientId, event.data.loginUrl);
forcetkClient.setSessionToken(event.data.accessToken, event.data.apiVersion, event.data.instanceUrl);
forcetkClient.setRefreshToken(event.data.refreshToken);
}

Add an extra method called setIdentityUrl() in forcetk.js, inspire from setRefreshToken, and parse the "id" param data in it.

I will try the same soon, but in next 1-2 days.

Related Topic