How do I properly return as JSON-ified version of Parse object? - objective-c

I'm hitting a custom function on my server, getting a PFObject in my Convos objects and returning that object from JS, which results in this string in my Objective-C code:
"<convos: 0x6080002ae220, objectId: e1VYAIFCyQ, localId: (null)> {
\n buyerDeleted = NO;\n buyerId = NNfjWZrk8r;\n buyerPicture = \"<PFFile: 0x60800065de80>\";\n buyerSentMessage = YES;\n buyerSentTwoMessages = YES;\n buyerUnseen = 0;\n buyerUser = \"<PFUser: 0x6080002f1900, objectId: NNfjWZrk8r, localId: (null)>\";\n buyerUsername = corby;\n convoId = bQLQWNEtwmNNfjWZrk8r;\n lastSent = \"<messages: 0x60c0000b8600, objectId: iYVIjJ6A3q, localId: (null)>\";\n lastSentDate = \"2018-06-05 19:09:52 +0000\";\n profileConvo = YES;\n sellerDeleted = NO;\n sellerId = bQLQWNEtwm;\n sellerSentMessage = YES;\n sellerUnseen = 0;\n sellerUser = \"<PFUser: 0x6080002f1a80, objectId: bQLQWNEtwm, localId: (null)>\";\n sellerUsername = tough;\n source = profile;\n totalMessages = 3;\n
}"
I'm trying to take the convo object in my JS and run convo.toJSON() on it (which seems like the solution) and then return it but that seems to take an extremely long time.
Any tips on how to return that Parse object so that I can ultimately turn it into an NSDictionary and then a PFObject in the client?

I think we got you covered in slack, but for anyone else who finds this:
Don't use toJSON() from your server, just return the Parse.Object
In your Obj-C code, add this line to the success block of your call back:
PFObject *resultParseObject = (PFObject*)object, where object is the _Nullable id object parameter to the callback of your cloud function.

Related

How to verify PKCS#7 signature in PHP

I have a digital signature (encrypted format PKCS#7) needs to be verified So I have tried by using different PHP core methods(openssl_verify, openssl_pkcs7_verify and even tried by external library such as phpseclib But nothing worked :(
I get a signature along with some extra params through by this link..
http://URL?sign={'param':{'Id':'XXXXXXX','lang':'EN','Rc':'00','Email': 'test#yahoo.com'’},'signature':'DFERVgYJKoZIhvcNAQcCoIIFRzCCBUMCAQExCzAJBgUrDg
MCGgUAMIGCBgkqhkiG9w0BBwGgdQRzeyJEYXRlIjoidG9fY2hhcihzeXNkYXRlJ0RETU1ZWVlZJykgIiwiSWQiOiJ
VMDExODg3NyIsIklkaW9tYSI6IkNBUyIsIk51bUVtcCI6IlUwM23D4DEE3dSi...'}
PHP code - returns always 0(false) instead of 1(true).
$JSONDATA = str_replace("'", '"', #$_GET["sign"]);
$data = json_decode($JSONDATA, true);
$this->email = $data['param']["EMAIL"];
$this->signature = $data['signature'];
$this->signature_base64 = base64_decode($this->signature);
$this->dataencoded = json_encode($data['param']);
//SOLUTION 1 (By using phpseclib) but didnt work..
$rsa = $this->phpseclib->load();
$keysize = 2048;
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$d = $rsa->createKey($keysize);
$Kver = $d['publickey'];
$KSign = $d['privatekey'];
// Signing
$rsa->loadKey($KSign);
$rsa->setSignatureMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setHash('sha256');
$signature = $rsa->sign($this->dataencoded);
$signedHS = base64_encode($signature);
// Verification
$rsa->loadKey($Kver);
$status = $rsa->verify($this->dataencoded, $this->firma_base64); // getting an error on this line Message: Invalid signature
var_dump($status); // reutrn false
//SOLUTION 2 (By using code php methods)
// obtener la clave pública desde el certifiado y prepararla
$orignal_parse = parse_url("https://example.com", PHP_URL_HOST);
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
openssl_x509_export($cert["options"]["ssl"]["peer_certificate"],$cert_key);
$pubkeyid = openssl_pkey_get_public($cert_key);
$dataencoded = json_encode($data['param']);
echo $ok = openssl_x509_check_private_key($cert_key,$this->firma_base64); // return nothing
echo $ok1 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA256); // returns 0
echo $ok2 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA512); // returns 0
echo $ok3 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA256); // returns 0
echo $ok4 = openssl_verify($dataencoded, $this->firma, $pubkeyid, OPENSSL_ALGO_SHA512); // returns 0
Java code - (this code works and returns true)
private boolean verifySignautre(String frm) throws NetinfException, IOException, CMSException,
CertificateException, OperatorCreationException, Exception {
Security.addProvider(new BouncyCastleProvider());
//we extract the containers that make up the signature and the keystore used to sign included in the same signature.
CMSSignedData signedData = new CMSSignedData(Base64.decode(frm.getBytes()));
SignerInformationStore signers = signedData.getSignerInfos();
Store certStore = signedData.getCertificates();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
//retrieve the certificate with the recipient's id.
SignerInformation signerInfo = (SignerInformation) it.next();
Collection certCollection = certStore.getMatches(signerInfo.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder signerCertificateHolder = (X509CertificateHolder) certIt.next();
//create the container to validate signature.
ContentVerifierProvider contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new
DefaultDigestAlgorithmIdentifierFinder()).build(signerCertificateHolder);
//valid signature and then certificate validity date
try{
X509Certificate signedcert = new
JcaX509CertificateConverter().setProvider("BC").getCertificate(signerCertificateHolder);
signedcert.checkValidity();
signedcert.verify(signedcert.getPublicKey());
return true;
}catch(Exception e){
return false;
}
}
I simply need to convert this Java code into PHP. However, as you can see above that I tried different approaches but none of them worked.
Please support me to find the solution.
your support would be higly appreciated

Restkit 20 failed to match all (0) response descriptors

I don't know if failed to match all (0) response descriptors means there are 0 descriptors?
Here are some logs:
PATH:
search/patients?q=qwer&start=0&max=40
BASE URL:
https://amb.XXX.com/
RKRESPONSEDESCRIPTORS:
(
"<RKResponseDescriptor: 0xaaca6a0 method=(GET) pathPattern=search/patients?q=qwer&start=0&max=40 keyPath=(null) statusCodes=(null) : <RKObjectMapping:0xaab4f80 objectClass=NSMutableDictionary propertyMappings=(\n \"<RKAttributeMapping: 0x9edf630 final_page => finalPage>\",\n \"<RKRelationshipMapping: 0xaac9750 results => patientSearchResultDetails>\"\n)>>"
)
restkit.object_mapping:RKMapperOperation.m:378 Executing mapping operation for representation: {
"final_page" = 1;
results = (
{
age = "39 years";
"date_of_birth" = "1975-01-15";
gender = Male;
mrns = {
effective = (
10000423
);
ineffective = (
);
};
"name_full_formatted" = "DOE, PETER";
"person_id" = 1390007;
"phone_numbers" = {
home = "(816) 555-5555";
};
"preferred_name" = PETE;
"primary_care_provider" = {
name = "Test, Physician4";
};
}
);
}
and targetObject: (null)
2014-04-16 12:45:03.263 IONShell[31463:4f03] D restkit.object_mapping:RKMapperOperation.m:404 Finished performing object mapping. Results: (null)
2014-04-16 12:45:03.264 IONShell[31463:4e1b] E restkit.network:RKObjectRequestOperation.m:208 GET 'https://amb.XXX.com/search/patients?q=qwer&start=0&max=40' (200 OK / 0 objects) [request=1.5086s mapping=0.0000s total=1.5143s]:
error=Error Domain=org.restkit.RestKit.ErrorDomain Code=1001 "No response descriptors match the response loaded." UserInfo=0xa9eead0 {NSErrorFailingURLStringKey=https://amb.XXX.com/search/patients?q=qwer&start=0&max=40, NSLocalizedFailureReason=A 200 response was loaded from the URL 'https://amb.XXX.com/search/patients?q=qwer&start=0&max=40', which failed to match all (0) response descriptors:, NSLocalizedDescription=No response descriptors match the response loaded., keyPath=null, NSErrorFailingURLKey=https://amb.XXX.com/search/patients?q=qwer&start=0&max=40, NSUnderlyingError=0xa9e3f40 "No mappable object representations were found at the key paths searched."}
Does (0) mean my RKObjectManager has no response descriptors? Or am I missing something else? This is driving me nuts.
thanks
Figure it out. I needed to send down the query part of the string as params.
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:queryString, #"q", start, #"start", maxCount, #"max", nil];
[self loadObjectsAtResourcePath:#"search/patients" params:params objectMapping:mapping]

Using mogenerator with Core Data entities results in error saving the data store

I have an iPad app that I use MagicalRecord to save the Core Data entities in a SQLite d/b. Everything was working fine until I decided to use FTASync to sync the Core Data with Parse.com.
Part of the requirements of FTASync are that you have to use mogenerator to generate the entity class files. Now, I'm getting this error:
2013-12-14 12:38:59.375 foo[5451:70b] Failed to save to data store: The operation couldn’t be completed. (Cocoa error 1560.)
2013-12-14 12:38:59.380 foo[5451:70b] DetailedError: {
NSLocalizedDescription = "The operation couldn\U2019t be completed. (Cocoa error 1570.)";
NSValidationErrorKey = objectId;
NSValidationErrorObject = "<PreferenceData: 0x1149c3a0> (entity: PreferenceData; id: 0x114a7eb0 <x-coredata://03C39CC9-AC6C-4E56-BB5A-67038ACB6801/PreferenceData/p25> ; data: {\n aAddlSvcs1 = \"\";\n aAddlSvcs10 = \"\";\n aAddlSvcs11 = \"\";\n aAddlSvcs12 = \"\";\n aAddlSvcs2 = \"\";\n aAddlSvcs3 = \"\";\n aAddlSvcs4 = \"\";\n aAddlSvcs5 = \"\";\n aAddlSvcs6 = \"\";\n aAddlSvcs7 = \"\";\n aAddlSvcs8 = \"\";\n aAddlSvcs9 = \"\";\n aApptInterval = \"\";\n aDeleteOldAppts = \"-1\";\n aDoubleBooking = \"-1\";\n aHideHelpBtns = 0;\n aHourFormat12 = 0;\n aShopCloses = 1200;\n aShopOpens = 1000;\n createdHere = 1;\n deleted = 0;\n objectId = nil;\n syncStatus = 2;\n updatedAt = nil;\n})";
}
If I want to sync my Core Data store using FTASync, I have to use mogenerator.
So, what exactly is this telling me, other than "it couldn't be completed"? How do I fix this?
UPDATED:
This is an image from the XCode Data Model Inspector
You have defined some validation rules in the xcdatamodel with the model editor: minimum/maximum values, required relationship, min/max string length.
When you insert objects via a GUI, you'll see immediate feedback when you try to create an object that fails validation. But if you create or modify an object in code, you won't see an error unless you try to save the Managed Object Context.
You can invoke -validateForUpdate: (or -validateForInsert: or -validateForDelete:) within the code that's creating your PreferenceData instance. Invoke it multiple times as you build the object, and you'll see where you're going wrong.

How to reach NSDictionary properties that have a class?

I've created an NSMutableArray with a class "Adealer" for it's objects. In my "listVC" I populate all the properties (as shown below) within a loop, where the "Adealer" class is used to create objects.
I then transferred one object from that array via a segue to my "detailsVC". Here I first import Adealer class and when I call this in my "detailsVC";
NSLog(#"restGPSTransfer (NSDictionary) class = %#, content is = %#",[restGPSTransfer class],[restGPSTransfer description]);
I get this;
restGPSTransfer (NSDictionary) class = Adealer, content is =
theDealer object and it's properties:
dealerID = 7
dealerName = Uppsala Centrum Test
dealerAdressStreet = Dragarbrunnsgatan 55
dealerAdressZip = 75320
dealerAdressCity = Uppsala
dealerTel =
dealerMail =
dealerWeb = www.uppsala.se
dealerLogo =
dealerImages =
dealerText = Uppsala centrum
dealerProducts =
dealerLongitude = 17.63893
dealerLatitude = 59.85856
dealerDistance = (null) // This is ok
dealerDistance2 = 8586398.000000
So far so god, BUT I can't reach the above properties in a simple call like this in the "detailsVC" (?!);
self.labelRestName.text = [restGPSTransfer objectForKey:#"dealerName"];
...it crashes with the error: "-[Adealer objectForKey:]: unrecognized selector sent to instance 0x8a92db0" (then termination with InvalidArgumentExeption...)
What have I missed?
Much more detail can be found in my question here (which I still got no answers to!);
How do I get out data from my NSDirectory (not just a property typo)?
Thank's for any help :-)
It looks like memory issue,
Are you using ARC?
Could you add your dictionary allocation code?

How to get output of a webpage in ActionScript 2

For Actionscript 2.0
Let's say this page
www.example.com/mypage
returns some html that I want to parse in Actionscript.
How do i call this page from Actionscript while getting back the response in a string variable?
use LoadVars():
var lv = new LoadVars();
//if you want to pass some variables, then:
lv.var1 = "BUTTON";
lv.var2 = "1";
lv.sendAndLoad("http://www.example.com/mypage.html", lv, "POST");
lv.onLoad = loadedDotNetVars;
function loadedDotNetVars(success)
{
if(success)
{
// operation was a success
trace(lv.varnameGotFromPage)
}
else
{
// operation failed
}
}
//if you dont want to send data, just get from it, then use just lv.Load(...) instead of sendAndLoad(...)
I understand. Use this code then:
docXML = new XML(msg);
XMLDrop = docXML.childNodes;
XMLSubDrop = XMLDrop[0].childNodes;
_root.rem_x = (parseInt(XMLSubDrop[0].firstChild));
_root.rem_y = (parseInt(XMLSubDrop[1].firstChild));
_root.rem_name = (XMLSubDrop[2].firstChild);
var htmlFetcher:LoadVars = new LoadVars();
htmlFetcher.onData = function(thedata) {
trace(thedata); //thedata is the html code
};
Use:
htmlFetcher.load("http://www.example.com/mypage");
to call.
I suppose you could use:
page = getURL("www.example.com/mypage.html");
And it would load the page contents on the page variable.