I currently using google calendar on my website with the iframe you can insert. I tested Fullcalendar and I like what you can do with it.
But I would like to do same as the embed calendar, I would like to be able to create private event (not calendar, events). The sharing settings of the calendar is on public, but when using chrome, you can log with your google account and with the embed calendar you can see private event (if you have access to the calendar).
Is that possible with Fullcalendar ?
I figure out how to connect via OAUTH and get the private event when you are authentified.
By clicking on a button, you can connect to a google account (If already connected in browser, no button will appear and you will be log automaticly).
I follow this google example
<script type="text/javascript">
var clientId = '<your-client-id>';
var apiKey = '<your-api-key>';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
GeneratePublicCalendar();
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
// Step 4: Load the Google+ API
gapi.client.load('calendar', 'v3').then(function() {
// Step 5: Assemble the API request
var request = gapi.client.calendar.events.list({
'calendarId': '<your-calendar-id(The #gmail.com>'
});
// Step 6: Execute the API request
request.then(function(resp) {
var eventsList = [];
var successArgs;
var successRes;
if (resp.result.error) {
reportError('Google Calendar API: ' + data.error.message, data.error.errors);
}
else if (resp.result.items) {
$.each(resp.result.items, function(i, entry) {
var url = entry.htmlLink;
// make the URLs for each event show times in the correct timezone
//if (timezoneArg) {
// url = injectQsComponent(url, 'ctz=' + timezoneArg);
//}
eventsList.push({
id: entry.id,
title: entry.summary,
start: entry.start.dateTime || entry.start.date, // try timed. will fall back to all-day
end: entry.end.dateTime || entry.end.date, // same
url: url,
location: entry.location,
description: entry.description
});
});
// call the success handler(s) and allow it to return a new events array
successArgs = [ eventsList ].concat(Array.prototype.slice.call(arguments, 1)); // forward other jq args
successRes = $.fullCalendar.applyAll(true, this, successArgs);
if ($.isArray(successRes)) {
return successRes;
}
}
if(eventsList.length > 0)
{
// Here create your calendar but the events options is :
//fullcalendar.events: eventsList (Still looking for a methode that remove current event and fill with those news event without recreating the calendar.
}
return eventsList;
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
});
}
function GeneratePublicCalendar(){
// You need a normal fullcalendar with googleApi when user isn't logged
$('#calendar').fullCalendar({
googleCalendarApiKey: '<your-key>',
...
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
And in your google api console, make sure in API & Auth -> ID
OAuth Javascript origin is set properly (Like http://localhost
https://localhost if you are working on a local website)
Leave Redirection and API referent empty.
Fullcalendar is a front-end solution only. Logging into a google account and any other authentication isn't part of it.
That said, it can be connected to a google calendar, but only if it's a public google calendar. If you want to interface it to a private google calendar, you would have to build in that functionality.
If you can get the gcal events with JS and handle authentication, getting them into FullCalendar is easy. But that first part takes a few steps. Take a look at the google calendar api docs for instruction.
Related
I'm using accounts-ui and accounts-google in Meteor v1.4.1. I can't get the user.services object to appear scoped in the client code. In particular, I need google's profile picture.
I've configured the server-side code to authenticate with Google like so:
import { Meteor } from 'meteor/meteor';
import { ServiceConfiguration } from 'meteor/service-configuration';
const services = Meteor.settings.private.oauth;
for (let service of Object.keys(services)) {
ServiceConfiguration.configurations.upsert({
service
}, {
$set: {
clientId: services[service].app_id,
secret: services[service].secret,
loginStyle: "popup"
}
});
}
...and the client side code to configure permissions like so:
Accounts.ui.config({
requestPermissions: {
google: ['email', 'profile']
},
forceApprovalPrompt: {
google: true
},
passwordSignupFields: 'EMAIL_ONLY'
});
When users click the 'Sign-In with Google' button, a pop-up appears and they can authenticate. No prompt appears, however, despite forceApprovalPrompt being set to true for google.
The big issue is that when I execute this,
const user = Meteor.user();
console.log(user.services);
anywhere in client code, I do not see the expected user services information. I check my database and it is definitely there for the taking:
$ mongo localhost:27017
> db.users.find({})
> ... "services" : { "google" : { "accessToken" : ... } } ...
I'm curious what I'm missing? Should I explicitly define a publish function in order for user services data to exist in the client?
The services property is intentionally hidden on the client side for security reasons. There are a couple of approaches here :
Suggestions
My preferred one would be to expose a meteor method to bring you the
public keys and avatars you might need in the few places you'd need
them.
On a successful login, you could record the data you need somewhere in the user object, but outside of the services property.
As you said, you could make a new publication which explicitly specifies which fields to retrieve and which ones to hide. You have to be careful what you publish, though.
Code Examples
Meteor methods:
// server
Meteor.methods({
getProfilePicture() {
const services = Meteor.user().services;
// replace with actual profile picture property
return services.google && services.google.profilePicture;
}
});
// client
Meteor.call('getProfilePicture', (err, profilePicture) => {
console.log('profile picture url', profilePicture);
});
Update on successful user creation (you might want to have a login hook as well to reflect any avatar/picture changes in google):
// Configure what happens with profile data on user creation
Accounts.onCreateUser((options, user) => {
if (!('profile' in options)) { options.profile = {}; }
if (!('providers' in options.profile)) { options.profile.providers = {}; }
// Define additional specific profile options here
if (user.services.google) {
options.profile.providers.google = {
picture: user.services.google.picture
}
}
user.profile = options.profile;
return user;
});
Publish only select data...
// Server
Meteor.publish('userData', function () {
if (this.userId) {
return Meteor.users.find({ _id: this.userId }, {
fields: { other: 1, things: 1 }
});
} else {
this.ready();
}
});
// Client
Meteor.subscribe('userData');
I m using full calendar for a web app project and I sync it with google calendar of my client, but for the moment only public calendar.
Is there any way to sync with a private calendar ?
Note : We use 0auth to identify and sync with Google account.
Thanks
I think it would work with private calendar using the correct authorization.
Authorizing requests with OAuth 2.0
All requests to the Google Calendar API must be authorized by an authenticated user.
Here is a sample create by Alexandre:
<script type="text/javascript">
var clientId = '<your-client-id>';
var apiKey = '<your-api-key>';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
GeneratePublicCalendar();
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
// Step 4: Load the Google+ API
gapi.client.load('calendar', 'v3').then(function() {
// Step 5: Assemble the API request
var request = gapi.client.calendar.events.list({
'calendarId': '<your-calendar-id(The #gmail.com>'
});
// Step 6: Execute the API request
request.then(function(resp) {
var eventsList = [];
var successArgs;
var successRes;
if (resp.result.error) {
reportError('Google Calendar API: ' + data.error.message, data.error.errors);
}
else if (resp.result.items) {
$.each(resp.result.items, function(i, entry) {
var url = entry.htmlLink;
// make the URLs for each event show times in the correct timezone
//if (timezoneArg) {
// url = injectQsComponent(url, 'ctz=' + timezoneArg);
//}
eventsList.push({
id: entry.id,
title: entry.summary,
start: entry.start.dateTime || entry.start.date, // try timed. will fall back to all-day
end: entry.end.dateTime || entry.end.date, // same
url: url,
location: entry.location,
description: entry.description
});
});
// call the success handler(s) and allow it to return a new events array
successArgs = [ eventsList ].concat(Array.prototype.slice.call(arguments, 1)); // forward other jq args
successRes = $.fullCalendar.applyAll(true, this, successArgs);
if ($.isArray(successRes)) {
return successRes;
}
}
if(eventsList.length > 0)
{
// Here create your calendar but the events options is :
//fullcalendar.events: eventsList (Still looking for a methode that remove current event and fill with those news event without recreating the calendar.
}
return eventsList;
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
});
}
function GeneratePublicCalendar(){
// You need a normal fullcalendar with googleApi when user isn't logged
$('#calendar').fullCalendar({
googleCalendarApiKey: '<your-key>',
...
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
Or
Perform Google Apps Domain-Wide Delegation of Authority
In enterprise applications you may want to programmatically access users data without any manual authorization on their part. In Google Apps domains, the domain administrator can grant to third party applications domain-wide access to its users' data — this is referred as domain-wide delegation of authority. To delegate authority this way, domain administrators can use service accounts with OAuth 2.0.
For additional detailed information, see Using OAuth 2.0 for Server to Server Applications
Hope this helps!
I have tried in the backend with php, use the google php client library to get the events and then put it into fullcalendar. This way, it works.
I am having trouble sorting out the new MailChimp API (V3.0). It does not seem like there is a way to call a subscribe method. It seems like I have to use their Sign Up Form. Am I correct?
If by "subscribe" you mean that your application will add someone to a mailing list, you may want to take a look at the List Members Collection portion of their documentation.
http://kb.mailchimp.com/api/resources/lists/members/lists-members-collection
Adding/editing a subscriber via MailChimp v3.0 REST API.
// node/javascript specific, but pretty basic PUT request to MailChimp API endpoint
// dependencies (npm)
var request = require('request'),
url = require('url'),
crypto = require('crypto');
// variables
var datacenter = "yourMailChimpDatacenter", // something like 'us11' (after '-' in api key)
listId = "yourMailChimpListId",
email = "subscriberEmailAddress",
apiKey = "yourMailChimpApiKey";
// mailchimp options
var options = {
url: url.parse('https://'+datacenter+'.api.mailchimp.com/3.0/lists/'+listId+'/members/'+crypto.createHash('md5').update(email).digest('hex')),
headers: {
'Authorization': 'authId '+apiKey // any string works for auth id
},
json: true,
body: {
email_address: email,
status_if_new: 'pending', // pending if new subscriber -> sends 'confirm your subscription' email
status: 'subscribed',
merge_fields: {
FNAME: "subscriberFirstName",
LNAME: "subscriberLastName"
},
interests: {
MailChimpListGroupId: true // if you're using groups within your list
}
}
};
// perform update
request.put(options, function(err, response, body) {
if (err) {
// handle error
} else {
console.log('subscriber added to mailchimp list');
}
});
I'm using the Google Analytics Embed API to embed some GA data on a custom dashboard. I'm using the method from the demo site:
https://ga-dev-tools.appspot.com/embed-api/
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: 'MY CLIENT ID',
});
This works fine. But it requires the user to authenticate before they can see the data. How do I get around this or auto-authenicate using this method (so anyone that can access the page doesn't have to login)?
I want to use Google Analytics Embed in my admin dashboard. After hours, searching similar posts on stackoverflow, and any other sites found by google search, i have solved my auth problem. Then i want to share.
Firstly, you know, you need some credentials. get your client_id and client_secret keys from https://console.developers.google.com. Add your site(example.com) to authenticated js source... and follow directions...
Secondly, go to https://developers.google.com/oauthplayground/ and select api (Google Analytics Reporting API v4) check https://www.googleapis.com/auth/analytics and https://www.googleapis.com/auth/analytics.readonly
And this is important: Before pressing Authorize Apis button, you should press settings button on top rigth side of page. then check "Use your own OAuth credentials" on settings popup and write your own client_id client_secret
Now you can press Authorize Apis button.
Then press "Exchange authorization code for tokens" button and copy refresh token code. Seems like 1/gwPrtXcdqpC_pDXXXXXXXXXXXXXXXXXzvVA.
So you have client_id, client_secret and refresh_token(taken by your own auth via settings popup)
Let see javascript code:
of course, add
<script>
(function (w, d, s, g, js, fs) {
g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } };
js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
js.src = 'https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); };
}(window, document, 'script'));
</script>
Then you can use this script as example:
<script>
//CX Google Auth Process
var client_id = "111XXXXXXXXXXXXXXXXson.apps.googleusercontent.com";
var client_secret = "edXXXXXXXXXXXXXXXXabW";
function CXAuth(parameters) {
var credits= { client_secret: client_secret, grant_type: 'refresh_token', refresh_token: '1/AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXi7', client_id: client_id };
$.ajax({
type: "POST",
url: "https://www.googleapis.com/oauth2/v4/token",
contentType: "application/x-www-form-urlencoded",
data: credits,
dataType: "json",
success: function (credits) {
//console.log("CX Auth success");
gapi.analytics.auth.authorize({
serverAuth: {
"access_token": credits.access_token,
"expires_in": credits.expires_in,
"token_type": credits.token_type
},
container: 'embed-api-auth-container', //Your auth div id in html
clientid: client_id,
clientsecret: client_secret
});
}, error: function (xhr, textStatus, errorThrown) {
console.log("cx ajax post error:" + xhr.statusText);
}
});
}
gapi.analytics.ready(function () {
CXAuth();
//CX Get your ids no from https://ga-dev-tools.appspot.com/query-explorer/
var report = new gapi.analytics.report.Data({
query: {
ids: 'ga:18XXXXX', //Your ids no
//CX ga:visits,ga:sessions,ga:users for Tekil kullanıcı Sayısı-Unique user count
metrics: 'ga:pageviews', // Not unique user count
dimensions: 'ga:date',
'start-date': '2018-01-01',
'end-date': 'today'
}
});
var total = 0;
report.on('success', function handleCoreAPIResponse(resultsAsObject) {
if (resultsAsObject.rows.length > 0) {
resultsAsObject.rows.forEach(function pushNumericColumn(row) {
total = Number(total) + Number(row[1]);
});
document.getElementById("totalCounter").textContent = total;
}
});
report.execute();
var dataChart = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:18XXXXX', // <-- Replace with the ids value for your view.
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:sessions,ga:users',
'dimensions': 'ga:date'
},
chart: {
'container': 'site_statistics', //Your div id
'type': 'LINE',
'options': {
'width': '100%'
}
}
});
//CX Responsive Google Charts
window.addEventListener('resize', function () {
dataChart.execute();
});
$(document).ready(function () {
dataChart.execute();
});
});
</script>
and finally in your html like this:
<div id="embed-api-auth-container"></div>
<div id="site_statistics" class="chart"> </div>
<div id="totalCounter">0</div >
if all steps correct, you can get auto refresh token via js on your Admin Dashboard without pressing sign in button manually everytime.
Essentially, you're asking about authorizing server side on behalf of your visitors.
Various forms of this question have been asked before, so rather than re-answer I'll just send you some links:
Using Google Analytics to show subset of data for customers of web application using embed api
Google Analytics Embed API: How to retireve access token?
And here's the documentation for the auth method, which discusses the serverAuth option:
https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference#auth
I would suggest you follow this:
Go to this website: Google Analytics
SignUp for a Google Analytics Account
Go to the Admin Tab
Create a new Property (put your website URL)
Under new Property go to Tracking Info > Tracking Code, and there is a piece of code
Copy it and put in every JS file of each page you want to track in your site
Go to Reporting Tab on Google Analytics and on the left side click on Real-Time
Start seeing real-time data of visitors of your page
I've been searching about how to implement authentication/authorization in SPA's with AngularJS and ASP.NET Web API and I have one doubt. First we can implement authentication and authorization on server side with ASP.NET Identity. Then we create an Angular service to use this to authenticate a user and after that requests to Web API actions that use the Authorize attribute will be allowed.
There's still one problem. The logged in user will probably won't be allowed to access some pages of the app. Although using the app itself it won't be allowed, the HTML for the SPA is still available. If the user goes to http://website.com/app/views/notAllowedPage.html it will render in the browser. It's really not useful I know, but still I think to be a security failure, since the user shouldn't be allowed to get this HTML from the server.
Is there a way to secure this HTML or it is simply not possible?
We discussed the same problem in our developers group. Our conclusion was not to see this as a security thread.
What you want to protect is the data that is displayed, not the static "layout" of a HTML page. As long as the WebAPI services that deliver the data are secured and only allow authorized users to retrieve the data, we are safe.
Would that suit your needs as well?
We currently use this same setup.
Since we are using Angular, we don't do much with MVC itself or the Razor engine. The only things we are really doing with Razor is rendering a layout and the basic page (usually Index()).
So my recommendation is to do the same--instead of having a page website.com/app/views/notAllowedPage.html, have the user navigate to website.com/app/NotAllowed/, and secure the NotAllowedController with an Authorize attribute.
Create a service for securing your Angular htmlpage
As per the these services a guest user can't access the secure pages
Angular service
angular.module('application').factory('authorizationService', function ($resource, $q, $rootScope, $location,dataFactory) {
return {
permissionCheck: function (roleCollection) {
var deferred = $q.defer();
var parentPointer = this;
var user = dataFactory.getUsername();
var permission = dataFactory.getUserRole()
var isPermissionLoaded=dataFactory.getIsPermissionLoaded();
if (isPermissionLoaded) {
this.getPermission(permission, roleCollection, deferred);
}
else {
$location.path("/login");
}
return deferred.promise;
},
getPermission: function (permission, roleCollection, deferred) {
var ifPermissionPassed = false;
angular.forEach(roleCollection, function (i,role) {
switch (role) {
case roles.ROLE_USER:
angular.forEach(permission, function (perms) {
if (perms=="ROLE_USER") {
ifPermissionPassed = true;
}
});
break;
case roles.ROLE_ADMIN:
angular.forEach(permission, function (perms) {
if (perms=="ROLE_ADMIN") {
ifPermissionPassed = true;
}
});
break;
default:
ifPermissionPassed = false;
}
});
if (ifPermissionPassed==false) {
$location.path("/login");
$rootScope.$on('$locationChangeSuccess', function (next, current) {
deferred.resolve();
});
} else {
deferred.resolve();
}
},
isUserAuthorised: function () {
var isPermissionPassed = false;
var permission = dataFactory.getUserRole()
var isPermissionLoaded=dataFactory.getIsPermissionLoaded();
if (isPermissionLoaded) {
angular.forEach(permission, function (perms) {
if (perms=="ROLE_USER") {
ifPermissionPassed = true;
}
});
}
return isPermissionPassed;
}
};
});
and this code for your app.js where u mention your url and their controller
var application = angular.module('application', ['ngRoute']);
var roles = {
ROLE_USER: 0, //these are the roles which I want to secure from guest user
ROLE_ADMIN: 1
};
var routeForUnauthorizedAccess = '/login'; //if any unauthories user access the page the user will redirect on the login page
$routeProvider.when('/', {
templateUrl: 'view/home.html',
controller: 'homepage'
}).when('/login', {
templateUrl: 'view/loginpage.html',
controller: 'login'
}).when('/signup', {
templateUrl: 'view/signup.html',
controller: 'signup'
}).when('/dashboard', {
templateUrl: 'view/dashboard.html',
controller: 'dashboard',
resolve: {
permission: function(authorizationService, $route) {
return authorizationService.permissionCheck([roles.ROLE_USER, roles.ROLE_ADMIN]);
},
}
// the last dashboard page is access by only admin and the user who logged IN