inserting google calender event into my agenda without oath - javascript

i am creating an agenda system that list and creates events in google calendar API,
i have successfully retrieved using the following code:
var mykey = 'your_api_key'; // typically like Gtg-rtZdsreUr_fLfhgPfgff
var calendarid = 'you_calendar_id'; // will look somewhat like 3ruy234vodf6hf4sdf5sd84f#group.calendar.google.com
$.ajax({
type: 'GET',
url: encodeURI('https://www.googleapis.com/calendar/v3/calendars/' + calendarid+ '/events?key=' + mykey),
dataType: 'json',
success: function (response) {
//do whatever you want with each
},
error: function (response) {
//tell that an error has occurred
}
});
now i need to insert events and everything i can find requires oath and is mostly about saving an event on the users calendar while i just want it saved in my calendar. any advice?

You can use a service account => https://developers.google.com/android/management/service-account
Create a Service Account
Create a Key for your service account (JSON should work)
Provide access to the required calendar scopes for your service account
Go to https://admin.google.com/
Go to Security->API Controls -> Domain-wide Delegation
Add scopes, for example https://www.googleapis.com/auth/calendar, https://www.googleapis.com/auth/calendar.events
When you call the API use the JSON (JWT => Json Web Token) file to authenticate
In the account where the calendar lives you have to provide permission to edit events from your calendar to the service account.
All the steps and code samples for HTTP/Rest using service account are here https://developers.google.com/identity/protocols/oauth2/service-account#httprest_1

Related

Use git credential manager to fetch azure devops api instead of personal access token

I am trying to fetch git azure devops api to get information about repositories and branches in js.
In order to achieve that, I made a little application with the following code :
$(document).ready(function() {
var personalToken = btoa(':'+'<personnalAccessToken>');
fetch('https://dev.azure.com/<company>/<project>/_apis/git/repositories?api-version=5.1', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
'Authorization': 'Basic '+ personalToken
}
}).then(function(response) {
return response.json();
}).then(function(repositories) {
console.log("There are "+repositories.count+" repositories");
}).catch(function(error) {
console.log('Fetch error: ' + error.message);
});
This code is working great but as you can see there is my personnalAccessToken writen directly inside the code... which is really bad...
When I am using git in command line, I don't have to specify any credential information because I use git credential manager for windows. Which means my personnalAccessToken is already stored, cached and automatically used everytime I use a git command, like clone, etc.
So, I would like my js code to use the same thing, I would like it to use my stored credentials automatically to fetch the api without being required to set my personnalAccessToken in code.
I have already searched for hours but can't find out if it is possible.
I have already searched for hours but can't find out if it is
possible.
Sorry but as I know it's impossible. The way you're calling the Rest API is similar to use Invoke-RestMethod to call rest api in Powershell.
In both these two scenarios, the process will try to fetch PAT for authentication in current session/context and it won't even try to search the cache in Git Credential Manager.
You should distinguish the difference between accessing Azure Devops service via Rest API and by Code:
Rest API:
POST https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?api-version=5.1
Request Body:
{
"query": "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = 'Task' AND [State] <> 'Closed' AND [State] <> 'Removed' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc"
}
Corresponding Code in C#:
VssConnection connection = new VssConnection(new Uri(azureDevOpsOrganizationUrl), new VssClientCredentials());
//create http client and query for resutls
WorkItemTrackingHttpClient witClient = connection.GetClient<WorkItemTrackingHttpClient>();
Wiql query = new Wiql() { Query = "SELECT [Id], [Title], [State] FROM workitems WHERE [Work Item Type] = 'Bug' AND [Assigned To] = #Me" };
WorkItemQueryResult queryResults = witClient.QueryByWiqlAsync(query).Result;
Maybe you can consider using a limited PAT, limit its scope to Code only:
I know there exists other Authentication mechanism
:
For Interactive JavaScript project: ADALJS and Microsoft-supported Client Libraries.
You can give it a try but I'm not sure if it works for you since you're not using real Code way to access the Azure Devops Service... Hope it makes some help :)
If you have the script set up in an Azure Runbook you can set it as an encrypted variable there and have it pull it from there before running rather than having it directly written into the code.
$encryptedPatVarName = "ADO_PAT"
$adoPat = Get-AutomationVariable -Name $encryptedPatVarName
$adoPatToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($adoPat)"))
$adoHeader = #{authorization = "Basic $adoPatToken"}
The above is the Powershell version of it. I have seen some people do it with other

Javascript: Google Calender + gapi: service account

My app makes use of Firebase to log users in, and they have access to a calendar, which is especially created as a single common calendar to add and remove reservations.
The app has, so to speak, its own gmail address for this purpose. The app is accessed via the google API (gapi client).
In order for the users to be able to interact with the calendar, I have found out that I can only use the service account of the calendar / app.
So far I managed to:
create a service key for the service account,
share the calendar with the service account "dummy" user,
use that service key (certificate) to create a JWT token (using jsrsasign library),
make a POST request to get an access token for gapi,
initialise the gapi auth and client, and have access to the calendar via gapi
Now when I get to the point of retrieving the google Calendar events, I do get a successful response, but the array of events is empty, even though there are test events available in the shared calendar.
The response looks like this:
{
"kind": "calendar#events",
"etag": "\"pqef3g4h5j6j0g\"",
"summary": "my_app_email#appspot.gserviceaccount.com",
"updated": "2019-01-15T21:14:05.029Z",
"timeZone": "UTC",
"accessRole": "owner",
"defaultReminders": [],
"items": []
}
There are a few topics on Stackoverflow regarding this, but none of them have helpful information, or they are for Pythin / PHP.
I am hoping someone can give advice with this for Javascript...
I resolved this... The problem was in the gapi request, when fetching the events.
I was using the wrong calendarId. I had its value set to the default 'primary', but the actual calendarId to be used, can be found under the Google Calendar Settings >> Integrate Calendar. In my settings, the calendarId was the associated account's email address.
So the gapi request looks like this:
const fetchTimeLimit = new Date(2019, 0, 1).toISOString();
let events = await gapi.client.calendar.events.list({
calendarId: 'calendar_email#gmail.com',
timeMin: fetchTimeLimit,
showDeleted: false,
singleEvents: true,
maxResults: 300,
orderBy: 'startTime'
})
.then(response => { ........etc

How to use Facebook token obtained through Firebase authentication appropriately?

I am trying to get a person's first name and last name when the person would like to sign up through Facebook, but wondering if there can be some security issue.
Based on the document from Firebase, the answer from Stack Overflow, and the explanation about parameters from Facebook website, I wrote the following codes:
firebase.auth().getRedirectResult().then(function(result) {
var token = result.credential.accessToken;
FB.api('/me', {fields: 'last_name', access_token: token}, function(response) {
console.log(response);
})
})
My main concern is that according to Facebook, it says:
One parameter of note is access_token which you can use to make an API call with a Page access token. App access tokens should never be used in this SDK as it is client-side, and your app secret would be exposed."
It looks like I cannot use this approach to get a user's first and last name.
Starting with Firebase 4.0.0, additional IdP data will be directly returned in the result of type UserCredential. You shouldn't need to make an additional API call to Facebook to get data like first/last name:
firebase.auth().getRedirectResult().then(function(result) {
if (result.user) {
// Additional user info like first name, last name,
// Facebook account url, gender, etc.
console.log(result.additionalUserInfo.profile);
// Facebook access token returned in the process
// for the scopes requested.
console.log(result.credential.accessToken);
}
});

How can I not authenticate everytime in StackExchange API calls using JS client?

I am using this code from the StackExchange App Documentation to get the user information from StackOverflow.
// For simplicity, we're using jQuery for some things
// However, the library has no jQuery dependency
$(function(){
// Initialize library
SE.init({
// Parameters obtained by registering an app, these are specific to the SE
// documentation site
clientId: 1,
key: 'U4DMV*8nvpm3EOpvf69Rxw((',
// Used for cross domain communication, it will be validated
channelUrl: 'https://api.stackexchange.com/docs/proxy',
// Called when all initialization is finished
complete: function(data) {
$('#login-button')
.removeAttr('disabled')
.text('Run Example With Version '+data.version);
}
});
// Attach click handler to login button
$('#login-button').click(function() {
// Make the authentication call, note that being in an onclick handler
// is important; most browsers will hide windows opened without a
// 'click blessing'
SE.authenticate({
success: function(data) {
alert(
'User Authorized with account id = ' +
data.networkUsers[0].account_id + ', got access token = ' +
data.accessToken
);
},
error: function(data) {
alert('An error occurred:\n' + data.errorName + '\n' + data.errorMessage);
},
networkUsers: true
});
});
});
This code works fine but I noticed that everytime it fires and gives the response access_token changes. How I can I just get user information using the access token. Plus this is returning user's data with all the sites he is part of. How can I limit it to just StackOverflow. I am unable to find proper documentation for this.
Can anyone please point me to the JS methods for making API calls from StackExchange API?

Send notifications to individual users using Azure Mobile Services with custom API

I hope to send notifications to individual users using Azure Mobile Services. When I add the notification service in Visual Studio 2013, it automatically generate a custom API in my Azure service. Since I have built my mobile service with JavaScript backend. The generate code is follow:
exports.post = function (request, response) {
response.send(statusCodes.OK);
sendNotifications(request);
};
function sendNotifications(request) {
var payload = '<?xml version="1.0" encoding="utf-8"?><toast><visual><binding template="ToastText01">' +
'<text id="1">' + request.body.toast + '</text></binding></visual></toast>';
var push = request.service.push;
push.wns.send(null,
payload,
'wns/toast', {
success: function (pushResponse) {
console.log("Sent push:", pushResponse);
}
});
}
And In my client service, I have used userId as my tags and invoke the function
`await App.MobileService.GetPush().RegisterNativeAsync(channel.Uri,userIdTags);`
where userIdTags is a List of strings that contains certain userId values I hope to receive the message.
But when I debug I found that all of users will receive the notification. So I would like to know whether do I need to handle or modify the auto-generate code in the custom API or any other reason that cause the problem .

Categories

Resources