oauth client

A boilerplate code

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="author" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> -->
  <link rel="stylesheet" href="index.css">
  <!--[if lt IE 9]>
      <script src="//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
      <![endif]-->
  <link rel="shortcut icon" href="">
</head>
<body>

  <button onclick="hello('google').login()">google</button>
  <button onclick="hello('google').logout()">logout</button>
  <!-- SCRIPTS -->
  <!--
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
      -->
  <script src="hello.all.js"></script>
  <script>
    hello.init(
      {google: "516591458871-s6jr870dbt8ep543258oaaofsl3v189v.apps.googleusercontent.com"}
    );
  </script>

  <script>
    hello.on('auth.login', function (auth) {

      hello(auth.network).api('/me').then(function (r) {
        console.log(JSON.stringify(r));
        debugger;
        var lab = document.createElement("div");
        lab.id = "pic_and_greet";
        lab.innerHTML = '<img src="' + r.thumbnail + '" /> Hey ' + r.name + '<p>'+r.aboutMe;
        document.body.appendChild(lab);
      });
    });

    hello.on('auth.logout', function () {
      var lab = document.getElementById("pic_and_greet");
      if (lab != null) document.body.removeChild( lab );
    });

  </script>

</body>
</html>

Spin up a local server

# Simple Server (to test it locally): 
$ python -m SimpleHTTPServer 5000

# Following aren't required

# Chrome Disable Security: 
$ open -a Google\ Chrome --args --disable-web-security --user-data-dir

# install pip: 
$ sudo easy_install pip

# install virtualenv: 
$ pip install virtualenv virtualenvwrapper
Advertisements

filter component

1. All urls to 1 route

Router.map(function() {
  this.route('about', {path: '/'});
  this.route('about', { path: '/*wildcard' });
});

2. Dom Manipulation

// in any controller
Ember.$('#component-x').val('My Value');

3. Adapter: rental.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  'namespace': 'api'
});

4. Template: index.hbs

<div class="jumbo">
  <div class="right tomster"></div>
  <h2>Welcome!</h2>
  <p>
    We hope you find exactly what you're looking for in a place to stay.
    <br>Browse our listings, or use the search box above to narrow your search.
  </p>
</div>

{{input value=filterText type='text' placeholder='Search City'}}
  {{#unless filteredResults.length}}
    <h4>no record matched your criteria</h4>
  {{/unless}}

  <ul>
    {{#each filteredResults as |item|}}
      <li>{{item.id}} {{item.attributes.city}}</li>
    {{/each}}
  </ul>

5. Route: index.js

import Ember from 'ember';

export default Ember.Route.extend({
  filterText: '',

  setupController(controller, model) {
    this._super(controller, model);
    controller.set('filterText', this.get('filterText'));
  },

  queryParams: {
    search: {
      refreshModel: true
    }
  },

  beforeModel: function(transition) {
    // console.log('before model: '+transition.queryParams.search);
    this.set('filterText', transition.queryParams.search);
  },

  model: function(params) {
    var endPoint = 'http://localhost:4200/api/deals';
    var results = [];

    endPoint = (params.search)? endPoint+'/city='+params.search : endPoint;

    $.ajax({
      url: endPoint,
      type: 'GET',
      accepts: 'application/json',
      success: function(data) {
        if(data.rentals) {
          data.rentals.forEach(function(deal) {
            results.addObject(deal);
          });
        } else if(data.data === 'no records found'){
          console.log('No results found');
        } else {
          data.data.forEach(function(deal) {
            results.addObject(deal);
          });
        }
      },
      error: function() {
          console.log('DEBUG: GET Deals Failed');
      },async:false
    });
    return results;
  }
});

6. Controller: index.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['search'],

  onFilterTextChange: function() {
    Ember.run.debounce(this, this.applyFilter, 0);
  }.observes('filterText'),

  applyFilter: function() {
    this.set('search', this.get('filterText'));
    console.log('search set: ' + this.get('search'));
  },
  
  filteredResults: function() {
    return this.get('model');
  }.property('search'),
});

7. Mock Response(http-mock): rentals.js

/*jshint node:true*/
module.exports = function(app) {
  var express = require('express');
  var rentalsRouter = express.Router();
  var rentals = [
      {
        type: 'rentals',
        id: 1,
        attributes: {
          title: 'Grand Old Mansion',
          owner: 'Veruca Salt',
          city: 'San Francisco',
          type: 'Estate',
          bedrooms: 15,
          image: 'https://upload.wikimedia.org/wikipedia/commons/c/cb/Crane_estate_(5).jpg'
        }
      }, {
        type: 'rentals',
        id: 2,
        attributes: {
          title: 'Urban Living',
          owner: 'Mike Teavee',
          city: 'Seattle',
          type: 'Condo',
          bedrooms: 1,
          image: 'https://upload.wikimedia.org/wikipedia/commons/0/0e/Alfonso_13_Highrise_Tegucigalpa.jpg'
        }
      }, {
        type: 'rentals',
        id: 3,
        attributes: {
          title: 'Downtown Charm',
          owner: 'Violet Beauregarde',
          city: 'Portland',
          type: 'Apartment',
          bedrooms: 3,
          image: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Wheeldon_Apartment_Building_-_Portland_Oregon.jpg'
        }
      }
    ];

  rentalsRouter.get('/', function(req, res) {
    res.send({
      rentals
    });
  });


  rentalsRouter.post('/', function(req, res) {
    res.status(201).end();
  });

  /*rentalsRouter.get('/:id', function(req, res) {
    res.send({
      '':req.params
    });
  });*/

  rentalsRouter.get('/:city', function(req, res) {
    let val = req.params.city.split("=");
    let filteredRentals = rentals.filter(function(i) {
      return i.attributes.city.toLowerCase().indexOf(val[1].toLowerCase()) !== -1;
    });

    if(filteredRentals.length>=1) {
      res.send({
        'data': filteredRentals
      });
    } else {
      res.send({
        'data': 'no records found'
      });
    }

    
  });

  rentalsRouter.put('/:id', function(req, res) {
    res.send({
      'rentals': {
        id: req.params.id
      }
    });
  });

  rentalsRouter.delete('/:id', function(req, res) {
    res.status(204).end();
  });

  // The POST and PUT call will not contain a request body
  // because the body-parser is not included by default.
  // To use req.body, run:

  //    npm install --save-dev body-parser

  // After installing, you need to `use` the body-parser for
  // this mock uncommenting the following line:
  //
  //app.use('/api/rentals', require('body-parser').json());
  app.use('/api/rentals', rentalsRouter);
};

Journal – publish bower package; setup ember mock

1. Publish Bower Package

Bower was started by twitter.
https://bower.io/docs/creating-packages/

2. Simple Ember App

Super Rentals

3. Mocks with EmberJS

EmberJS comes with ExpressJS (internally, http-mock) here are steps to setup a mock. Once setup it works like a real service & it actually be used to build REST API for your backend if it is fueled with real data.

  • generate ember project with ember-cli
  • generate an express route
    ember g http-mock destinations
  • to view: http://localhost:4200/api/destinations
  • Unlike fixtures, this helps you test your Adapter as well
  • setting up a mock response
// server/mocks/destinations.js
/*jshint node:true*/
module.exports = function(app) {
  var express = require('express');
  var destinationsRouter = express.Router();

  destinationsRouter.get('/', function(req, res) {
    res.send({
      'destinations': [
		{
			id:'001',
			loc: 'london'
		}, {
			id:'002', 
			loc: 'rotterdam'
		}, {
			id:'003', 
			loc: 'amsterdam'
		}
	  ]
    });
  });

  destinationsRouter.post('/', function(req, res) {
    res.status(201).end();
  });

  destinationsRouter.get('/:id', function(req, res) {
    res.send({
      'destinations': {
        id: req.params.id
      }
    });
  });

  destinationsRouter.put('/:id', function(req, res) {
    res.send({
      'destinations': {
        id: req.params.id
      }
    });
  });

  destinationsRouter.delete('/:id', function(req, res) {
    res.status(204).end();
  });

  // The POST and PUT call will not contain a request body
  // because the body-parser is not included by default.
  // To use req.body, run:
  //    npm install --save-dev body-parser

  // After installing, you need to `use` the body-parser for
  // this mock uncommenting the following line:
  //app.use('/api/destinations', require('body-parser').json());
  app.use('/api/destinations', destinationsRouter);
};

Built to last; Build with Ember

#01. Wildcard Route for 404

// app/router.js
Router.map(function() {
  // other routes
  this.route('page-not-found', { path: '/*wildcard' });
});
// app/templates/page-not-found.hbs
Page Not Found
{{outlet}}

#02. Helper Method

// app/helpers/increment.js
import Ember from "ember";

export function increment(integer){
  return ++integer;
}

export default Ember.Helper.helper(increment);
// app/templates/index.hbs
{{#each model as |contact index|}}
    #{{increment index}}. {{contact.title}}
{{/each}}

#03. Load a model within a Route

// app/routes/post.js
import Ember from 'ember';

var articles = [{
  id: 1,
  title: 'FirstPost',
  content: 'First Post'
}, {
  id: 2,
  title: 'About',
  content: 'About Splash'
}, {
  id: 5,
  title: 'Contact',
  content: 'You can reach us too!'
}];

export default Ember.Route.extend({
  model: function(params) {
    var index = params.post_id -1;
    return articles[index];
  }
});
// app/templates/post.hbs
Id:: {{model.id}}
title: {{model.title}}
body: {{model.content}}

Port an Ember App to Cordova

1. Pre-Requisites

1.1. Ember Cli
$sudo npm install -g ember-cli

1.2. Cordova
$sudo npm install -g cordova

1.3. Also consider
Git, Node.js (with NPM), Bower, Ember CLI, PhantomJS

2. create ember project

$ember new labs

3. include ember-cordova-cli in package.json

DevDependencies
“ember-cli-cordova”: “0.0.15”,

4. alter config/environment.js

modulePrefix: ‘hello’,
environment: environment,
baseURL: ‘/’,
locationType: ‘hash’,
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. ‘with-controller’: true
}
},

APP: {
// Here you can pass flags/options to your application instance
// when it is created
},

cordova: {
rebuildOnChange: false,
emulate: false
}

5. Generate Cordova Proj (reverse domain name)

sudo ember generate cordova-init com.hamzeen.hello –platform=android

6. Open Existing Proj

ember cordova:prepare

7. Open iOS Porject in Xcode

ember cordova:open

8. Build for target platform

$sudo ember cordova:build –environment=production –platform=android

9. Additional

9.1. full access
$chmod 777 -R /dir

9.2. To modify npmrc for proxies and npm registry
$vi ~/.npmrc

10. Live debug

visit this url on chrome
chrome://inspect/#devices

Reference:

introduction:

ember-cli-cordova
https://github.com/poetic/ember-cli-cordova

for iOS
http://dreamingin.codes/article/merging-ember-cli-cordova-and-make-it-emulate-ios-live/

http://lelandbatey.com/posts/2015/02/ember-and-cordova

Live Edit

Live edit is a Firefox extension which allows you to edit any page live on your browser. Last couple of weeks, I have been playing around with some grease monkey scripts which ultimately lead me develop a Firefox extension.

Though, Initially I wanted to develop an enteprising extension, due time constraints I chose to stick to a simple one yet, an intersting one at that. Live edit comes with a toolbar button, menu item and as a popup menu item once it’s installed and it allows you to virtually edit any page on the go.
It’s all about having fun while browsing.

On the side lines, it also helps developers to test and edit their content live on the browser which allows them to change the code only once things are perfectly done and finalized. And it also gives you the luxury of using your browser just like a simple text editor when you open up a blank page. (How is it for a change, writing on the browser?). But once you refresh the page, everything will be restored and even if you save the page after you editing it, the page saved so will not have the altered content (Obvious!!).

Anyway, the biggest threat to this extension will be, people trying to edit, take screen shots and publish it as if it’s their stuff. It’s understood this is pure violation of IP laws and I strongly advice you to refrain from doing so.

The plugin is not yet publicly listed since it is still in its review phase hopefully once it is done, it will be listed publicly, for downloads. So now you can start viewing the web as you like it. Hope you will enjoy it!.

Still, you are free to evalaute it if you have a mozilla account on,
https://addons.mozilla.org/en-US/firefox/addon/9394