简体   繁体   English

如果用户已经登录Ionic Facebook集成应用程序,如何避免Facebook登录屏幕

[英]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. 我正在从事离子项目,进入应用程序的唯一方法是通过Facebook登录。

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 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) Userservices.js(工厂)

 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 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 对于离子版本> 1

I used cordova-plugin-facebook4 for integrating facebook in an ionic project. 我使用cordova-plugin-facebook4将facebook集成到离子项目中。 And to store logged in user's information I used native-storage . 为了存储登录的用户信息,我使用了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 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. 说明:首先app.component.ts检查是否有任何存储的信息。 If there is some info then HomePage is loaded otherwise LoginPage is loaded. 如果有一些信息,则将加载HomePage,否则将加载LoginPage。

Now in login.ts on the constructor level Facebook object is being initialised. 现在在构造函数级别的login.ts中 ,正在初始化Facebook对象。 And whenever fbLogin() method is called(may be from button click) facebook login happens with array of permissions that you provide to it. 每当调用fbLogin()方法(可能是通过单击按钮),Facebook登录就会发生,并提供您提供的权限数组。 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) 成功登录后,用户信息将存储在设备中,然后加载HomePage(我在推送HomePage时传递了一些值,请忽略该信息)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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