Getting Auth with Cookie vs Token | AngularJS

These last few days, i’ve been working with AngularJS, dealing with RESTFull-API concept in my back end. And now, i learn to get auth with AngularJS.
The scenario is, when user login, i’ll send username and password, server with validate user credentials and send the auth that must be saved and for the next request, i had send the auth. Ok, and it drives me into Cookies vs Token. Which one i’ll use?

My senior do some research and decided to try with cookie first. But, i still want to share about this matter.

Good articles is here : http://www.angulartutorial.net/2014/05/set-headers-for-all-http-calls-in.html and http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

Ya, there some word about interceptors :

Interceptors allow you to:

  • Intercept a request by implementing the request function: This method is called before $http sends the request to the backend, so you can modify the configurations and make other actions. This function receives the request configuration object as a parameter and has to return a configuration object or a promise. Returning an invalid configuration object or promise that will be rejected, will make the $http call to fail.
  • Intercept a response by implementing the response function: This method is called right after $http receives the response from the backend, so you can modify the response and make other actions. This function receives a response object as a parameter and has to return a response object or a promise. The response object includes the request configuration, headers, status and data that returned from the backend. Returning an invalid response object or promise that will be rejected, will make the $http call to fail.
  • Intercept request error by implementing the requestError function: Sometimes a request can’t be sent or it is rejected by an interceptor. Request error interceptor captures requests that have been canceled by a previous request interceptor. It can be used in order to recover the request and sometimes undo things that have been set up before a request, like removing overlays and loading indicators, enabling buttons and fields and so on.
  • Intercept response error by implementing the responseError function: Sometimes our backend call fails. Other times it might be rejected by a request interceptor or by a previous response interceptor. In those cases, response error interceptor can help us to recover the backend call.

I found a good article here and here.

What are the benefits of using a token-based approach?

  • Cross-domain / CORS: cookies + CORS don’t play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.
  • Stateless (a.k.a. Server side scalability): there is no need to keep a session store, the token is a self-contanined entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side.
  • CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.
  • Decoupling: you are not tied to a particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.
  • Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a secure API (you have to deal with cookie containers). Adopting a token-based approach simplifies this a lot.
  • CSRF: since you are not relying on cookies, you don’t need to protect against cross site requests (e.g. it would not be possible to <iframe> your site, generate a POST request and re-use the existing authentication cookie because there will be none).
  • Performance: we are not presenting any hard perf benchmarks here, but a network roundtrip (e.g. finding a session on database) is likely to take more time than calculating an HMACSHA256 to validate a token and parsing its contents.
  • Login page is not an special case: If you are using Protractor to write your functional tests, you don’t need to handle any special case for login.
  • Standard-based: your API could accepts a standard JSON Web Token (JWT). This is a standard and there are multiple backend libraries (.NET, Ruby, Java, Python, PHP) and companies backing their infrastructure (e.g. Firebase, Google, Microsoft). As an example, Firebase allows their customers to use any authentication mechanism, as long as you generate a JWT with certain pre-defined properties, and signed with the shared secret to call their API.

Ya, as you see, JSON Web Token is quite popular i think, and you can see some example here : https://auth0.com/learn/token-based-authentication-made-easy/

Create Simple Accordion with ionic and angular

Banyak trik bisa kita lakukan untuk membuat tampilan accordion, di jquery kita bisa tinggal pakai saja function yang ada. Nah kali ini saya mau share sedikit tentang ionic dan angular. Tapi kali ini saya melakukannya dengan ionic 1, karena memang sedang ada project dengan menggunakan framework ini meski pada beberapa post sebelumnya saya sempat ngeshare tentang ionic2, tenang, yang ionic 2 saya juga terus pakai kok, nanti akan saya share.

How to get start with Ionic 2

Choosing best mobile apps technology : native vs hybrid

About ionic creator

Ionic vs OnsenUI : UI Framework for Hybrid Mobile Apps 

How to install phonegap for android apps development

Kali ini, saya membuat tampilan accordion simple saja, saya tidak banyak cuma butuh 2, jadi untuk animasinya saya cukup pakai css. Saya menggunakan ng-show ini dari angular. Oke, langsung aja kita liat code nya

Sederhana, untuk header accordionnya saya cuma pakai list divider dari component ionic, tinggal saya modif sedikit seperti ini:

the html

<ion-item class=”item-icon-right item-divider”
ng-click=”toggleGroup(‘A’)”
ng-class=”{active: isGroupShown(‘A’)}”>
<i class=”icon” ng-class=”isGroupShown(‘A’) ? ‘ion-chevron-up icon-accessory’ : ‘ion-chevron-down icon-accessory'”></i>
List Group A
</ion-item>

<ion-list>

<!– ************************* LIST GROUP A *******************************************–>
<ion-item class=”item-remove-animate item-icon-right item-accordion” ng-repeat=”list in listdata” type=”item-text-wrap” ng-show=”isGroupShown(‘A’)” href=”#/detail”>
<h2>Barang {{list .name}}</h2>
<p>{{list .message}}</p>
<i class=”icon ion-chevron-right icon-accessory”></i>
</ion-item>
</ion-list>

 

itu untuk satu group, kalo mau nambah lagi tinggal tambahin code yang sama, cuma tinggal ganti nama grupnya aja itu misal jadi isGroupShown(‘B’). So its very simple, kalo mau yang lebih kompleks, bisa ja sih, but this is easier, hhaaaaaaa..

note : ini datanya saya ngambil dari service sederhana saja, cuma array :

.service(‘listdata’, function() {
return {
lists: [
{id: “1”,name : “A”,message: “Detail Informasi A”},
{id: “2”, name : “B”,message: “Detail Informasi B”},
{id: “3”, name : “C”,message: “Detail Informasi C”},
{id: “4”, name : “D”,message: “Detail Informasi D”},
{id: “5”, name : “E”,message: “Detail Informasi E”},
{id: “6”, name : “F”,message: “Detail Informasi F”}

],
getLists: function() {
return this.lists;
},
getList: function(listId) {
for(i=0;i<this.lists.length;i++) {
if(this.lists[i].id == listId) {
return this.lists[i];
}
}
}
}

 

okey, then the css; ini penting yah buat transisi pas itemnya dibuka dan ditutup, biar lebih halus, coba liat sendiri perbedannya yah, hapus aja line yang pertama dan bandingkan hasilnya..

.list .item.item-accordion {transition: 0.09s all linear;}
.list .item.item-accordion.ng-hide {line-height: 0px;}
.list .item.item-accordion.ng-hide-add,
.list .item.item-accordion.ng-hide-remove {display: block !important;}

 

and then the .js file tinggal taruh didalam controller nya saja:

$scope.shownGroup=null; //default nutup semua

$scope.isGroupShown = function(group) {
return $scope.shownGroup === group;
};
$scope.toggleGroup = function(group) {
if ($scope.isGroupShown(group)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = group;
}
};

 

Enjoyyy, atau kalian bisa mampir kesini -> https://codepen.io/ionic/pen/uJkCz

How to get start with Ionic 2

Now, i wanna share about how to start with ionic. Official site ; http://ionicframework.com/

Ionic 2 is still in beta release but, you may want to read about ionic 1 and 2 and should you upgrade to ionic 2 or not ->  here.

First of all you have to make sure this following things already installed to your computer :

  1. Android SDK
  2. Java JDK
  3. NodeJS
  4. AntJS
  5. Cordova Latest Version

And now, we’re ready to start about ionic. http://ionicframework.com/getting-started/

For you who just heard about ionic, you can visit my previos post about ionic right here.

We use Nodejs command line tools to run ionic command , you can read more here https://www.npmjs.com/package/ionic

  1. Install ionic
    $ npm install -g ionic@beta
  2. Create Project
    use –v2 to create ionic 2 project, if you do not add this line, it will install ionic 1 by default. ex : $ ionic start myApp ==> ionic 1 version

    $ ionic start myApp [template] --v2
    $ ionic start myApp tabs --v2 
    ionic create porject

    ionic create porject

    I can’t believe i’m having trouble when start ionic project, the installation is stuck on “installing npm packages…” this command try to call the npm packages source but i’ve been waiting for an hour and theres nothing changed. I terminated it, and then try to start a project test again and still the same. My friend, Hadi, wait for it, so long but end up with an error. My senior said, how about restart the PC? Then me and my friend doing that, and still failed. And then, we both try to uninstall the cordova, the ionic again and when start project it is still failed. We spent the day by doing that and still not working. I can’t believe i had something trouble like this, so frustating and finally,  i think this is about the connection -_- Okay, i start again this day. And i try to use my own connection instead of office’s. And i am get through it. Oh my god, i can’t belive, my senior said: ya, because office connection is too slow -_-

  3. Add platform
    $ cd myApp
    $ ionic platform add android
    
    $ ionic build android
    
    Oh, and let me show you my ionic info by run this command -> $ ionic info

    ionic info

    ionic info

  4. Emulate project
    $ ionic emulate android
    
    
  5. Run Project
    $ ionic run android
    
    
  6. Run in browsers
    $ ionic serve or $ ionic serve lab
    
    Next, i have to learn the components~ okay, noted! start from today yo! :D
  7. And here some commands that can help you :
    $ ionic g page detail -> will generate your page named 'detail' . A folder 'detail' and by contain detai.html, detail.js and detail.scss like this one :
    
    g page
    
    $ ionic g provider mydata -> will add new file named "mydata.js" under provider folder
    

    provider

Cara Menginstall Phonegap untuk Android Apps Development

Screens are small, apps are big, and life as we know it is on its head again. In a world that’s increasingly social and open, mobile apps play a vital role, and have changed the focus from what’s on the Web, to the apps on our mobile device. Mobile apps are no longer an option, they’re an imperative. You need a mobile app, but where do you start?

Sebenarnya build hybrid apps itu gampang aja kok, yg penting adalah bisa sampai running appsnya, jadi prepare apa apa saja yang kita butuhkan. Like node.js, ants, phonegap dll.

Ini singkat saja ya, hehe, untuk instalasi phonegap sampai bisa run di android Emulator.

  1. Yang pertama dan utama, wajib punya android sdk.  Kalau belum punya, bisa download di http://developer.android.com/sdk/index.html –
  2. Java SDK latest version
  3. Install node.js, ini disini -> http://nodejs.org/download/
  4. Install phonegap, liat docsnya phonegap nih -> http://phonegap.com/install/
    1. Setelah berhasil install nodejs, lalu buka nodejs command prompt.. emm, ini command promt nya node js ya, jadi ntar setelah install nodejs, trs search aja command prompt dari start menu, pilih yg nodejs command prompt.
    2.  Kemudian Jalankan : npm install -g phonegap , ntar dia ngedownload, tunggu aja sampe selesai.
    3. Create apps? Liat lebih lengkapnya di CLI interface ini : http://docs.phonegap.com/en/edge/guide_cli_index.md.html#The%20Command-Line%20Interface
    4. Contoh create project, misal saya buat di drive D, masuk ke dir D, so

      C:\Users\Feni\ D:
      D:\ phonegap create hello com.example.hello HelloWorld
      Cek d drive D, akan ada folder hello 😀

      Oke, sampai sini udah berhasil install phonegap dan create project helloworld di drive D. Yang selanjutnya caranya biar bisa run d emulator kitah 😀

  5. Oiya, download juga  http://ant.apache.org/, extract aja di C:\.
    Dan ini dia link downloadnya => http://www.mediafire.com/download/0v4cmor7s2188m2/apache-ant-1.9.3-bin.zip
  6. Kalo udah add path nya di ->
    Buka explorer, klik kanan My computer -> Properties -> Advanced System Settings -> Pilih Tab Advaced -> Klik Environtment variables.
    1. Saya menambahkan 3 path untuk Android SDK, ants,sama java sdk tadi 😀
    2. Caranya, klik new aja, terus isikan variable name dan value nya:

    Misal kaya punya saya ini :

    ANDROID_HOME itu path ke sdknya, misal punya saya ,
    [variable name -> value], seperti dibawah ini:
    D:\Masandro Dev\adt-bundle-windows-x86-20130917\sdk
    JAVA_HOME -> C:\Program Files (x86)\Java\jdk1.6.0_22
    ANT_HOME -> C:\apache-ant-1.9.3

    And finally, EDIT variable PATH, valuenya menjadi :

    C:\Users\Feni\AppData\Roaming\npm;%JAVA_HOME%\bin;%ANT_HOME%\bin;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools

    Perhatikan ada tambahan2 dibelakangnya, /bin dan untuk ANDROID_HOME di tambah dua kali, untuk tools sama platform-tools 😀

    Kalo udah, saatnya mencoba menjalankan di emulator kita.  Kalo download yg bundle dari developer.android.com ada AVD nya, bisa add player dan play emulator seperti biasa dari situ.

    Tapi kalo saya lebih suka pake emulator dari Genymotion, lebih ringan dan lebih cepat soalnya 😀 Caranya tinggal mampir aja ke genymotion.com – register, kemudian download genymotion, kalo temen2 pake windows, pilih yg sekalian bundlded sama VirtualBoxnya.

    Install, kemudian login. Lalu klik +Add, nanti akan muncul list device yg disediakan oleh genymotion, pilih kemudiandownload emulator sesuai yang temen2 inginkan, banyak kok pilihannya. 🙂  Ini screenshot punya saya 😀

    Kalo udah, pilih emulator yg mau dijalankan , lalu Play , terus buka command prompt.
    Masuk ke dir project yang kita buat tadi, kalo saya berarti :

    D:\hello>

    Lalu jalankan perintah :

    D:\hello> phonegap platform add android

    D:\hello> phonegap run android

    tunggu beberapa saat, nanti dia akan nginstall ke emulator kita, ingat, emulatornya harus udah jalan dulu ya ^_^

    sampe sini sih harusnya udah bisa, muncul splash screen helloworld gitu. Oke, kurang lebih seperti ini:


    Selamat Mencoba ^_^

  7. Oya, buat yg mau develop, disini saya pake jquery, tp agak berat ya kalo buat mobile apps.
    Saran saya , bisa coba pake AngularJS atau Backbonejs + Topcoat.css , oh yaa.. ada OnsenUI itu juga keren banget, ringan, great UX,  HTML5 UI Framework, Onsen work with jquery and angularJS, nah , keren kan. Saya udah nyoba, dan emang simple n easy to use, nice design, multiscreen support.Great.

    Oiya satu lagi, ada ionic framework , masih beta sih, but i keep my eyes on it. Ini juga bakal keren nih 😀

 

Seach data using onkeyup event jquery

Sedikit mau bagi-bagi tips nih buat agan-aganwati yang hobby coding dan bereksperimen… heuheu
Jadi di website maupun mobile apps kan biasanya ada search box dari list yang ada, bisa kita filter, ini beda sama suggestion ya 🙂 Ini konsepnya cuma get value dari search box dan dicocokin sama list yg kita punya, kalo ga cocok ya di hide. Simple aja 🙂

Misal kita punya html seperti ini :

 

<input type="text" id="search">
<p class="red">Angin</p>
<p class="red">Feni</p>
<p class="red">Dendi</p>
<p class="red">Mutia</p>
<p class="red">Alvita</p>
<p class="red">Fian</p>

Nah, untuk filternya saya pake jquery, langsung disimak aja 😀

Event yang saya gunakan adalah onkeyup dimana function pada onkeyup akan dilakukan secara otomatis saat user melepaskan tombol pada keyboard, jadi selama kita masih menekan tombol pada keyboard aksi tidak akan dijalankan. Konsepnya, kita menyeleksi semua elemen yang memiliki class red, kemudian dari elemen tersebut akan dicocokkan dengan keyword search dengan function indexOf, jika tidak cocok maka elemen tersebut akan di sembunyikan.

     $('#search').on('keyup', function(){
         var key = $(this).val().toLowerCase(); //ambil nilai dari inputtext search, dijadikan huruf kecil semua
         var elements = $('.red');   // select semua elemen yang memiliki class "red"
         for (var i=0; i<elements.length; i++){
			var elem = $(elements[i]);
			var nama = elem.text().toLowerCase(); //text dari selected element ke -i 
			if((key !== '') && (nama.indexOf(key) < 0)) 
//cek jika key kosong, dan ada kesamaan dengan text nama menggunakan function indexOf dimana jika tidak terdapat karakter yang sama dengan key, maka return nya adadalah -1, means, jika < 0 maka tidak ditemukan kesamaan
				{
				    elem.hide(); //hide element
				} 
             else 
                 {  //karakter yang dicari ditemukan,
                     elem.show(); //show element
                 }
		}
         
     });

Sekian, dan semoga membantu ^_^
Untuk demonya bisa dilihat disini ^_^