Search code examples
cordovaionic-frameworkphonegap-buildcordova-cli

Cordova app local storage remains after app re-installed


My cordova app has a login (username/password) that once authenticated creates a file called stk.db within the root of the app's file system.

When I uninstall the app & re-install it, I am automatically logged in with the previous account I logged in with (due to the stk.db file being read & pulling a 'token' that correlates to a user account).

Obviously I want to have the user be forced to enter a new user account if they re-install the app, what is the best way to approach this based on the code below?

define([
"jquery",
"backbone",
"config",
"stk/controllers/errorController",
"stk/controllers/accountController",
"stk/controllers/onboardController",
"stk/controllers/stkController"
],

function(
$,
Backbone,
Config,
ErrorController,
AccountController,
OnboardController,
stkController) 
{

"use strict";

// --------------------------------------------------------------------------------------------
// Controller
// --------------------------------------------------------------------------------------------

var app = function(router) {

    var self = this;
    self.router = router;
    self.views = {};
    self.ctors = {};

    self.stack = [
        { id: 0, name : "Account", selected: true, direction: null },
        { id: 1, name : "Achievements", selected: false, direction: null },
        { id: 2, name : "Prizes", selected: false, direction: null },
        { id: 3, name : "Shop", selected: false, direction: null },
        { id: 4, name : "Leaderboard", selected: false, direction: null },
        { id: 5, name : "Stats", selected: false, direction: null },
        { id: 6, name : "Contactus", selected: false, direction: null }
    ];

    // --------------------------------------------------------------------------------------------
    // register events
    // --------------------------------------------------------------------------------------------

    _.extend(this, Backbone.Events);

    this.on("error", function (args) { this.error(args); }, this);
    this.on("start", function (args) { this.db(args); }, this);
    this.on("login:complete", function (args) { this.loginComplete(args); }, this);
    this.on("onboard:complete", function (args) { this.onboardComplete(args); }, this);

    // --------------------------------------------------------------------------------------------
    // event handlers
    // --------------------------------------------------------------------------------------------        

    this.db = function() {

        var self = this;

        var loadDB = function(callback) {
            self.storage(callback);
        }        

        loadDB(function(db) {

            var check = {};

            $.each(db.split("|"), function() {
                var entry = this.split(":");
                check[entry[0]] = entry[1];
            })

            self.start(check);

        })

    };


    this.start = function(db) {

        if (db.loggedin != "true") {
            this.login();
        } else {
            this.token = db.token;
            if (db.boarded === "true") {
                this.launch();
            } else {
                this.onboard();
            }
        }

    };

    this.isCarUser = function (usercb) {


        var self = this;
        var check = {};

        self.storage(function (db) {

            $.each(db.split("|"), function () {
                var entry = this.split(":");
                check[entry[0]] = entry[1];
            })

            usercb(check.Car_user);
        });
    };



    this.error = function(message) {
        var handle = "errorCtor";
        (this.ctors[handle] === undefined)
                ? new ErrorController().setup(handle).events().init(message)
                : this.ctors[handle].init(message);
    };

    this.login = function(args) {
        var handle = "accountCtor";
        (this.ctors[handle] === undefined)
                ? new AccountController().setup(handle).events().init(args)
                : this.ctors[handle].init(args);
    };

    this.loginComplete = function(args) {

        var self = this;
        self.token = args;

        var store = function(callback) {
            self.setLoggedIn(callback, self.token);
        }        

        store(function(db) {
            self.onboard();
        });

    };

    this.onboard = function(args) {
        var handle = "onboardCtor";
        (this.ctors[handle] === undefined)
                ? new OnboardController().setup(handle).events().init(args)
                : this.ctors[handle].init(args);
    };

    this.onboardComplete = function(args) {

        var self = this;

        var store = function(callback) {
            self.setBoarded(callback, self.token);
        }        

        store(function() {
            self.launch();
        });

    };

    this.launch = function(args) {
        var handle = "stkCtor";
        (this.ctors[handle] === undefined)
                ? new stkController().setup(handle).events().init(args)
                : this.ctors[handle].init(args);
    };

    // --------------------------------------------------------------------------------------------
    // FS
    // --------------------------------------------------------------------------------------------

    this.setBoarded = function(callback, token) {

        var self = this;

        var fc = 'opened:true|loggedin:true|boarded:true||Car_user:false|token:' + token;

        var errorHandler = function(e) {
            self.error(e);
        };

        var onInitFs = function(fs) {

            fs.root.getFile('stk.db', {}, function(fileEntry) {

                fileEntry.createWriter(function(fileWriter) {

                    fileWriter.onwriteend = function(e) {                                
                        callback(fc);
                    };

                    fileWriter.onerror = function(e) {
                        self.error(e.toString());
                    };

                    var boarded = new Blob([fc], {type: 'text/plain'});

                    fileWriter.write(boarded);

                }, errorHandler);

            });

        };

        if (window.isDevice) {
            window.requestFileSystem(window.PERSISTENT, 512, onInitFs, errorHandler);
        } else {
            callback(fc);
        }

    };

    this.setLoggedIn = function(callback, token) {

        var self = this;

        var fc = 'opened:true|loggedin:true|boarded:false|Car_user:false|token:' + token;

        var errorHandler = function(e) {
            self.error(e);
        };

        var onInitFs = function(fs) {

            fs.root.getFile('stk.db', {}, function(fileEntry) {

                fileEntry.createWriter(function(fileWriter) {

                    fileWriter.onwriteend = function(e) {                                                            
                        callback(fc);
                    };

                    fileWriter.onerror = function(e) {
                        self.error(e.toString());
                    };

                    var loggedIn = new Blob([fc], {type: 'text/plain'});

                    fileWriter.write(loggedIn);

                }, errorHandler);

            });

        };

        if (window.isDevice) {
            window.requestFileSystem(window.PERSISTENT, 512, onInitFs, errorHandler);
        } else {
            callback(fc);
        }

    };


    this.setCarUser =  function(callback, CarUser){

        var self = this;

        var fc = 'opened:true|loggedin:true|boarded:true|token:' + this.token + "|Car_user:"+ CarUser;

        var errorHandler = function(e) {
            self.error(e);
        };

        var onInitFs = function(fs) {

            fs.root.getFile('stk.db', {}, function(fileEntry) {

                fileEntry.createWriter(function(fileWriter) {

                    fileWriter.onwriteend = function(e) {
                        callback(fc);
                    };

                    fileWriter.onerror = function(e) {
                        self.error(e.toString());
                    };

                    var loggedIn = new Blob([fc], {type: 'text/plain'});

                    fileWriter.write(loggedIn);

                }, errorHandler);

            });

        };

        if (window.isDevice) {
            window.requestFileSystem(window.PERSISTENT, 512, onInitFs, errorHandler);
        } else {
            callback(fc);
        }
    }

    this.storage = function(callback) {

        var self = this;

        var fc = 'opened:true|loggedin:false|boarded:false|token:null|Car_user:false';

        var errorHandler = function(e) {
            console.log(e);
        };

        var onInitFs = function(fs) {

            fs.root.getFile('stk.db', {}, function(fileEntry) {

                fileEntry.file(function(file) {

                    var reader = new FileReader();

                    reader.onloadend = function(e) {
                        callback(this.result);
                    };

                    reader.readAsText(file);

                }, errorHandler);

            }, function() {

                fs.root.getFile('stk.db', {create: true, exclusive: true}, function(fileEntry) {

                    fileEntry.createWriter(function(fileWriter) {

                        fileWriter.onwriteend = function(e) {                                
                            callback(fc);
                        };

                        fileWriter.onerror = function(e) {
                            self.error(e.toString());
                        };

                        var opened = new Blob([fc], {type: 'text/plain'});

                        fileWriter.write(opened);

                    }, errorHandler);

                }, errorHandler);

            });

        };

        if (window.isDevice) {
            window.requestFileSystem(window.PERSISTENT, 512, onInitFs, errorHandler);
        } else {
            callback(fc);
        }

    };

};

return app;

}

);

Solution

  • If you really need to use local file for some reasons, you can store a version number in the local file, and compare it with the version number stored inside the index.html, if these two version numbers are different, erase the login info. in the local file and update the version no. in the local file.

    by the way, would like to tell you that the local file Api does not work as expected in all phones. e.g. sometimes it hangs in Samsung Note 2, i.e. neither success nor fail fires, but the same codes work well in other phones.