RahinRahi

Ionic 2 Typescript Sample

Dec 18th, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //E.g Github comment "login, facebook login , Google login feature added"
  2. import {Component} from '@angular/core';
  3. import {IonicPage, NavController, NavParams, ModalController, Events, Platform} from 'ionic-angular';
  4. import {FormBuilder, FormGroup, Validators, AbstractControl} from '@angular/forms';
  5. import {RemoteServiceProvider} from '../../providers/remote-service/remote-service';
  6. import {RegistrationPage} from '../registration/registration';
  7. import {HomePage} from '../home/home';
  8. import {LoginhelpPage} from '../loginhelp/loginhelp';
  9. import {GooglePlus} from '@ionic-native/google-plus';
  10. import {Facebook} from '@ionic-native/facebook';
  11. import {SocialregPage} from '../socialreg/socialreg';
  12. import {OneSignal} from '@ionic-native/onesignal';
  13.  
  14. /**
  15.  * Page for normal login, facebook login , Google login
  16.  * Add by Rahi
  17.  * Date : 8th nov, 17
  18.  */
  19. @IonicPage()
  20. @Component({
  21.     selector: 'page-login',
  22.     templateUrl: 'login.html',
  23. })
  24. export class LoginPage {
  25.  
  26.     pages: any;
  27.     loginForm: FormGroup;
  28.     submitAttempt: boolean = false; // bool var for to set and show error on button click
  29.     registrationPage = RegistrationPage;
  30.     isfbLoggedIn: boolean = false;
  31.     onesignalplayerid = ''
  32.     onesignaltoken = ''
  33.  
  34.     constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder,
  35.         public remotService: RemoteServiceProvider, public modalCtrl: ModalController, private storage: Storage
  36.         , public events: Events, private fb: Facebook, private googlePlus: GooglePlus, private oneSignal: OneSignal, platform: Platform) {
  37.  
  38.         //Initialize login form validation
  39.         this.loginForm = formBuilder.group({
  40.             username: ['', Validators.compose([Validators.minLength(4), Validators.maxLength(50), Validators.required])],
  41.             password: ['', Validators.compose([Validators.minLength(4), Validators.maxLength(20), Validators.required])]
  42.         });
  43.  
  44.         window.localStorage['fbprofileinfo'] = ''; // make previously stores fb info empty
  45.  
  46.         // if it is in real device get onesignal player ID for push notification
  47.         if (platform.is('cordova')) {
  48.  
  49.             this.oneSignal.getIds().then((ids) => {
  50.                 // console.log("One signal ids"+ids.userId);
  51.                 this.onesignalplayerid = ids.userId;
  52.                 this.onesignaltoken = ids.pushToken;
  53.  
  54.             });
  55.         }
  56.  
  57.     }
  58.  
  59.     /*
  60.      * Google login handler
  61.      * Add by Rahi
  62.      * Date : 8th nov, 17
  63.      */
  64.     googleLogIn() {
  65.  
  66.         this.googlePlus.login({})
  67.             .then(res => {
  68.                 // console.log("google login Response", res);
  69.  
  70.                 var googleparams = {
  71.                     google_id: res.userId,
  72.                     email: res.email,
  73.                 }
  74.  
  75.                 this.remotService.presentLoading("Please wait ...");
  76.                 this.remotService.postData(googleparams, 'googlelogin').subscribe((response) => {
  77.                     this.remotService.dismissLoader();
  78.                     if (response.success == 1) {
  79.  
  80.                         var dataRes = response.data;
  81.  
  82.                         window.localStorage['usertype'] = dataRes.user_type;
  83.                         window.localStorage['userid'] = dataRes.user_id;
  84.                         window.localStorage['token'] = dataRes.token;
  85.                         window.localStorage['username'] = dataRes.username;
  86.                         window.localStorage['premium_user'] = dataRes.premium_user;
  87.                         window.localStorage['name'] = dataRes.name;
  88.                         // fire event in app.component to show the header
  89.                         this.events.publish('user:loggedin');
  90.                         this.remotService.presentToast('Logged in successfully.');
  91.  
  92.  
  93.                     } else {
  94.                         var params = {data: res, type: 'google'}
  95.                         this.navCtrl.push(SocialregPage, params);
  96.                         //window.localStorage['fbprofileinfo'] = JSON.stringify(res);
  97.                     }
  98.                 }, () => {
  99.                     this.remotService.dismissLoader();
  100.                     this.remotService.presentToast('Error!');
  101.                 });
  102.  
  103.  
  104.             })
  105.             .catch(err => console.error(err));
  106.     }
  107.  
  108.     /*
  109.      * FB login handler
  110.      * Add by Rahi
  111.      * Date : 8th nov, 17
  112.      */
  113.     faceBooklogin() {
  114.  
  115.         this.fb.login(['public_profile', 'user_friends', 'email'])
  116.             .then(res => {
  117.                 // if connected get facebook user details
  118.                 if (res.status === "connected") {
  119.                     this.isfbLoggedIn = true;
  120.                     this.getFbUserDetail(res.authResponse.userID);
  121.                 } else {
  122.                     this.isfbLoggedIn = false;
  123.                 }
  124.             })
  125.             .catch(e => console.log('Error logging into Facebook', e));
  126.     }
  127.  
  128.     /*
  129.     * FB Get user details after getting authtoken & Check if user exist
  130.     * Add by Rahi
  131.     * Date : 8th nov, 17
  132.     */
  133.     getFbUserDetail(userid) {
  134.         this.fb.api("/" + userid + "/?fields=id,email,name,picture,token_for_business", ["public_profile"])
  135.             .then(res => {
  136.                 console.log(res);
  137.  
  138.                 var facemail = res.hasOwnProperty("email") ? res.email : null;
  139.                 var fbParams = {
  140.                     email: facemail,
  141.                     facebook_id: res.token_for_business,
  142.                 };
  143.                 this.remotService.presentLoading("Please wait ...");
  144.                 this.remotService.postData(fbParams, 'Facebooklogin').subscribe((response) => {
  145.  
  146.                     this.remotService.dismissLoader();
  147.                     if (response.success == 1) {
  148.  
  149.                         // If user exist log in user
  150.                         var dataRes = response.data;
  151.                         console.log(dataRes);
  152.                         window.localStorage['usertype'] = dataRes.user_type;
  153.                         window.localStorage['userid'] = dataRes.user_id;
  154.                         window.localStorage['token'] = dataRes.token;
  155.                         window.localStorage['username'] = dataRes.username;
  156.                         window.localStorage['premium_user'] = dataRes.premium_user;
  157.                         window.localStorage['name'] = dataRes.name;
  158.  
  159.                         // fire event in app.component to show the header
  160.                         this.events.publish('user:loggedin');
  161.                         this.remotService.presentToast('Logged in successfully.');
  162.  
  163.  
  164.                     } else {
  165.                         var params = {data: res, type: 'facebook'}
  166.                         this.navCtrl.push(SocialregPage, params);
  167.                         //window.localStorage['fbprofileinfo'] = JSON.stringify(res);
  168.                     }
  169.                 }, () => {
  170.                     this.remotService.dismissLoader();
  171.                     this.remotService.presentToast('Error!');
  172.                 });
  173.                 //this.users = res;
  174.             })
  175.             .catch(e => {
  176.                 this.remotService.presentToast("Error logging in using facebook.");
  177.                 console.log(e);
  178.             });
  179.     }
  180.  
  181.  
  182.  
  183. }
Add Comment
Please, Sign In to add comment