How to get access to user's google calendar from React Native (expo)? - react-native

I use Expo, and I want to add access to my app to users which have a Google account. Then I need to get info about Google calendars of the user which login into my app.
I implement login function using: Expo.Google.logInAsync(options) (https://docs.expo.io/versions/latest/sdk/google). My scope look like this:
scopes: ['https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/calendar.readonly']
When someone tries to login into my app, it asks about permission to see calendars list. In response I get:
Object {
"accessToken": "a",
"idToken": "b",
"refreshToken": "c",
"serverAuthCode": "d",
"type": "success",
"user": Object {
"email": "e",
"familyName": "f",
"givenName": "g",
"id": "h",
"name": "i",
"photoUrl": "j",
},
}
I received data about the user, but I don't have any data about its calendars.
I tried to get data about calendars (https://developers.google.com/calendar/v3/reference/calendarList) with this function:
getUsersCalendarList = async (accessToken) => {
let calendarsList = await fetch('https://www.googleapis.com/calenda/v3/users/me/calendarList', {
headers: { Authorization: `Bearer ${accessToken}`},
});
return calendarsList;
}
In response I got:
Response {
"_bodyBlob": Blob {
"_data": Object {
"blobId": "67b8b161-690f-4ff6-9cee-1dce12840ebd",
"offset": 0,
"size": 994,
},
},
"_bodyInit": Blob {
"_data": Object {
"blobId": "67b8b161-690f-4ff6-9cee-1dce12840ebd",
"offset": 0,
"size": 994,
},
},
"headers": Headers {
"map": Object {
"alt-svc": Array [
"quic=\":443\"; ma=2592000; v=\"44,43,39,35\"",
],
"cache-control": Array [
"public, max-age=0",
],
"content-type": Array [
"application/json; charset=UTF-8",
],
"date": Array [
"Thu, 17 Jan 2019 11:30:32 GMT",
],
"expires": Array [
"Thu, 17 Jan 2019 11:30:32 GMT",
],
"server": Array [
"GSE",
],
"vary": Array [
"X-Origin",
],
"x-content-type-options": Array [
"nosniff",
],
"x-frame-options": Array [
"SAMEORIGIN",
],
"x-xss-protection": Array [
"1; mode=block",
],
},
},
"ok": false,
"status": 403,
"statusText": undefined,
"type": "default",
"url": "https://www.googleapis.com/calendar/v3/users/me/calendarList",
}
How can I get a list of user's google calendars in Expo?

I find the solution here: React-Native JSON fetch from URL. One needs to use json() function on returned object.
The getUsersCalendarList schulde look like this:
getUsersCalendarList = async (accessToken) => {
let calendarsList = await fetch('https://www.googleapis.com/calenda/v3/users/me/calendarList', {
headers: { Authorization: `Bearer ${accessToken}`},
});
return calendarsList.json();
}

You can also add the access token as a parameter on the request.
https://www.googleapis.com/calenda/v3/users/me/calendarList?access_token={token}
I am not a react dev so not exactly sure how to fix your header. It looks ok.

Related

Vonage WhatsApp messages suddenly stopped working

I have recently joined a company that is using Vonage and we have WhatsApp communications which was working fine in both dev and production that have both suddenly stopped working.
The shape of the incoming json looks to have changed significantly, but I have changed the code that is reading this and am able to read the messages into the system.
The problem that I have now, is outgoing message is not being accepted.
If I send this json body over
{
"from": "4474183xxxxx",
"to": "4474719xxxxx",
"message": {
"Type": "text",
"content": "Hello! I’m CAI, A Virtual Chat-bot assistant. blurb, more blurb.... .\n\n1. Okay I understand\n\nChoose any one option. Type \"1\" to choose first option."
}
}
I get the following response
{
"Status": "fail", // custom one to my company
"e3": {
"Error": {
"body": {
"type": "https://developer.vonage.com/api-errors",
"title": "Your request parameters didn't validate.",
"detail": "Found errors validating 1 of your submitted parameters.",
"invalid_parameters": [
{
"name": "to",
"reason": "Malformed JSON body."
}
],
"instance": "cf4bce73-2db5-4102-b7af-xxxxxx"
},
"headers": {
"date": "Wed, 02 Nov 2022 14:02:08 GMT",
"content-type": "application/problem+json",
"content-length": "287",
"connection": "close",
"x-envoy-upstream-service-time": "3",
"x-frame-options": "deny",
"x-xss-protection": "1; mode=block",
"strict-transport-security": "max-age=31536000; includeSubdomains",
"x-content-type-options": "nosniff",
"server": "envoy"
},
"statusCode": 400
},
"StatCode": 400,
"Response": null
},
"a": {
"label": 6,
"trys": [
[
0,
6,
null,
7
]
],
"ops": []
}
}
However, looking at the shape of the message that is on the website (https://dashboard.nexmo.com/messages/sandbox) and send this message
{
"from": "xxxx",
"to": "xxxx",
"message_type": "text",
"text": "Hello! I’m CAI, blurb... .\n\n1. Okay I understand\n\nChoose any one option. Type \"1\" to choose first option.",
"channel" : "whatsapp"
}
I get this response
{
"Status": "fail",
"e3": {},
"a": {
"label": 6,
"trys": [
[
0,
6,
null,
7
]
],
"ops": []
},
"Message": "Cannot read property 'Type' of undefined"
}
I would be grateful if someone could help me shape the message that needs to be sent to vonage to that this can be sent out to the end user \ recipient correct.
Thanks
Simon

Docusign : 400 Error "Unable to parse multipart body" when trying to create envelope from Template ID from UI5 application

We are trying to figure out whether Docusign can be used in productive scenarios for our client requirements.
We have a UI5 application which will be used to sign Documents. We have created a template in the demo instance of Docusign.
However when we are trying to create an envelope from the application we are getting 400 Error Unable to parse multipart body. Now the same payload when used in POSTMAN application results in the envelope getting created successfully. The headers passed are also the same.
In Ui5 App :
var settings = {
"async": true,
"crossDomain": true,
"url": "/docusign/envelopes",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": "User DnVj27euWrCi4ANoMV5puvxVxYAcUCG3PlkUSpWpC08=, Organization 6ba64ce816dec995b17d04605e329a30, Element X4XuUq/T5UUh2o9xwaamZCCRwOKUCPr1Kv1Nj+qHPj0=",
"Content-Type": "application/json"
},
"data": JSON.stringify({
"status": "sent",
"compositeTemplates": [{
"compositeTemplateId": "1",
"inlineTemplates": [{
"recipients": {
"signers": [{
"email": "johndoe#testmail.com",
"name": "John Doe",
"recipientId": "1",
"roleName": "Signer",
"clientUserId": "12345",
"tabs": {
"textTabs": [{
"tabLabel": "firstName",
"value": "John"
}, {
"tabLabel": "lastName",
"value": "Doe"
}, {
"tabLabel": "phoneNo",
"value": "022-635363"
}, {
"tabLabel": "email",
"value": "test#gmail.com"
}]
}
}]
},
"sequence": "1"
}],
"serverTemplates": [{
"sequence": "1",
"templateId": "0bf97611-a457-4e8e-ac7e-1593c17ba3f6"
}]
}]
})
};
var deferred = $.Deferred();
$.ajax(settings).done(function (response) {
deferred.resolve(response);
}.bind(this)).fail(function (error) {
deferred.reject(error);
}.bind(this));
In Postman :
Help would be greatly appreciated in resolving this issue.
Could you stringify outside of the json settings and perhaps break your call down a little before placing everything in settings.
i.e. Try and re-shape your jquery ajax call:
var headers = {"Authorization": "User DnVj27euWrCi4ANoMV5puvxVxYAcUCG3PlkUSpWpC08=, Organization 6ba64ce816dec995b17d04605e329a30, Element X4XuUq/T5UUh2o9xwaamZCCRwOKUCPr1Kv1Nj+qHPj0=", "Content-Type": "application/json" };
var payload = JSON.stringify({
"status": "sent",
"compositeTemplates": [{
"compositeTemplateId": "1",
"inlineTemplates": [{
"recipients": {
"signers": [{
"email": "johndoe#testmail.com",
"name": "John Doe",
"recipientId": "1",
"roleName": "Signer",
"clientUserId": "12345",
"tabs": {
"textTabs": [{
"tabLabel": "firstName",
"value": "John"
}, {
"tabLabel": "lastName",
"value": "Doe"
}, {
"tabLabel": "phoneNo",
"value": "022-635363"
}, {
"tabLabel": "email",
"value": "test#gmail.com"
}]
}
}]
},
"sequence": "1"
}],
"serverTemplates": [{
"sequence": "1",
"templateId": "0bf97611-a457-4e8e-ac7e-1593c17ba3f6"
}]
}]
});
$.ajax({
"async": true,
"crossDomain": true,
"url": "/docusign/envelopes",
"method": "POST",
"timeout": 0,
"headers": headers,
"data": payload
});
I am sure this will lead you to your final "consolidated" answer.
If the exact same JSON is being sent from Postman and from the UI5 application, then you'll get the same results. But you aren't, so something is different.
Probably the UI5 system is sending the API as a mime multi-part request, but isn't setting the content type for the JSON request part correctly.
To verify: use the DocuSign API logger to see what is being received by DocuSign. Compare between the request being sent from UI5 and from Postman.
To fix: you'll need to set additional UI5 parameters so the request is NOT sent as a multi-part mime message. Or send the multi-part message with the needed settings. See the docs and see a multi-part example.
PS PLEASE post an answer to your question with the solution to your problem (once you've found it) to help others in the future. Thank you!!
I was able to fix the issue by directly using the Docusign API (https://demo.docusign.net/restapi/v2/accounts). I was earlier using the SAP Openconnector to connect to Docusign.
https://api.openconnectors.eu3.ext.hanatrial.ondemand.com/elements/api-v2
Thanks all for the help.
I have run into the very same issue recently, and almost decided to give up, but finally, I have managed to find a way to make it work!
The thing is that you need to execute the Ajax call in the following way:
_createEnvelops: function () {
var deferred = $.Deferred();
var oTemplateData = this._getTemplateData();
var oFormData = new FormData();
oFormData.append('envelope', JSON.stringify(oTemplateData));
var settings = {
"async": true,
"crossDomain": true,
"url": '/docusign/envelopes',
"method": "POST",
"data": oFormData,
processData: false,
contentType: false,
"headers": {
"Authorization": sAuthToken
}
};
$.ajax(settings).done(function (response) {
deferred.resolve(response);
}.bind(this)).fail(function (error) {
deferred.reject(error);
}.bind(this));
return deferred;
},
Maybe it will be useful for someone in the future ;)

Axios Request Does Not Return a Token

i'm trying to apply token for my request. So i tried to console.log the result of the request, and cannot find any token there inside the object array.
Object {
"config": Object {
"adapter": [Function xhrAdapter],
"data": "ktp=3578270708950002&member=199508070003",
"headers": Object {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded",
},
"maxContentLength": -1,
"method": "post",
"timeout": 0,
"transformRequest": Object {
"0": [Function transformRequest],
},
"transformResponse": Object {
"0": [Function transformResponse],
},
"url": "http://103.53.10.122/mobile/LoginCheck.php",
"validateStatus": [Function validateStatus],
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
},
"data": Array [
Object {
"status": "67457",
},
],
"headers": Object {
"connection": "keep-alive",
"content-type": "text/html; charset=UTF-8",
"date": "Fri, 22 Dec 2017 05:38:21 GMT",
"server": "nginx",
"transfer-encoding": "chunked",
"vary": "Accept-Encoding",
},
"request": XMLHttpRequest {
"DONE": 4,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"OPENED": 1,
"UNSENT": 0,
"_aborted": false,
"_cachedResponse": undefined,
"_hasError": false,
"_headers": Object {
"accept": "application/json, text/plain, */*",
"content-type": "application/x-www-form-urlencoded",
},
"_incrementalEvents": false,
"_lowerCaseResponseHeaders": Object {
"connection": "keep-alive",
"content-type": "text/html; charset=UTF-8",
"date": "Fri, 22 Dec 2017 05:38:21 GMT",
"server": "nginx",
"transfer-encoding": "chunked",
"vary": "Accept-Encoding",
},
"_method": "POST",
"_requestId": null,
"_response": "[{\"status\":\"67457\"}]",
"_responseType": "",
"_sent": true,
"_subscriptions": Array [],
"_timedOut": false,
"_trackingName": "unknown",
"_url": "http://103.53.10.122/mobile/LoginCheck.php",
"readyState": 4,
"responseHeaders": Object {
"Connection": "keep-alive",
"Content-Type": "text/html; charset=UTF-8",
"Date": "Fri, 22 Dec 2017 05:38:21 GMT",
"Server": "nginx",
"Transfer-Encoding": "chunked",
"Vary": "Accept-Encoding",
},
"responseURL": "http://103.53.10.122/mobile/LoginCheck.php",
"status": 200,
"timeout": 0,
"upload": XMLHttpRequestEventTarget {},
"withCredentials": true,
},
"status": 200,
"statusText": undefined,
}
Can someone point me how to add token to authenticate, because i'm still confuse about the concept even after reading it. So if i'm not mistaken, i should do the following in order:
Generate the token when user successfully login
Save the token in local storage
Use the token for each request (How does the backend check the validity of the token?)
Any help would be appreciated
Depending on the way the backend handles API requests you should either use axios.get and append the token to the URL or use axios.post and pass a object as body to the method with your token.
E.g.
axios.post('http://103.53.10.122/mobile/LoginCheck.php', {
username: "test",
password: "1234"
})
.then((res) => {
console.log(res);
/*
In this example I assume that res.data has the token returned from the backend
The res.data should look like this then:
{
token: "1234"
}
*/
let token = res.data.token;
AsyncStorage.setItem("token", token);
})
.catch((err) => {
console.log(err);
});
To use the token for each request save it in AsyncStorage for persistent storage or in the redux state if you are using redux.
On the server side you could generate a JSON web token which contains all data you need for authenticating the user and validating it with the data stored in a database. Due to the fact that you are using PHP I can recommend you this introduction to JSON web tokens in combination with PHP: https://www.sitepoint.com/php-authorization-jwt-json-web-tokens/

AWS SES S3 process inbound email

I'm working on a publish by email system based on AWS SES. For all incoming emails I've set routing to save messages in an S3 bucket so I can asynchronously process them. The problem I have is that the messages are saved in the S3 bucket in a raw format: headers, email body, etc + the encrypted attachment (a huge string) - all in a single file.
Is there a way to break the email message apart form the attachment and save both in separate files at AWS SES level? I'm trying to get the data in the format I need straight from AWS and avoid adding another processing step to the process.
If AWS SES doesn't provide such a feature, what would be the proper way to process these messages to obtain the result described above?
It doesn't look possible to have SES automatically split up the email for you. As per the documentation here:
Amazon SES provides you the raw, unmodified email, which is typically
in Multipurpose Internet Mail Extensions (MIME) format.
I would use S3 or SNS to trigger a Lambda function whenever SES puts a new email file to S3. The Lambda function could split the file however you wish, then write those new files to another S3 bucket.
For anyone coming back later on to this question, this is the link to the JSON structure that you get when you invoke a Lambda function from SES.
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-notifications-examples.html
It took some searching to arrive at that page ;-)
From the link, a Lambda notification would look like this,
{
"notificationType": "Received",
"receipt": {
"timestamp": "2015-09-11T20:32:33.936Z",
"processingTimeMillis": 406,
"recipients": [
"recipient#example.com"
],
"spamVerdict": {
"status": "PASS"
},
"virusVerdict": {
"status": "PASS"
},
"spfVerdict": {
"status": "PASS"
},
"dkimVerdict": {
"status": "PASS"
},
"action": {
"type": "S3",
"topicArn": "arn:aws:sns:us-east-1:012345678912:example-topic",
"bucketName": "my-S3-bucket",
"objectKey": "\email"
}
},
"mail": {
"timestamp": "2015-09-11T20:32:33.936Z",
"source": "0000014fbe1c09cf-7cb9f704-7531-4e53-89a1-5fa9744f5eb6-000000#amazonses.com",
"messageId": "d6iitobk75ur44p8kdnnp7g2n800",
"destination": [
"recipient#example.com"
],
"headersTruncated": false,
"headers": [
{
"name": "Return-Path",
"value": "<0000014fbe1c09cf-7cb9f704-7531-4e53-89a1-5fa9744f5eb6-000000#amazonses.com>"
},
{
"name": "Received",
"value": "from a9-183.smtp-out.amazonses.com (a9-183.smtp-out.amazonses.com [54.240.9.183]) by inbound-smtp.us-east-1.amazonaws.com with SMTP id d6iitobk75ur44p8kdnnp7g2n800 for recipient#example.com; Fri, 11 Sep 2015 20:32:33 +0000 (UTC)"
},
{
"name": "DKIM-Signature",
"value": "v=1; a=rsa-sha256; q=dns/txt; c=relaxed/simple; s=ug7nbtf4gccmlpwj322ax3p6ow6yfsug; d=amazonses.com; t=1442003552; h=From:To:Subject:MIME-Version:Content-Type:Content-Transfer-Encoding:Date:Message-ID:Feedback-ID; bh=DWr3IOmYWoXCA9ARqGC/UaODfghffiwFNRIb2Mckyt4=; b=p4ukUDSFqhqiub+zPR0DW1kp7oJZakrzupr6LBe6sUuvqpBkig56UzUwc29rFbJF hlX3Ov7DeYVNoN38stqwsF8ivcajXpQsXRC1cW9z8x875J041rClAjV7EGbLmudVpPX 4hHst1XPyX5wmgdHIhmUuh8oZKpVqGi6bHGzzf7g="
},
{
"name": "From",
"value": "sender#example.com"
},
{
"name": "To",
"value": "recipient#example.com"
},
{
"name": "Subject",
"value": "Example subject"
},
{
"name": "MIME-Version",
"value": "1.0"
},
{
"name": "Content-Type",
"value": "text/plain; charset=UTF-8"
},
{
"name": "Content-Transfer-Encoding",
"value": "7bit"
},
{
"name": "Date",
"value": "Fri, 11 Sep 2015 20:32:32 +0000"
},
{
"name": "Message-ID",
"value": "<61967230-7A45-4A9D-BEC9-87CBCF2211C9#example.com>"
},
{
"name": "X-SES-Outgoing",
"value": "2015.09.11-54.240.9.183"
},
{
"name": "Feedback-ID",
"value": "1.us-east-1.Krv2FKpFdWV+KUYw3Qd6wcpPJ4Sv/pOPpEPSHn2u2o4=:AmazonSES"
}
],
"commonHeaders": {
"returnPath": "0000014fbe1c09cf-7cb9f704-7531-4e53-89a1-5fa9744f5eb6-000000#amazonses.com",
"from": [
"sender#example.com"
],
"date": "Fri, 11 Sep 2015 20:32:32 +0000",
"to": [
"recipient#example.com"
],
"messageId": "<61967230-7A45-4A9D-BEC9-87CBCF2211C9#example.com>",
"subject": "Example subject"
}
}
}
Regarding the question on how to write a Lambda. Here is a portion of our Lambda. The main thing to take out of it is the parseEvent function. and data.event.Records[0] which will give you details
exports.handler = function(event, context, callback) {
var AWS = require('aws-sdk');
// Validate characteristics of a SES event record.
if (!event ||
!event.hasOwnProperty('Records') ||
event.Records.length !== 1 ||
event.Records[0].hasOwnProperty('eventSource') ||
event.Records[0].eventSource !== 'aws:ses' ||
event.Records[0].eventVersion !== '1.0') {
callback(null, {'disposition':'STOP_RULE_SET'});
}
email = data.event.Records[0].ses.mail;
subjectLine = event.Records[0].ses.mail.commonHeaders.subject;
}
The key is the event.Record[0].ses.mail. Unfortunately, I can't find the structure of it via a Google search, I am sure I had seen it before.

Detect the id of a sent mail

I would like to detect the message-id of an email
sent from the gmail interface?
what are your proposals?
Thanks.
One way of doing it would be to first list messages:
GET https://www.googleapis.com/gmail/v1/users/me/messages
Response:
{
"messages": [
{
"id": "14f60b097be71757",
"threadId": "14f60b097be71757"
},
{
"id": "14f603ead78aff97",
"threadId": "14f603ead78aff97"
}, ...
Then, get the message you want, and just ask for the Message-Id-header:
format = metadata
metadataHeaders = Message-Id
GET https://www.googleapis.com/gmail/v1/users/me/messages/14f60b097be71757?format=metadata&metadataHeaders=Message-Id
Response:
{
"id": "14f60b097be71757",
"threadId": "14f60b097be71757",
"labelIds": [
"INBOX",
"CATEGORY_PROMOTIONS",
"UNREAD"
],
"snippet": "Cool snippet...",
"historyId": "545168",
"internalDate": "1440436229000",
"payload": {
"mimeType": "multipart/alternative",
"headers": [
{
"name": "Message-Id",
"value": "<10342275.20150824171029.55db500501e9a7#example.com>" // Here it is!
}
]
},
"sizeEstimate": 73995
}