简体   繁体   中英

How to avoid Facebook LogIn screen if user already logged in in Ionic facebook integration app

I am working on ionic project, the only way to enter into app is via Facebook login.

The default page will be the login page.

The problem is login page appearing every time I open the App, So how to avoid login page if user is already logged in?

My default path is login page but I am struggling to avoid login page if user is already logged in.

app.js

var wowzer = angular.module('wowzer', ['ionic'])
wowzer.config(function($stateProvider, $urlRouterProvider, $locationProvider) {

  $stateProvider
    .state('login', {
      url: '/',
      templateUrl: 'templates/login.html',
      controller: 'LoginCtrl'
    })
    .state('app', {
      url: '/app',
      abstract: true,
      templateUrl: 'templates/menu.html',
      controller: 'LoginCtrl'
    })

    .state('app.search', {
      url: '/search',
      views: {
        'menuContent': {
          templateUrl: 'templates/search.html'
        }
      }
    })

    .state('app.browse', {
      url: '/browse',
      views: {
        'menuContent': {
          templateUrl: 'templates/browse.html'
        }
      }
    })
    .state('app.profileInfo', {
      url: '/profileInfo',
      views: {
        'menuContent': {
          templateUrl: 'templates/profileInfo.html',
          controller: 'ProfileInfoCtrl'
        }
      }
    })

    .state('app.profile', {
      url: '/profile',
      views: {
        'menuContent': {
          templateUrl: 'templates/profile.html',
          controller: 'ProfileCtrl'

        }
      }
    })
    .state('app.dog', {
      url: '/dog',
      views: {
        'menuContent': {
          templateUrl: 'templates/dog.html',
          controller: 'ProfileCtrl'
        }
      }
    });
    $urlRouterProvider.otherwise('/');

});

wowzer.constant('ApiEndpoint', {
  //url:'http://spmean.southindia.cloudapp.azure.com/wowzer'
  url: 'http//192.168.0.62:8100/api'
})

wowzer.run(function($ionicPlatform, $rootScope, $State, UserService) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });


  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if (UserService.getUser()) {
      console.log(UserService.getUser());
      console.log('goto dashboard');
      $state.go('app.profileinfo');
    } else {
      console.log('must login!');
      $state.go('login');
    }
  });

})

wowzer.constant("constantService", {
  attr: "this is first contant"
});

Userservices.js(factory)

 wowzer.factory('UserService', function() {


  var setUser = function(user_data) {
    window.localStorage.starter_facebook_user = JSON.stringify(user_data);
    console.log(window.localStorage.starter_facebook_user)
  };

  var getUser = function(){
    console.log(window.localStorage.starter_facebook_user)
    return JSON.parse(window.localStorage.starter_facebook_user || '{}');
  };

  return {
    getUser: getUser,
    setUser: setUser
  };

logInController.js

 wowzer.controller('LoginCtrl', function($scope, $state, $ionicModal, $q, $timeout, UserService, $ionicLoading, $ionicActionSheet) { var fbLoginSuccess = function(response) { if (!response.authResponse){ fbLoginError("Cannot find the authResponse"); return; } var authResponse = response.authResponse; getFacebookProfileInfo(authResponse) .then(function(profileInfo) { // For the purpose of this example I will store user data on local storage UserService.setUser({ authResponse: authResponse, userID: profileInfo.id, name: profileInfo.name, email: profileInfo.email, picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large" }); $ionicLoading.hide(); $state.go('app.profileInfo'); }, function(fail){ // Fail get profile info console.log('profile info fail', fail); }); }; // This is the fail callback from the login method var fbLoginError = function(error){ console.log('fbLoginError', error); $ionicLoading.hide(); }; // This method is to get the user profile info from the facebook api var getFacebookProfileInfo = function (authResponse) { var info = $q.defer(); facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null, function (response) { console.log(response); info.resolve(response); }, function (response) { console.log(response); info.reject(response); } ); return info.promise; }; //This method is executed when the user press the "Login with facebook" button $scope.facebookSignIn = function() { facebookConnectPlugin.getLoginStatus(function(success){ if(success.status === 'connected'){ // The user is logged in and has authenticated your app, and response.authResponse supplies // the user's ID, a valid access token, a signed request, and the time the access token // and signed request each expire console.log('getLoginStatus', success.status); // Check if we have our user saved var user = UserService.getUser('facebook'); if(!user.userID){ getFacebookProfileInfo(success.authResponse) .then(function(profileInfo) { // For the purpose of this example I will store user data on local storage UserService.setUser({ authResponse: success.authResponse, userID: profileInfo.id, name: profileInfo.name, email: profileInfo.email, picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large" }); $state.go('app.profile'); }, function(fail){ // Fail get profile info console.log('profile info fail', fail); }); }else{ $state.go('app.profileInfo'); } } else { // If (success.status === 'not_authorized') the user is logged in to Facebook, // but has not authenticated your app // Else the person is not logged into Facebook, // so we're not sure if they are logged into this app or not. console.log('getLoginStatus', success.status); $ionicLoading.show({ template: 'Logging in...' }); // Ask the permissions you need. You can learn more about // FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4 facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError); } }); }; $scope.showLogOutMenu = function() { var hideSheet = $ionicActionSheet.show({ destructiveText: 'Logout', titleText: 'Are you sure you want to logout? This app is awsome so I recommend you to stay.', cancelText: 'Cancel', cancel: function() {}, buttonClicked: function(index) { return true; }, destructiveButtonClicked: function(){ $ionicLoading.show({ template: 'Logging out...' }); // Facebook logout facebookConnectPlugin.logout(function(){ $ionicLoading.hide(); $state.go('login'); }, function(fail){ $ionicLoading.hide(); }); } }); }; }) 

For Ionic version > 1

I used cordova-plugin-facebook4 for integrating facebook in an ionic project. And to store logged in user's information I used native-storage . I actually don't remember which blog I followed (that would have helped you more). But following is my code.

app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { NativeStorage } from '@ionic-native/native-storage';

import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html'
})
export class YahooWhetherApp {
  rootPage:any; // = LoginPage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, public nativeStorage: NativeStorage) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.

      this.setHomePage()
      statusBar.styleDefault();
    });
  }

  setHomePage() {
    let env = this;
      this.nativeStorage.getItem('user').then(function (data) {
        env.rootPage = HomePage;
        this.splashScreen.hide();
      }, function (error) {
        env.rootPage = LoginPage;
        this.splashScreen.hide();
      })
  }

}

login.ts

    import { Component } from '@angular/core';
    import { IonicPage, NavController, NavParams } from 'ionic-angular';
    import { NativeStorage } from '@ionic-native/native-storage';

    import { Facebook } from '@ionic-native/facebook';
    import { Geolocation } from '@ionic-native/geolocation';

    import { HomePage } from '../home/home';

    /**
     * Generated class for the LoginPage page.
     *
     * See http://ionicframework.com/docs/components/#navigation for more info
     * on Ionic pages and navigation.
     */

    @IonicPage()
    @Component({
      selector: 'page-login',
      templateUrl: 'login.html',
    })
    export class LoginPage {
      FB_APP_ID: number = xxxxxxxx;
      latitude: number = null;
      longitude: number = null;
      constructor(public navCtrl: NavController, public navParams: NavParams, public fb: Facebook, public nativeStorage: NativeStorage, private geolocation: Geolocation) {
        this.fb.browserInit(this.FB_APP_ID, "v2.8");
      }

      ionViewDidLoad() {
        console.log('ionViewDidLoad LoginPage');
      }

      fbLogin() {
        console.log('fBLogin() called!!');
        let permissions = new Array<string>();
        let nav = this.navCtrl;
        let env = this;

        permissions = ["public_profile"];

        this.fb.login(permissions).then(function(response) {
          let userID = response.authResponse.userID;
          let params= new Array<string>();

          //Getting name & gender properties
          env.fb.api("/me?fields=name,gender", params).then(function(user) {
            user.picture = "https://graph.facebook.com/" + userID + "/picture?type=large";
            console.log('getting user fb info');
//Store in loggedIn user's info in device
            env.nativeStorage.setItem('user', {
              name: user.name,
              gender: user.gender,
              picture: user.picture          
            }).then(function() {
              nav.push(HomePage, {
                latitude: this.latitude,
                longitude: this.longitude
              });
            }, function(error) {
              console.log(error);
            })
          })
        }, function(error) {
          console.log(error);
        });
      }
    }

Explanation: First of all app.component.ts checks if there is any stored info or not. If there is some info then HomePage is loaded otherwise LoginPage is loaded.

Now in login.ts on the constructor level Facebook object is being initialised. And whenever fbLogin() method is called(may be from button click) facebook login happens with array of permissions that you provide to it. On successful login, user's info is stored in device and then HomePage is loaded(I have passed some values while pushing HomePage, please ignore that)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM