OAUTH gives a flexibility to choose the some of the Largest Data providers Example: Facebook and Google to Authenticate our Application user on our behalf. Other cool things are not just Authentication we can also request for user Profile details, friends etc.
Most of the times for an user registration we might just need Profile information like: name, email, profile pic, gender etc.. So as you can see by now we can SKIP the large forms for registration and login and JUST with a button click it takes you directly to the content no hassle.
So how to make this happen? Simple register your App with the Providers, basically they ask you to create an App on their developer sites. Once created an App you will have access to some tokens and keys which further can be used in the client Apps for Authentication and fetching other informations.
Here are the labels in this Tutorial to follow along:
- What’s the out come of this tutorial?
- Create an App on Facebook and Google and get the Keys for OAuth
- Creating a Basic App layout using IONIC
- Adding functionality with AngularJS
- User session using $cookieStore
- Wrapping up
1. What’s the out come of this tutorial?
We are going to create a simple Application with two screens,
- Welcome/Login screen: Displaying the App logo and social login buttons
- Dashboard/Profile: Displaying the logged in user details.
Here is the Demo URL check out: http://techiedreams.com/demos/oauth-ionic-angular/
Download the Sources from GitHub: https://github.com/chanusukarno/Angular-Ionic-OAuth
Other tips also covered with the Sample App:
- Client session maintenance using Cookies
- Profile cover design with Blurred-Glassy-Scaled effect
Prerequisites: Please check out some of the basic tutorials on Ionic and AngularJS, before jumping further in to this tutorial:
AngularJS: http://techiedreams.com/category/angularjs/
Ionic Framework: http://techiedreams.com/category/ionic-framework/
2. Create an App on Facebook and Google and get the Keys for OAuth
Facebook:
Video:
Step 1: Goto https://developers.facebook.com/ and login
Step 2: From the Left menu select Manage Apps under Developer
Step 3: User My Apps select Add a New App
Step 4: From the popup select Website
Step 5: Type in a name for the App and click Create New Facebook App ID
Step 6: Choose category form the Popup and Click Create App ID
Step 7: Enter the Captcha and click Submit
Now we are done with App creation. Go and setup other features.
Step 8: Under Tell us about your website Enter your website URL:
While testing under development you can use the local URL itself ex:
http://localhost:8100/
Later when published we need to change update this URL to the server address. And click Next.
Now copy the App ID and replace it in the index.html and Test the App
ionic serve.
Not done yet! Now the can only be tested by you, follow along to make it available for general public:
Step 9: Go to home page https://developers.facebook.com/ refresh now under My Apps we see our new App, select it.
Step 10: Under the Left Menu Select Status & Review
Step 11: When you try to switch that button it will ask you setup a valid email. Goto Settings and set a valid email then return to Status & Review and Switch the button.
Additionally Goto App Details and setup a logo for your App and other information.
Google+:
Video:
Step 1: Goto https://console.developers.google.com/project
Step 2: Login to with gmail account and Click Create Project
Step 3: Enter project name in the Popup and click create
Step 4: In the left Menu under API’s and auth select APIs
Step 5: Under Browse APIs Search for Google+ and turn it on
Step 6: In the left Menu under API’s and auth select Credentials
Step 7: It will ask you to first setup consent screen[Screen to setup about your App], click Configure consent screen
Step 8: Select email address, Give a name to Product, Optionally you can set a home page url and a URL to your App logo and Save
Step 9: Now give your App url under Create Client id and Click Create client ID
Step 10: Under public API access in the same screen click Create new Key
Step 11: Select Browser key from popup and enter your URL Ex:
http://localhost:8100/*[* indicates any subfolder] and click Create new Key
Note: For development you can enter local address and while in Production update this urls to the servers
Copy the API KEY and replace it in Index.html Then again copy the CLIENT ID and in your controller replace the existing and Test the App
ionic serve
3. Creating a Basic App layout using IONIC
Firstly setup a new ionic project, follow this tutorial for instructions: http://techiedreams.com/getting-started-with-ionic-framework/
Then will design our welcome page, where will have a background image and app logo and login options at the center:
welcome.html
<ion-view title="" id="welcome-view" hide-nav-bar="true"> <ion-content> <div class="logo-welcome"></div> <div class="login-btns"> <div id="social-links"> <ul> <li ng-click="fbLogin()"><span class="ifacebook"><img src="img/social-icons/facebook.png"></span><a href="#" class="afacebook">sign in with facebook</a></li> <li ng-click="gplusLogin()"><span class="igoogleplus"><img src="img/social-icons/googleplus.png"></span><a href="#" class="agoogleplus">sign in with google+</a></li> </ul> </div> <hr id="login-divider" /> <div id="login-reg"> <button id="btn-login" class="button button-clear button-positive uppercase">Login</button> <button id="btn-reg" class="button button-clear button-positive uppercase">Register</button> </div> </div> </ion-content> <div id="footer" class="bar bar-footer"> <div class="title em-footer-title">© TechieDreams</div> </div> </ion-view>
For this layout we don’t need a header so we can set
hide-nav-bar="true"on <ion-view>.
Then we add an ul to hold our social login buttons.
Then below the social buttons we add two buttons for email login and registration.
dashboard.html
<ion-view> <ion-header-bar class="bar-header bar-positive"> <div class="title uppercase">Welcome</div> <button class="button button-clear" ng-click="logout()">Logout</button> </ion-header-bar> <ion-content> <div class="list"> <div class="profile-container"> <!--<div id="em-profile" class="item">--> <!-- <img src="img/ionic.png"> --> <div ng-if="user.profilePic" class="profile-pic" ng-style="{'background-image': 'url(' + user.profilePic + ')'}"></div> <div ng-if="!user.profilePic" class="profile-pic" style="background-image: url(img/profile-pic-default.png)"></div> <!--</div>--> <div id="myDiv"> <div id="color"> <div id="effect"></div> </div> </div> <div class="profile-background" ng-style="{'background-image': 'url(' + user.profilePic + ')'}"></div> </div> <div class="list"> <label class="item item-input field-disabled"> <span class="input-label">Email</span> <input ng-model="user.email" type="text" placeholder="user@gmail.com"> </label> <label class="item item-input"> <span class="input-label">Display Name</span> <input ng-model="user.name" type="text" placeholder="Chanu Sukarno"> </label> <label class="item item-input"> <span class="input-label">Country</span> <input ng-model="user.country" type="text" placeholder="INDIA"> </label> <label class="item item-input"> <span class="input-label">Phone</span> <input ng-model="user.phone" type="text" placeholder="+91 8123595959"> </label> <label class="item item-input"> <span class="input-label">Birthday</span> <input ng-model="user.dobObj" type="date" placeholder=""> </label> <label class="item item-input em-gender"> <span class="input-label">Gender</span> <ion-checkbox class="em-gender-cb" ng-model="isMale" ng-change="isMale ? user.gender='M' : user.gender = 'F'; isFemale = false" ng-checked="user.gender === 'M'">Male</ion-checkbox> <ion-checkbox class="em-gender-cb" ng-model="isFemale" ng-change="isFemale ? user.gender='F' : user.gender = 'M'; isMale = false" ng-checked="user.gender === 'F'">Female</ion-checkbox> </label> </div> </div> </ion-content> </ion-view>
Our dashboard in this example its rather a Profile where it holds user info like:
- Display Name
- Country
- Phone
- DOB
- Gender
Ionic has default styles available for all the components but for positioning on desired locations we need to write our own CSS.
Here is out final styles.css
/* Empty. Add your own CSS if you like */ body { font-family: 'Roboto', serif; } #welcome-view { background: url(../img/welcome_bg.png) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; } .logo-welcome { width: 120px; height: 120px; margin: 100px auto 60px auto; background: url(../img/ionic.png) no-repeat; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; } hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; } .login-btns { width: 250px; margin: 0 auto 0 auto; } #btn-reg { float: right; } #login-divider { margin: 40px 0 10px 0; } #footer { background: #5A5A5A; opacity: 0.4; color: #fff; } .uppercase { text-transform: uppercase; } #btn-reg, #btn-login { color: white; } .em-small { font-size: 16px; text-decoration: none; } .bar .title { font-weight: bold; text-align: center !important; } .em-padding-header { padding: 2px; } .profile-container { position: relative; padding: 35px; background-color:lightblue; } .profile-background { position:absolute; top:-20%; left:-20%; width:140%; height:140%; z-index:1; background-size: cover; -webkit-filter: blur(30px); -moz-filter: blur(25px); -o-filter: blur(25px); -ms-filter: blur(25px); filter: blur(25px); opacity: 0.65; } .profile-pic { position:relative; z-index:5; text-align: center; height: 95px; width: 95px; background-size: cover; display: block; margin: 0 auto 0 auto; border-radius: 100px; -webkit-border-radius: 100px; -moz-border-radius: 100px; } .em-gender .item-checkbox { padding-left: 50px !important; font-size: 14px; border-width: 0; padding: 10px 0px 10px 0px; margin: 0px; } .platform-android ion-popover-view.fit { margin-top: 10px !important; }
Cool we now have our UI setup. Lets add the functionality to it now.
4. Adding functionality with AngularJS
Facebook or Google allows you to load the oauth js library dynamically, In the sense the initial loading time of your application doesn’t depend on the oauth libraries.
Also we need to initialize oauth with the keys we stored in the first step.
In the index.html we added this script to initialize and load the SDK dynamically:
<script> // Facebbok OAuth init window.fbAsyncInit = function () { FB.init({ appId: '1529225140628860', // Replace the App ID with yours status: true, // check login status cookie: true, // enable cookies to allow the server to access the session xfbml: true // parse XFBML }); }; // Load the SDK asynchronously (function (d) { var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) { return; } js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); // Facebbok OAuth init - END // Google OAuth Init (function () { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); function onLoadCallback() { // Replace the API key with yours gapi.client.setApiKey('AIzaSyC5JgBIrjOGKDAIZLcsVHvgkjjGkkrZTqk'); gapi.client.load('plus', 'v1', function () { }); } // Google Oauth Init - END </script>
And in our controller we add this script to query the Facebook and Google to get user details. Code is commented where necessary.
var oauthApp = angular.module('oauthApp.controllers', []); oauthApp.controller('welcomeCtrl', function ($scope, $state, $cookieStore) { /** * SOCIAL LOGIN * Facebook and Google */ // FB Login $scope.fbLogin = function () { FB.login(function (response) { if (response.authResponse) { getUserInfo(); } else { console.log('User cancelled login or did not fully authorize.'); } }, {scope: 'email,user_photos,user_videos'}); function getUserInfo() { // get basic info FB.api('/me', function (response) { console.log('Facebook Login RESPONSE: ' + angular.toJson(response)); // get profile picture FB.api('/me/picture?type=normal', function (picResponse) { console.log('Facebook Login RESPONSE: ' + picResponse.data.url); response.imageUrl = picResponse.data.url; // store data to DB - Call to API // Todo // After posting user data to server successfully store user data locally var user = {}; user.name = response.name; user.email = response.email; if(response.gender) { response.gender.toString().toLowerCase() === 'male' ? user.gender = 'M' : user.gender = 'F'; } else { user.gender = ''; } user.profilePic = picResponse.data.url; $cookieStore.put('userInfo', user); $state.go('dashboard'); }); }); } }; // END FB Login // Google Plus Login $scope.gplusLogin = function () { var myParams = { // Replace client id with yours 'clientid': '18301237550-3vlqoed2en4lvq6uuhh88o2h1l9m70tr.apps.googleusercontent.com', 'cookiepolicy': 'single_host_origin', 'callback': loginCallback, 'approvalprompt': 'force', 'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read' }; gapi.auth.signIn(myParams); function loginCallback(result) { if (result['status']['signed_in']) { var request = gapi.client.plus.people.get({'userId': 'me'}); request.execute(function (resp) { console.log('Google+ Login RESPONSE: ' + angular.toJson(resp)); var userEmail; if (resp['emails']) { for (var i = 0; i < resp['emails'].length; i++) { if (resp['emails'][i]['type'] == 'account') { userEmail = resp['emails'][i]['value']; } } } // store data to DB var user = {}; user.name = resp.displayName; user.email = userEmail; if(resp.gender) { resp.gender.toString().toLowerCase() === 'male' ? user.gender = 'M' : user.gender = 'F'; } else { user.gender = ''; } user.profilePic = resp.image.url; $cookieStore.put('userInfo', user); $state.go('dashboard'); }); } } }; // END Google Plus Login });
5. User Session using $cookieStore:
We use $cookieStore from angular-cookies.js, to setup user session when he logs in. On every route change will look if user is authenticated or not. Here is simple script for maintaining session with $cookieStore:
// App.js var oauthApp = angular.module('oauthApp', ['ngCookies', 'ionic', 'oauthApp.controllers']); oauthApp.run(function ($rootScope, $cookieStore, $state) { // Check login session $rootScope.$on('$stateChangeStart', function (event, next, current) { var userInfo = $cookieStore.get('userInfo'); if (!userInfo) { // user not logged in | redirect to login if (next.name !== "welcome") { // not going to #welcome, we should redirect now event.preventDefault(); $state.go('welcome'); } } else if (next.name === "welcome") { event.preventDefault(); $state.go('dashboard'); } }); });
Note: ngCookies module should be added as a dependency before using $cookieStore.
Once user logs out we can remove the user data from the cookies, so our dashboardCtrl will be as follows:
// Dashboard/Profile Controller module.controller('dashboardCtrl', function ($scope, $window, $state, $cookieStore) { // Set user details $scope.user = $cookieStore.get('userInfo'); // Logout user $scope.logout = function () { $cookieStore.remove("userInfo"); $state.go('welcome'); $window.location.reload(); }; });
6. Wrapping up
We now have Facebook and Google+ login system integrated in our Application. Its quite simple to include other OAuth systems also, a similar procedure try it out. Any quires post in the comments.
Subscribe & Share Thanks!
You may also like
The post Facebook and Google OAuth with IONIC and AngularJS appeared first on TechieDreams.