Reputation: 486
In Google apps script documentation, there is a page about Private functions on server side. That should explain that without private functions, the server code is visible from the user browser. Can anybody explain how you can see such server side functions in a browser ? Thanks
See : https://developers.google.com/apps-script/guides/html/communication#private_functions
Upvotes: 8
Views: 12739
Reputation: 3004
Using IIFEs with closures
counter.gs
const Counter = (function() {
const count = 0; // Private variable
function increment() {
count++; // Accessing the private variable
console.log('Count:', count);
}
function decrement() {
count--; // Accessing the private variable
console.log('Count:', count);
}
return {
increment,
decrement
};
})();
main.gs
Counter.increment(); // Output: Count: 1
Counter.increment(); // Output: Count: 2
Counter.decrement(); // Output: Count: 1
In the code above, an IIFE is used to create a closure that encapsulates the count variable and two inner functions: increment and decrement. The count variable is private and can only be accessed by the inner functions.
The IIFE immediately executes, returning an object with references to the inner functions (increment and decrement). These functions have access to the private count variable due to the closure.
Upvotes: 2
Reputation: 17752
The server code is never visible on the user's browser, only the functions names. Private functions hides those names, but more importantly they remove the ability from the frontend to call them directly.
In other words, private functions allow you to define your backend entry-points, preventing a malicious user to bypass some checks you might have and call your "internal" functions directly.
To showcase how easy it is to see the name and call any non-private backend function, I've put up this example where we inspect the google.script.run
object:
function myFunction() {}
function anotherFunction() {}
function privateFunction_() {}
function doGet() {
return HtmlService.createHtmlOutput(
'<p id="output"></p>'+
"<script>var s = ''; for( var prop in google.script.run ) s+=prop+'<br>';"+
"document.getElementById('output').innerHTML = s;</script>"
);
}
Here's this example published: https://script.google.com/macros/s/AKfycbzk0d03iB1O3vVYVD_U7eONM357iOPlAn7RFxAeZKx34q1Ones/exec
And its source code (same as above): https://script.google.com/d/1WMY5jWblGl8U84WvVU_mZjHDg-6rGOoOPnKMF6m2bS_V-2g6IChBVDrg/edit
-- to address a question in the comments
The doGet
function cannot be made private since its name is fixed/predefined. But that is not really a problem as this function is supposed to be an entry point anyways, and since you expect it to be called from the users' browsers and can do your parameters checks and such accordingly.
Upvotes: 8