UserInfo SalesForce - salesforce

var SalesforceOAuthPlugin = {
/**
* Obtain authentication credentials, calling 'authenticate' only if necessary.
* Most index.html authors can simply use this method to obtain auth credentials
* after onDeviceReady.
* success - The success callback function to use.
* fail - The failure/error callback function to use.
* PhoneGap returns a dictionary with:
* accessToken
* refreshToken
* clientId
* userId
* orgId
* loginUrl
* instanceUrl
* userAgent
*/
getAuthCredentials: function(success, fail) {
PhoneGap.exec(success, fail, "com.salesforce.oauth","getAuthCredentials",[]);
},
SalesforceOAuthPlugin.getAuthCredentials(getUserid(), getAuthCredentialsError);
I am trying to get the id of the user using the above function, but its not working.

Use link of this format https://na1.salesforce.com/id/1/1
na1 - salesforce instance, first 1 - organizationId, next 1 - userId.
Note, that in such get you should be logged (provide OAuth token).
I think that actual userId you provide in URL, or have mapping between token and id.

Related

Laravel Orchid: How can the post entry in the database be retrieved from in the PostEditScreen.php?

Laravel Orchid: How can the post entry in the database be retrieved from in the PostEditScreen.php?
In a function in the PostEditScreen.php, how can the entry in the database that is being referred to by the PostEditScreen be accessed?
Post::find($post.id) is not working.
Any help would be greatly appreciated.
/**
* Query data.
*
* #param Post $post
*
* #return array
*/
public function query(Post $post): array
{
// This will already be a record of your model.
}
Or you can do it explicitly
/**
* Query data.
*
* #param int $id
*
* #return array
*/
public function query(int $id): array
{
Post::find($id)
}
This is stated in the laravel documentation: https://laravel.com/docs/7.x/routing#route-model-binding

javascript evaluation failed- karate

I am trying to call an API in second feature file , passing arguments from first feature file . These has to be passed as a param for second API
* def activeDetails =
"""
function(times){
for(i=0;i<=times;i++){
karate.log('Run test round: '+(i+1));
karate.call('getActiveRouteDetails.feature', { token: token, currentPage: i });
}
java.lang.Thread.sleep(1*1000);
}
"""
* call activeDetails totalPages
In my second feature , I am able to print the values passed , Getting error while passing it as a param 'no step-definition method match found for: param pageNumber'
And print currentPage
And print token
And param pageNumber = '#currentPage'
And param token = token
Watch the white space around the = sign. Normally if you use IDE support you can avoid these issues. You seem to have an extra space after pageNumber.
So make this change:
And param pageNumber = currentPage
I request you to please read the docs and examples. You are still un-necessarily making 2 calls. And over complicating your test.

Different Views for connected Users in CakePHP

I got 3 controller/tables Users / Adresses / AdressesUsers
This is my Adresses View function
/**
* View method
*
* #param string|null $id Adress id.
* #return \Cake\Network\Response|null
* #throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$this->viewBuilder()->layout('user');
$uid = $this->request->session()->read('Auth.User.id');
$adress = $this->Adresses->get($id, [
'contain' => ['Users']
]);
$counter = 0;
foreach($adress['users'] as $userid){
$users[$counter] = $userid['id'];
}
if(in_array($uid, $users)) {
$adress['dabei'] = 1;
} else {
$adress['dabei'] = 0;
}
$this->set('adress', $adress);
$this->set('_serialize', ['adress']);
}
I want all the users who are connected with the adress to see more detail information. How do I reach that goal? Tried to do it with a if clause, but didn´t work, since I get an array of more then just one user (since multiple users can connect to one adress (adress of orders - not their own).
EDIT: I used an foreach loop to find out which users are in it and use an if/else in my view. But I think this is not best practice :/

How to post to Google Docs Form directly

I'm working on a project where i need to post the data i acquire to a Google form and obtain the data from the spreadsheet. I cannot use google apps script and need a method using the direct POST method as i will be doing this function from a GSM module. All the solutions posted previously take into consideration the old structure of the Google form which provides a form key.Like the solution described in this one:
http://www.open-electronics.org/how-send-data-from-arduino-to-google-docs-spreadsheet/
The link to my current form is this.
https://docs.google.com/forms/d/14MkYG3fPNezzUC_nXUsWHlZ5JhplvjyWTAeob7f_W7g/viewform
Any help would be appreciated.
Is it a requirement that a google form be in the middle of this? If it is enough to be able to post your data to a spreadsheet, here's a Google-Apps-Script for one side of the problem: a simple web service that will accept form data as a query string, and write that to your spreadsheet.
This examples assumes a very simple spreadsheet, with three columns, "Timestamp", "col1" and "col2". Edit the code to suit your situation.
You can see the spreadsheet here, and even make a test post.
/**
* doGet() function to add data to a spreadsheet.
*
* Spreadsheet data is provided as a querystring, e.g. ?col1=1&col2='pizza'
*
* From: http://stackoverflow.com/a/18725479/1677912
*
* #param {event} e Event passed to doGet, with querystring
* #returns {String/html} Html to be served
*
* Test URLs (adjust ID as needed):
* https://script.google.com/macros/s/--DEV-SCRIPT-ID--/dev?col1=1&col2='pizza'
* https://script.google.com/macros/s/--PUB-SCRIPT-ID--/exec?col1=1&col2='pizza'
*/
function doGet(e) {
Logger.log( JSON.stringify(e) ); // view parameters
var result = 'Ok'; // assume success
if (e.parameter == undefined) {
result = 'No Parameters';
}
else {
var id = '--SHEET-ID---'; // Spreadsheet id for responses
var sheet = SpreadsheetApp.openById(id).getActiveSheet();
var newRow = sheet.getLastRow() + 1;
var rowData = [];
rowData[0] = new Date(); // Timestamp
for (var param in e.parameter) {
Logger.log('In for loop, param='+param);
var value = stripQuotes(e.parameter[param]);
//Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'col1':
rowData[1] = value;
break;
case 'col2':
rowData[2] = value;
break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
// Write new row to spreadsheet
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
// Return result of operation
return ContentService.createTextOutput(result);
}
/**
* Remove leading and trailing single or double quotes
*/
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
You can do the sending with the new forms, there is a menu option for it. (Responses->Get prefill url) It gives the url for posting data to a form.
You also asked: "obtain the data from the spreadsheet":There are two ways, google apps script and gdata style "google-spreadsheet-api". But I suggest you use a mix of google apps script and "arduino" style code, as it has better docs and features than gdata style api.
p.s. I created some formulas for creating an "arduino" user interface a while back.

Using OAuth2 with service account on gdata in python

I want to use data.photos.service.PhotosService to push and pull photos from Picasa. I got a service key file XXXXXXXX-privatekey.p12 from Google console and am now trying to authenticate using said key with google.
The documentation for OAUTH2 using appengine has led me to believe that using the following would be of use:
f = file(settings.SITE_ROOT + '/aurora/' + settings.PRIVATE_KEY, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(settings.SERVICE_ACCOUNT_NAME, key, scope = 'http://picasaweb.google.com/data https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile')
http = httplib2.Http()
http = credentials.authorize(http)
service = build("oauth2", "v2", http=http)
user_info = None
try:
user_info = service.userinfo().get().execute()
# neither of these two methods work
#gd_client.SetOAuthInputParameters(signature_method = gdata.auth.OAuthSignatureMethod.RSA_SHA1, consumer_key = "asdfasdfasdf.apps.googleusercontent.com", rsa_key = key, two_legged_oauth = True, requestor_id = user_info.get('email'))
#gd_client.auth_token = gdata.gauth.TwoLeggedOAuthRsaToken(consumer_key = user_info.get('email'), rsa_private_key = key, requestor_id = user_info.get('email'))
except errors.HttpError, e:
logging.error('An error occurred: %s', e)
user_inf0 = {u'verified_email': True, u'id': u'1234', u'name': u'asdfasdfasdf#developer.gserviceaccount.com', u'email': u'asdfasdfasdf#developer.gserviceaccount.com'}
The issue is that either method 1 using SetOAuthInputParameters returns a invalid token, or method 2 returns a 403 restricted.
I am at my wits' end reading through mountains of code that all do regular 3 legged oauth when I really and truly do not want to do it that way. Any ideas/articles I haven't seen yet?
Use gdata.gauth.OAuth2TokenFromCredentials.
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
gd_client = auth2token.authorize(gd_client)
OAuth2TokenFromCredentials is designed to help you use apiclient and gdata at the same time. Under the covers, it uses the credentials for making sure it has the auth information it needs to perform gdata calls.
Note, if you still get 403, it may be something else entirely. I was using a service account to access a user's data and was getting 403 because I hadn't spec'd the user properly in the SignedJwtAssertionCredentials call.
UPDATE: Here's the basic pattern I used:
from oauth2client.client import SignedJwtAssertionCredentials
credentials = SignedJwtAssertionCredentials(
    "XXXXXXXXXXX#developer.gserviceaccount.com",
    open("keyfile").read(),
    scope=(
    "https://www.googleapis.com/auth/drive",
    "https://spreadsheets.google.com/feeds",
    "https://docs.google.com/feeds"
), # For example.
    sub="user#gmail.com"
)
http = httplib2.Http()
http = credentials.authorize(http) # Not needed? See comment below.
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
gd_client = gdata.photos.service.PhotosService() # For example.
gd_client = auth2token.authorize(gd_client)
If you are using MFA on your google account, you need to use the consent screen authentication method. With Picassa API, it does not work as is, as the request API is slightly different.
import gdata.gauth
import os
import pickle
import gdata.photos.service
clientid='xxx' # https://console.developers.google.com/apis/credentials
clientsecret='xxx'
Scope='https://picasaweb.google.com/data/'
User_agent='myself'
def GetAuthToken():
if os.path.exists(".token"):
with open(".token") as f:
token = pickle.load(f)
else:
token = gdata.gauth.OAuth2Token(client_id=clientid,client_secret=clientsecret,scope=Scope,user_agent=User_agent)
print token.generate_authorize_url(redirect_uri='urn:ietf:wg:oauth:2.0:oob')
code = raw_input('What is the verification code? ').strip()
token.get_access_token(code)
with open(".token", 'w') as f:
pickle.dump(token, f)
return token
token = GetAuthToken()
gd_client = gdata.photos.service.PhotosService()
old_request = gd_client.request
def request(operation, url, data=None, headers=None):
headers = headers or {}
headers['Authorization'] = 'Bearer ' + token.access_token
return old_request(operation, url, data=data, headers=headers)
gd_client.request = request
photos = gd_client.GetUserFeed(kind='photo', limit='10')
for photo in photos.entry:
print 'Recently added photo title:', photo.title.text

Resources