登录屏幕只有第一次在本机应用程序在sencha [英] Login screen only first time in native app in sencha

查看:237
本文介绍了登录屏幕只有第一次在本机应用程序在sencha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sencha touch中的原生应用。我想创建一个应该只有第一次可见的登录视图。任何建议如何解决。

i am working on a native app in sencha touch. i want to create a login view which should be visible only first time. any suggestion how to solve it.

Activation.js

Activation.js

Ext.define('FOS.view.Activation', {
    extend: 'Ext.form.Panel',
    alias: "widget.activationview",
    requires: ['Ext.form.FieldSet', 'Ext.form.Password', 'Ext.Label', 'Ext.Img', 'Ext.util.DelayedTask'],
    config: {
        title: 'Login',
        items: [

            {
                xtype: 'label',
                html: 'Activation failed. Please enter the correct credentials.',
                itemId: 'activationFailedLabel',
                hidden: true,
                hideAnimation: 'fadeOut',
                showAnimation: 'fadeIn',
                style: 'color:#990000;margin:5px 0px;'
            },
            {
                xtype: 'fieldset',
                title: ' ',
                items: [
                    {
                        xtype: 'textfield',
                        placeHolder: 'Enter Agency Id',
                        itemId: 'agencyIdTextField',
                        name: 'agencyIdTextField',
            label: 'Agency Id',
                        labelWidth: '40%',
                        //required: true
                    },
                    {
                        xtype: 'textfield',
                        placeHolder: 'Enter App Id',
                        itemId: 'appIdTextField',
                        name: 'appIdTextField',
            label: 'App Id',
                        labelWidth: '40%',
                       // required: true
                    }
                ]
            },
            {
                xtype: 'button',
                itemId: 'activationButton',
                ui: 'action',
                padding: '10px',
                text: 'Activate'
            }
         ],
        listeners: [{
            delegate: '#activationButton',
            event: 'tap',
            fn: 'onActivationButtonTap'
        }]
    },
    onActivationButtonTap: function () {

        var me = this,
            agencyidField = me.down('#agencyIdTextField'),
            appidField = me.down('#appIdTextField'),
            label = me.down('#activationFailedLabel'),
            agencyid = agencyidField.getValue(),
            appid = appidField.getValue();

        label.hide();

        // Using a delayed task in order to give the hide animation above
        // time to finish before executing the next steps.
        var task = Ext.create('Ext.util.DelayedTask', function () {

            label.setHtml('');

            me.fireEvent('activationCommand', me, agencyid, appid);

            agencyidField.setValue('');
            appidField.setValue('');
        });

        task.delay(500);

    },
    showActivationFailedMessage: function (message) {
        var label = this.down('#activationFailedLabel');
        label.setHtml(message);
        label.show();
    }
});

Login.js

Ext.define('FOS.view.Login', {
    extend: 'Ext.form.Panel',
    alias: "widget.loginview",
    requires: ['Ext.form.FieldSet', 'Ext.form.Password', 'Ext.Label', 'Ext.Img', 'Ext.util.DelayedTask'],
    config: {
        title: 'Login',
        items: [

            {
                xtype: 'label',
                html: 'Login failed. Please enter the correct credentials.',
                itemId: 'signInFailedLabel',
                hidden: true,
                hideAnimation: 'fadeOut',
                showAnimation: 'fadeIn',
                style: 'color:#990000;margin:5px 0px;'
            },
            {
                xtype: 'fieldset',
                title: ' ',
                items: [
                    {
                        xtype: 'textfield',
                        placeHolder: 'Enter UserName',
                        itemId: 'userNameTextField',
                        name: 'userNameTextField',
            label: 'UserName',
                        labelWidth: '40%',
                        //required: true
                    },
                    {
                        xtype: 'passwordfield',
                        placeHolder: 'Enter Password',
                        itemId: 'passwordTextField',
                        name: 'passwordTextField',
            label: 'Password',
                        labelWidth: '40%',
                       // 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('#signInFailedLabel'),
            username = usernameField.getValue(),
            password = passwordField.getValue();

        label.hide();

        // Using a delayed task in order to give the hide animation above
        // time to finish before executing the next steps.
        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('#signInFailedLabel');
        label.setHtml(message);
        label.show();
    }
});

MainMenu.js

MainMenu.js

Ext.define('FOS.view.MainMenu', {
    extend: 'Ext.Panel',
    requires: ['Ext.TitleBar'],
    alias: 'widget.mainmenuview',
    config: {
        layout: {
            type: 'fit'
        },
        items: [{
            xtype: 'titlebar',
            title: 'Main Menu',
            docked: 'top',
            items: [
                {
                    xtype: 'button',
                    text: 'Log Off',
                    itemId: 'logOffButton',
                    align: 'right'
                }
            ]
        }],
        listeners: [{
            delegate: '#logOffButton',
            event: 'tap',
            fn: 'onLogOffButtonTap'
        }]
    },
    onLogOffButtonTap: function () {
        this.fireEvent('onSignOffCommand');
    }
});

控制器

Ext.define('FOS.controller.Login', {
    extend: 'Ext.app.Controller',

   config: {
        refs: {
            loginView: 'loginview',
            mainMenuView: 'mainmenuview',
        activationView: 'activationview'
        },
        control: {
        activationView: {
                activationCommand: 'onActivationCommand'
            },
               loginView: {
                   signInCommand: 'onSignInCommand'
            },
            mainMenuView: {
                onSignOffCommand: 'onSignOffCommand'
            }
        }
    },

    // Session token

   // sessionToken: null,

    // Transitions
    getSlideLeftTransition: function () {
        return { type: 'slide', direction: 'left' };
    },

    getSlideRightTransition: function () {
        return { type: 'slide', direction: 'right' };
    },

onActivationCommand: function (view, agencyid, appid) {

        console.log('AgencyId: ' + agencyid + '\n' + 'AppId: ' + appid);

        var me = this,
            activationView = me.getActivationView();

        if (agencyid.length === 0 || appid.length === 0) {

            activationView.showActivationFailedMessage('Please enter your Agency Id and App Id.');
            return;
        }

        activationView.setMasked({
            xtype: 'loadmask',
            message: 'Activating...'
        });

            me.activationSuccess();     //Just simulating success.

    },

    activationSuccess: function () {
        console.log('Activated.');
        var activationView = this.getActivationView();
        loginView = this.getLoginView();
        activationView.setMasked(false);

        Ext.Viewport.animateActiveItem(loginView, this.getSlideLeftTransition());
    },

    onSignInCommand: function (view, username, password) {

        console.log('Username: ' + username + '\n' + 'Password: ' + password);

        var me = this,
            loginView = me.getLoginView();

        if (username.length === 0 || password.length === 0) {

            loginView.showSignInFailedMessage('Please enter your User Name and Password.');
            return;
        }

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

      /*  Ext.Ajax.request({
            url: '../../services/login.ashx',
            method: 'post',
            params: {
                user: username,
                pwd: password
            },
            success: function (response) {

                var loginResponse = Ext.JSON.decode(response.responseText);

                if (loginResponse.success === "true") {
                    // The server will send a token that can be used throughout the app to confirm that the user is authenticated.
                    me.sessionToken = loginResponse.sessionToken;*/
                    me.signInSuccess();     //Just simulating success.
               /* } else {
                    me.singInFailure(loginResponse.message);
                }
            },
            failure: function (response) {
                me.sessionToken = null;
                me.singInFailure('Login failed. Please try again later.');
            }
        });*/
    },

    signInSuccess: function () {
        console.log('Signed in.');
        var loginView = this.getLoginView();
        mainMenuView = this.getMainMenuView();
        loginView.setMasked(false);

        Ext.Viewport.animateActiveItem(mainMenuView, this.getSlideLeftTransition());
    },
/*
    singInFailure: function (message) {
        var loginView = this.getLoginView();
        loginView.showSignInFailedMessage(message);
        loginView.setMasked(false);
    },*/

    onSignOffCommand: function () {

        var me = this;

       /* Ext.Ajax.request({
            url: '../../services/logoff.ashx',
            method: 'post',
            params: {
                sessionToken: me.sessionToken
            },
            success: function (response) {

                // TODO: You need to handle this condition.
            },
           failure: function (response) {

                // TODO: You need to handle this condition.
            }
        });*/

        Ext.Viewport.animateActiveItem(this.getLoginView(), this.getSlideRightTransition());
    }
});

app.js

//<debug>
Ext.Loader.setPath({
    'Ext': 'touch/src',
    'FOS': 'app'
});
//</debug>

Ext.application({
    controllers: ["Login"],

    name: 'FOS',

    requires: [
        'Ext.MessageBox'
    ],

    views: ['Activation','Login','MainMenu'],



    icon: {
        '57': 'resources/icons/Icon.png',
        '72': 'resources/icons/Icon~ipad.png',
        '114': 'resources/icons/Icon@2x.png',
        '144': 'resources/icons/Icon~ipad@2x.png'
    },

    isIconPrecomposed: true,

    startupImage: {
        '320x460': 'resources/startup/320x460.jpg',
        '640x920': 'resources/startup/640x920.png',
        '768x1004': 'resources/startup/768x1004.png',
        '748x1024': 'resources/startup/748x1024.png',
        '1536x2008': 'resources/startup/1536x2008.png',
        '1496x2048': 'resources/startup/1496x2048.png'
    },

    launch: function() {
        // Destroy the #appLoadingIndicator element
        Ext.fly('appLoadingIndicator').destroy();

        // Initialize the main view

    Ext.Viewport.add([
         { xtype: 'activationview'},
             { xtype: 'mainmenuview' },
         { xtype: 'loginview' }
     ]);
    },

    onUpdated: function() {
        Ext.Msg.confirm(
            "Application Update",
            "This application has just successfully been updated to the latest version. Reload now?",
            function(buttonId) {
                if (buttonId === 'yes') {
                    window.location.reload();
                }
            }
        );
    }
});

我希望此激活视图只有一次。
web services is not availabale yet ....

i want this activation view only one time. web services are not availabale yet....

推荐答案

基本上,你所寻找的是类似于记住我 SSO (单点登录)功能,可在大多数网站和本机应用程序上使用。我自己需要这个在我最近的一个应用程序。

Basically, what you looking for is something similar to Remember Me or SSO (single sign-on) feature that is available on most of the websites and native apps. I myself needed this in one of my app recently.

使用sencha,您可以使用HTML5存储。一旦用户成功登录,将某些用户详细信息(如登录状态,访问令牌,用户ID等)存储到HTML5数据库中。你可以轻松地存储高达5MB的数据,因为sencha运行在现代的web浏览器,如webkit,你可以使用那个api,并做它的东西。

With sencha, you can use HTML5 storage. Once user is logged in successfully, store certain user details like login status, access token, user id etc into HTML5 database. You can easily store upto 5MB of data in it and since sencha runs on modern web browsers like webkit, you can use that api and do stuff with it.

所以,我创建了一个模型,其中包含用户ID,登录状态和访问令牌等各种字段。例如,你可以有类似的模型 -

So to the point, I've created a model having various fields like user id, login status and access token in my app. For instance you can have model something like -

Ext.define('MyApp.model.Userinfo',{
    extend:'Ext.data.Model',
    config:{
        identifier: 'uuid',
        store:'MyApp.store.Userinfo',
        fields:[                 
           {name: 'id', type: 'string' },
           {name: 'userid', type: 'string' },
           {name:'login_status',type:'string'},
           {name:'access_token',type:'string'}
        ]    
    }        
});

您可以根据需求添加字段数,并为每个字段选择合适的类型。但是你的模型应该有一个唯一的标识符。使用ST2.0,您可以使用 identifier:'uuid'为存储分配唯一标识符。

You can add number of field as per your requirement and choose suitable types for each field. But your model should have a unique identifier. With ST2.0 you can use identifier:'uuid' to assign unique identifier to your storage.

存储,它可以像 -

Then comes store, it can be like -

Ext.define('MyApp.store.Userinfo',{
   extend:'Ext.data.Store',   
   config:{
       model:'MyApp.model.Userinfo',
       autoLoaded:true,
       autoLoad: true,
       autoSave:true,
       proxy:{
           type:'localstorage',
           id:'userinfo'
       }
   }
});

最后,登录成功后,您可以使用 -

Then finally, when the login is successful, you can add data into your localstorage with -

  var userInfoData=Ext.getStore('Userinfo');                                
  userInfoData.removeAll();
  userInfoData.getProxy().clear();
  userInfoData.add({userid:'user_id_to_store',login_status:"true",access_token:'generated_access_token'});
  userInfoData.sync();

最后,在 app.js ,检查此本地存储的条目并验证访问令牌的可靠性。因此在启动方法中,

And at the end, in your app.js , check for a entry into this localstorage and validate access token for reliability. So in launch method,

var userInfoData=Ext.getStore('Userinfo');              
if(null!=userInfoData.getAt(0)){
    var status = userInfoData.getAt(0).get('login_status');
    var user_id=userInfoData.getAt(0).get('userid');
    var access_token = userInfoData.getAt(0).get('access_token');   

    //validate access token, check user id and status and load your next view that comes after login    

}else{
    // if reached here, that means user is not logged in.
    // load your login view.  
}

我无法读取您的整个代码并进行编辑。但这是我已经使用,它的工作没有任何麻烦,直到现在。您可以根据您的应用程序和要求轻松地更改它。

I couldn't read your whole code and edit it. But this is what I've used and it's working without any trouble up till now. You can alter it easily as per your app and requirements.

注意

代码是一年多。所以它可能不工作在最新的ST版本(未测试)。
但是想法是一样的。干杯。 :)

This code is more than a year old. So it might not work on latest ST version (not tested). But idea is same. Cheers. :)

这篇关于登录屏幕只有第一次在本机应用程序在sencha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆