Friday, September 25, 2015

Mastering Your Inbox with the Gmail JavaScript API

In this article, we’re going to build a basic Gmail inbox and message viewing app using the Gmail RESTful API. The purpose of this article is to give you a good starting point to create cool new JavaScript apps of your own using this API. We’re going to use jQuery and Bootstrap to take some weight out of the code base so we can focus on getting something working quickly without worrying about cross-browser JavaScript inconsistencies and basic styling.

As ever the complete code for this article can be found on our GitHub repo.

Gmail Logo

Enabling the Gmail API on Your Google Account

First off, we need to enable Gmail API access to get our API credentials. To do this, we need to visit Google’s Developer Console in our favourite web browser. From there, we need to create a project (or choose an existing one) and go to the APIs section. Choose “Gmail API” under the Google Apps APIs section and click the “Enable API” button.

Now we need to create two sets of credentials, one for an OAuth 2.0 client ID for a web application and the other to create a browser API key. This can be done in the credentials section of the Google Developer Console by clicking the “Add Credentials” button.

Add credentials screenshot

For the browser API key we need to only fill in the “name” field. However, for production I’d recommend adding a HTTP referrer (this will prevent abuse of our API key from non-authorized domains). For the OAuth 2.0 client ID we must enter at least one authorized JavaScript origin. For a local development environment this will likely be http://localhost or similar. We do not need to enter an authorized redirect URI.

Once we’ve filled in the necessary fields we should be able to see our credentials back in the Credentials section. Keep this info open in a browser tab for later.

Connecting to the Gmail API

[author_more]

Even though the Gmail API is a standard REST API using OAuth 2.0 we recommend using Google’s own JavaScript libraries for connecting to and working with any Google-authored APIs. This is because Google has already packaged up authentication logic and the required dependencies into a single include file — less work for us!

So, first things first – let’s set up our HTML file which we’re going to use as the base of our app. For the purpose of this app we’re going to include all of our code in a single HTML file. In a production environment Id recommend splitting out HTML, CSS and JavaScript into separate files.

<!doctype html>
<html>
  <head>
    <title>Gmail API demo</title>
    <meta charset="UTF-8">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
    <style>
      .hidden{ display: none; }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>Gmail API demo</h1>

      <button id="authorize-button" class="btn btn-primary hidden">Authorize</button>

      <table class="table table-striped table-inbox hidden">
        <thead>
          <tr>
            <th>From</th>
            <th>Subject</th>
            <th>Date/Time</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>

    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <script type="text/javascript">
      var clientId = 'xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
      var apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
      var scopes = 'http://ift.tt/1lIF7p7';
    </script>

    <script src="http://ift.tt/19G1Hp3"></script>
  </body>
</html>

Right at the bottom (above the closing </body> tag) is where we include Google’s JavaScript client library. Notice the query string on the end, this contains the callback function which will be executed once the script has loaded — we’ll use that to initialize our app a little later. Just above that is where we are defining our API credentials, we need to paste these from the Google Developer Console Credentials section. We also define which permissions we’ll require from the user, these are known as scopes. For the purpose of this app we only require read-only Gmail access. It’s good practice to request as few permissions as possible from the user — this provides the user peace of mind that we’re not going to do something nefarious like send emails on their behalf without them knowing.

Other than that we’ve got a button which will allow the user to authorize us to access their Gmail account, and we’ve also stubbed out a table to hold our inbox data once we fetch it. And, as mentioned earlier, we’ve included the necessary files for jQuery and Bootstrap.

Authenticating the User

Now we’re going to provide a mechanism for the user to authenticate us to access their Gmail account. As mentioned above, we need to build out a function named handleClientLoad() which will automatically be called once Google’s JavaScript client library has loaded into the page. This function will then call a chain of other functions which will eventually lead us to fetching their inbox.

function handleClientLoad() {
  gapi.client.setApiKey(apiKey);
  window.setTimeout(checkAuth, 1);
}

function checkAuth() {
  gapi.auth.authorize({
    client_id: clientId,
    scope: scopes,
    immediate: true
  }, handleAuthResult);
}

function handleAuthClick() {
  gapi.auth.authorize({
    client_id: clientId,
    scope: scopes,
    immediate: false
  }, handleAuthResult);
  return false;
}

function handleAuthResult(authResult) {
  if(authResult && !authResult.error) {
    loadGmailApi();
    $('#authorize-button').remove();
    $('.table-inbox').removeClass("hidden");
  } else {
    $('#authorize-button').removeClass("hidden");
    $('#authorize-button').on('click', function(){
      handleAuthClick();
    });
  }
}

function loadGmailApi() {
  gapi.client.load('gmail', 'v1', displayInbox);
}

We should insert this code directly below where we set the API credentials, within the same SCRIPT block.

To summarise the process this chain of function calls goes through:

  1. handleClientLoad() simply sets the API key and passes off to checkAuth() after 1 millisecond.
  2. checkAuth() checks if the user has previously authenticated our app with Google. Setting the immediate parameter to true here means that we do not prompt the user with a login/permissions modal if they are not authenticated. We then pass the authentication result to handleAuthResult().
  3. handleAuthResult() then does one of two things; if the user is already authenticated it’ll load the Gmail API using loadGmailApi(), alternatively it’ll display the authorize button on the UI and attach a click event to it which will trigger handleAuthClick()
  4. handleAuthClick() simply executes the same authentication function as checkAuth() but will present the user with a login/permissions modal. Once the user authenticates the same handleAuthResult() function from before is triggered.
  5. Once those series of functions have been executed and the user has authenticated we should always find ourselves at the loadGmailApi() function. This simply loads the Gmail API functionality from Google’s JavaScript client library and then calls our displayInbox() function.

Continue reading %Mastering Your Inbox with the Gmail JavaScript API%


by Jamie Shields via SitePoint

Day of the Dead

opl-small

Lovely colorful and illustrated One Pager promoting 'The Multicultural Day of the Dead Festival'. Lovely touch on mobile when clicking the skull navigation button that turns the eyes into x's. Top draw work once again from Grain & Mortar.

by Rob Hope via One Page Love

Watch: Compiling Sass using grunt-contrib-watch

Learn how to use grunt’s sass, watch, and connect plug-ins to create a build system that opens a browser, and updates any change in html, or Sass code live in the browser.

Loading the player...

Continue reading %Watch: Compiling Sass using grunt-contrib-watch%


by Thomas Greco via SitePoint

The Themes

OPL-Small

Launching soon page for upcoming minimal theme shop 'The Themes'.

by Rob Hope via One Page Love

A Visual Introduction to Machine Learning

opl-small

Informational One Pager filled with statistics and infographics explaining how effective "Machine Learning" has become.

by Rob Hope via One Page Love

Quickly Detect Hacked Files via CRON/PHP: SuperScan

As a Certified Ethical Hacker, I'm fully aware that prevention is the best tactic to prevent hackers but, should one break through, the sooner you know it, the quicker you can act to limit the damage.

A while back, I presented a script called hashscan, designed to track site changes. Executed via a daily CRON, the script reads the files for a specified directory (e.g., an account’s public_html directory on a server), generates hashes (for files with specific file extensions), and compares them with the previous scan’s hashes stored in a database. It's a great way for site owners to be alerted to files that have been added, altered or deleted by a hacker.

In this article, I'll present an updated version of the script, called SuperScan.

Benefits of SuperScan

The primary benefit is that SuperScan will report any changes to files in an account whether the file change is an addition, alteration or deletion. SuperScan was designed not to overwhelm the webmaster. It only provides a report of changes since the last scan (the default is one hour, but can be configured via CRON) and a summary report (daily by default, although, again, it can be configured via CRON).

Because the scan of a 1500 file account takes ~0.75 seconds, SuperScan can be run frequently without affecting server performance.

To support forensic investigation, the file last modified date and time are held in the database, along with the hash value of the most recent scan (and prior scan for altered files).

The scanner file need not be changed, as all variables are set within a required configure script. It's in the configure script where you can select specific (or ALL) file extensions to be scanned or, if ALL, the file extensions to omit. Additionally, you may specify directories which the scanner will not scan.

While the SuperScan files can be tested within a webspace, I recommend that it be moved outside the webspace for production use via CRON to protect against casual hackers.

Finally, a curious additional benefit is that changes in (extensionless) error_log files are captured and can direct the webmaster’s attention to coding problems that have slipped through the testing procedures.

Continue reading %Quickly Detect Hacked Files via CRON/PHP: SuperScan%


by DK Lynn via SitePoint

Create a Mobile App Using Famo.us and Angular