Sencha Touch 2:在应用启动时检查cookie

时间:2013-11-03 03:39:46

标签: extjs sencha-touch sencha-touch-2

我对使用Sencha Touch 2库进行开发完全不熟悉。我按照本教程来帮助创建一个简单的登录脚本(http://miamicoder.com/2012/adding-a-login-screen-to-a-sencha-touch-application-part-2/)。我不确定的一件事是如何检查会话令牌是否存在于客户端,这样当他们返回应用程序时,登录屏幕不会显示他们是否经过身份验证。

app.js

Ext.application({
    name: 'RecruitTalkTouch',
    views: ['Login', 'MainMenu'],
    controllers: ['Login'],
    launch: function () {
      Ext.Viewport.add([
        { xtype: 'loginview' },
        { xtype: 'mainmenuview' }
      ]);
    }
});

Login.js控制器:

Ext.define('RecruitTalkTouch.controller.Login', {
  extend: 'Ext.app.Controller',
  config: {
    refs: {
      loginView: 'loginview',
      mainMenuView: 'mainmenuview'
    },
    control: {
      loginView: {
        signInCommand: 'onSignInCommand'
      },
      mainMenuView: {
        signOffCommand: 'onSignOffCommand'
      }
    }
  },
  onSignInCommand: function(view, username, password) {
    var me = this,
        loginView = me.getLoginView();

    if(username.length === 0 || password.length === 0) {
      loginView.showSignInFailedMessage('Please enter your username and password.');
      return;
    }

    loginView.setMasked({
      xtype: 'loadmask',
      message: 'Signing In...'
    });

    Ext.Ajax.request({
      url: 'http://localhost:3000/api/v1/sessions.json',
      method: 'POST',
      useDefaultXhrHeader: false,
      params: {
        login: username,
        password: password
      },
      success: function(resp) {
        var json = Ext.JSON.decode(resp.responseText);

        if(json.success === "true") {
          me.sessionToken = json.auth_token;
          me.signInSuccess();
        } else {
          me.signInFailure(json.message)
        }
      },
      failure: function(resp) {
        me.sessionToken = null;
        me.signInFailure('Login failed. Please try again');
      }
    });
  },
  signInSuccess: function() {
    console.log("Signed In");
    var loginView = this.getLoginView(),
        mainMenuView = this.getMainMenuView();

    loginView.setMasked(false);

    Ext.Viewport.animateActiveItem(mainMenuView, this.transition('slide', 'left'));
  },
  signInFailure: function(message) {
    var loginView = this.getLoginView();
    loginView.showSignInFailedMessage(message);
    loginView.setMasked(false);
  },
  transition: function(type, direction) {
    return { type: type, direction: direction };
  },
  onSignOffCommand: function() {
    var me = this;
    me.sessionToken = null;
    Ext.Viewport.animateActiveItem(this.getLoginView(), this.transition('slide', 'right'));
  }
});

Login.js查看:

Ext.define('RecruitTalkTouch.view.Login', {
    extend: 'Ext.form.Panel',
    alias: "widget.loginview",
    requires: ['Ext.form.FieldSet', 'Ext.form.Password', 'Ext.Label', 'Ext.Button'],
    config: {
        title: 'Login',
        items: [
          {
            xtype: 'label',
            html: 'Login failed. Please enter the correct credentials.',
            itemId: 'signInFailed',
            hidden: true,
            hideAnimation: 'fadeOut',
            showAnimation: 'fadeIn'
          },
          {
            xtype: 'fieldset',
            title: 'Login',
            items: [
              {
                xtype: 'textfield',
                placeHolder: 'Username',
                itemId: 'userNameTextField',
                name: 'userNameTextField',
                required: true
              },
              {
                xtype: 'passwordfield',
                placeHolder: 'Password',
                itemId: 'passwordTextField',
                name: 'passwordTextField',
                required: true
              }
            ]
          },
          {
            xtype: 'button',
            itemId: 'logInButton',
            ui: 'action',
            padding: '10px',
            text: 'Log In'
          }
        ],
        listeners: [{
          delegate: '#logInButton',
          event: 'tap',
          fn: 'onLogInButtonTap'
        }]
    },
    onLogInButtonTap: function() {
      var me = this,
          usernameField = me.down('#userNameTextField'),
          passwordField = me.down('#passwordTextField'),
          label = me.down('#signInFailed'),
          username = usernameField.getValue(),
          password = passwordField.getValue();

      label.hide();

      var task = Ext.create('Ext.util.DelayedTask', function(){
        label.setHtml('');
        me.fireEvent('signInCommand', me, username, password);

        usernameField.setValue('');
        passwordField.setValue('');
      });

      task.delay(500);
    },
    showSignInFailedMessage: function(message) {
      var label = this.down('#signInFailed');
      label.setHtml(message);
      label.show();
    }
});

2 个答案:

答案 0 :(得分:2)

您可能会发现在服务器上添加检查功能以检查有效会话会更容易。即使cookie存在,也不意味着他们没有注销,会话cookie会随着每个请求来回发送。

也就是说,如果您想从客户端访问cookie,它们将作为单个字符串值附加到文档中。您可以在document.cookies上访问它们。我将查看ExtJS cookie实用程序的文档和来源,以获得有关如何在该字符串中查找cookie的一些灵感。

Ext.util.Cookies Documentation

Ext.util.Cookies Source

基本上,过程是遍历cookie字符串中的每个字母,将子字符串取出到会话密钥名称的长度,查看它是否匹配,然后在下一个等号和分号之间拉取数据。然后你对值进行非百分比编码,你很高兴。

修改 要ping服务器,只需在显示第一个视图之前在应用程序加载过程中的某个位置发出Ajax请求。我认为发射功能非常自然:

Ext.application({
    name: 'App',

    requires: [],
    models: [],
    stores: [],
    views: [],
    controllers: [],

    ....

    launch: function () {
        //Check with the server
        Ext.Ajax.request({
            //Proxy Settings
            url: 'path/to/check/script.php',
            //Callbacks
            success: function (response, opts) {
                // process server response here
                response = Ext.JSON.decode(response.responseText);
                if(response && response.success === true) {
                    //Load the normal first view
                    Ext.Viewport.add(Ext.create('App.view.Main');
                } else {
                    //Load the login view
                    Ext.Viewport.add(Ext.create('App.view.LoginForm');
                }
            },
            failure: function (response, opts) {
                //Notify of network failure
            }
        });
    }
});

就服务器端脚本中的操作而言,它取决于您正在开发的语言以及您要对其进行身份验证的内容。如果它只是用户名和密码的数据库,那么当用户首次登录时,启动会话,并为其userID和密码存储会话变量。在检查功能中,首先检查当前会话是否存在,然后针对您的数据库重新进行身份验证(以防您或其他人在会话仍然有效时取消其帐户),确保它们仍然有效。然后只需发回一条json响应,告知他们是否已登录,并包含使您的应用运行所需的任何相关用户信息。

答案 1 :(得分:0)

在Sencha Touch中使用:

var cookiestr = document.cookie.split('; ');
var cookieObjArr = new Array();

for (var i=0; i<cookiestr.length; ++i)
{
    if (i in cookiestr)
    {
        tmp = cookiestr[i].split('=');
        cookieObjArr.push({"key": tmp[0], "value": tmp[1]});
    }
}