How to store login credentials in localstorage - javascript

If got a sencha touch application, with a login form. For returning users, I would like to store the login credentials in the local storage.
User.js
App.models.User = Ext.regModel('User', {
fields: [
{
name: 'username',
type: 'string'
}, {
name: 'password',
type: 'string'
}
],
proxy: {
type: 'localstorage',
id: 'p2s-users'
}
});
Users.js
App.stores.users = new Ext.data.Store({
model: 'User',
autoLoad: true
});
Now I try to sync the form values with local storage, how can I do that, what's the activity flow for reading / getting it?
For reading I would do:
var model = new App.models.User();
users = App.stores.users.load();
if (users.data.length > 0 ) {
model = users.getAt(0);
} else {
App.stores.users.create();
}
form.load(model);
Writing:
form.model.set(form.data);
form.model.save();
App.stores.users.sync();
Somehow it looks too complicate to me (and it doesn't work anyway). How would you solve the problem?

First make sure your saving the models right. For example do this:
var model = new App.models.User();
model.data.username = 'theUser';
model.data.password = 'thePass';
model.save(); //the actual saving. Use chrome developer tools to see the local storage
Then load the model from the localstorage
users = App.stores.users.load();
model = users.getAt(0);
Check if the loaded model is OK and load that to the form with load(model)
The form could be like this:
new Ext.Application({
launch: function() {
new Ext.form.FormPanel({
id:'theForm',
fullscreen: true,
defaults: {
labelAlign: 'top',
labelWidth: 'auto',
},
items: [
{
id : 'userName',
name : 'username',
label: 'Email',
xtype: 'emailfield',
},
{
id : 'userPassword',
name: 'password',
label: 'Password',
xtype: 'passwordfield',
}
]
});
}
});
Then load the record like this Ext.getCmp('theForm').load(users.getAt(0));
To get the model from the form: Ext.getCmp('theForm').getRecord();

From a cursory look, it looks like a possible way to do it.
But, you should create model instances from the model manager, for instance:
Ext.ModelMgr.create({username: 'foo', password: 'bar'}, 'User');

Related

ExtJS 6 : load nested data by creating new instance of model

I try to create a model with an hasMany association but when I try to access to the store, it's empty.
This is my models :
BaseModel :
Ext.define( 'Test.model.schema.BaseModel', {
extend: 'Ext.data.Model',
schema: {
namespace: 'Test.model'
}
} );
UserModel :
Ext.define('Test.model.user.UserModel', {
extend: 'Ext.data.Model',
fields: [
{
name: 'displayName',
type: 'string'
}
],
hasMany: [
{
name: 'roles',
model: 'user.RoleModel', // also try with Test.model.user.RoleModel
associationKey: 'roles'
}
]
});
RoleModel :
Ext.define('Test.model.user.RoleModel', {
extend: 'Ext.data.Model',
fields: [
{
name: 'label',
type: 'string'
}
]
});
This is my Application :
Ext.application({
name: 'Test',
models : [
'Test.model.schema.BaseModel',
'Test.model.user.RoleModel',
'Test.model.user.UserModel'
],
appFolder : contextPath + '/' + staticsPath + '/js/app',
controllers : ['router.TestRouterController'],
defaultToken : 'auth'
});
In my controller I try to create my user model like this :
var user = Ext.create('Test.model.user.UserModel', {
displayName : 'Mick P.',
roles : [
{
label: 'test'
}
]
});
Same with JSon.
When I do user.roles().getAt(0) I got null and user.roles().data.items is empty.
Do you see what i'm doing wrong ?
EDIT 1 : A fiddle of my problem : https://fiddle.sencha.com/#fiddle/1e54
EDIT 2 : It works if I load my datas with a memory store. But why not by loading directly a model.
Sencha support send to me a response. Perhaps some of you need an answer.
First you need to read this documentation page : http://docs.sencha.com/extjs/6.0.2-classic/Ext.data.reader.Reader.html
When you pass data directly into the Model constructor, it is not passed through the configured reader, and only basic fields are evaluated.
Data does need to pass through a Reader.
If you don't want to create a Store :
1 - you need to declare proxy into models
2 - to create model with nested data, you have to do something like that :
UserModel.getProxy().getReader().read(raw);
If you need a fiddle example tell me.
- Mickael

Setting LocalStorage store for nested list

I've created a localstorage store, and stored demo values in it following this tutorial:
http://sureshdotariya.blogspot.com/2013/03/understanding-local-storage-proxy-in.html
And it all works fine, I've viewed the store data in the resources in chrome and it is there, and when I load the page it loads fine, no errors, but it shows no data, here's my view code:
Ext.define('MyTest.view.SearchPanel', {
extend: 'Ext.Panel',
xtype: 'searchpanel',
config: {
layout: 'fit',
items: [
{
xtype: 'nestedlist',
title: 'Search Results',
displayField: 'Name',
store: {
storeId: 'UserStore',
fields: ['Name']
},
}]
}
});
What am I missing here? Can I use local storage store as the store for the nested list? And if yes then why it shows "No items found", I've added the store in app.js, I tried requiring it in this view but that did not work.
Your help is appreciated, thanks.
Ext.dataview.NestedList requires Ext.data.TreeStore instead of Ext.data.Store ( in the sample URL you gave ).
There are root, defaultRootProperty config required in Ext.data.TreeStore, and leaf property in items.
Of course you can set Ext.data.proxy.LocalStorage as proxy in Ext.data.TreeStore , try with these codes :
Ext.define('ListApp.model.User', {
extend: 'Ext.data.Model',
config: {
fields: [{
name: 'text',
type: 'string'
}]
}
});
Ext.define('App.store.User', {
config: {
model: 'ListApp.model.User',
defaultRootProperty: 'items',
root: data
proxy: {
type: 'localstorage',
id: 'UserInfo'
}
}
});

Sencha Touch 2 LocalStorageProxy dosn't save data to LocalStorage

i'm trying to save some app settings to the LocalStorage.
I have a model with the LocalStorageProxy, I have a Store with the model and autoload = true.
I sync the store after adding a record.
The corresponding Docs: http://docs-origin.sencha.com/touch/2.4.0/#!/api/Ext.data.proxy.LocalStorage
But after reloading the app in the browser (Chrome) the data are lost. Addidionally to the autoload flag i do a manual store.load() in the launch method of the application.
All is working fine until i reload the app.
Any ideas on that? Thanks!
the model:
Ext.define('LwvMediaReminder.model.Setting', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field',
'Ext.data.proxy.LocalStorage'
],
config: {
idProperty: 'settingsId',
fields: [
{
name: 'settingsId',
type: 'int'
},
{
name: 'bPush',
type: 'boolean'
},
{
name: 'bEmail',
type: 'boolean'
},
{
name: 'sEmail',
type: 'string'
},
{
name: 'sToken',
type: 'string'
}
],
proxy: {
type: 'localstorage',
id: 'settings'
}
}
});
the store
Ext.define('LwvMediaReminder.store.SettingsStore', {
extend: 'Ext.data.Store',
alias: 'store.SettingsStore',
requires: [
'LwvMediaReminder.model.Setting'
],
config: {
autoLoad: true,
model: 'LwvMediaReminder.model.Setting',
storeId: 'SettingsStore'
}
});
the method in my SettingsController that should save the settings object, i always use only one record with the id 0:
onSaveSettingsButtonTap: function(button, e, eOpts) { var mainView = this.getMainView(),
store = Ext.getStore('SettingsStore'),
properties = {
settingsId: 0,
bPush: this.getPushCheckbox().isChecked(),
bEmail: this.getEmailCheckbox().isChecked(),
sEmail: this.getEmailField().getValue(),
sToken: this.getTokenField().getValue()
},
record = store.getById(0),
save = true;
// some form validation
if (properties.bEmail) {
if (properties.sEmail === '') {
save = false;
Ext.Msg.alert('Fehler', 'Bitte geben sie auch eine gültige Email-Adresse an.');
}
if (!this.validateEmail(properties.sEmail)) {
save = false;
Ext.Msg.alert('Fehler', 'Die angegebene Email-Adresse ist nicht gültig.');
}
}
// save the record
if (save) {
if (null !== record) {
record.set(properties);
} else {
store.add(properties);
}
store.sync();
mainView.pop();
}
},
I think i have found the solution.
It seems that the LocalstorageProxy has problems with given object ids.
I was setting the Object Id to 0 by default because i wanted only one object at a time with all my settings in one object.
Unfortunatly the local-storage wasn't able to write it to the browser storage.
No I have rewritten the code so that sencha can set the Id by itself. Now it seems to works fine.
And i can access the record by calling the .first() function from the store.
new code snippet:
var store = Ext.getStore('SettingsStore'),
// no preset id anymore
properties = {
bPush: this.getPushCheckbox().isChecked(),
bEmail: this.getEmailCheckbox().isChecked(),
sEmail: this.getEmailField().getValue(),
sToken: this.getTokenField().getValue()
},
// reading the first entry because there is always only one in my app
record = store.first();
I hope that will help somebody in the future.

Extjs 5.0 model POST values not received on server side (working Extjs 4.2)

I am upgrading our Extjs 4.2 app to Extjs 5.0.
I am able to bring up all the read only pages but i am getting issues when i try to update/save the data. I will really appreciate your help!!
My model data values are not showing up on the server side, i am able to print model with console.log(model) and it has all the values , but on the server side it only has id and all the other parameters are showing as null.
Here is proxy in the model :
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
id: 'user',
proxy: {
type: 'rest',
url : '/rest/update/user',
listeners: {
exception: function(proxy, response, operation) {
Ext.Msg.alert('Failed', 'Save the user Failed!');
}
}
},
fields: [
{name: 'id', type: 'int'},
{name: 'userName', type: 'string'},
{name: 'country', type: 'string'}
]
}
The controller :
onUserUpdateAction: function(button, event, action) {
var model = Ext.create('MyApp.model.User');
model.set('id', "123");
model.set('userName', "john");
model.set('country', "usa");
---
model.commit() / without commit() it does not add the id in URL like /user/123
model.save();
}
Here is the server side code :
#PUT
#Consumes({ "application/json" })
#Path("/Update/user/{id}")
updateUser(#PathParam("id") final int id, final User record);
First line log in the implementation class, id is there but all the other values are null
*** In updateUser() method, id : 123, record: User(id=123, **userName=null, country=null**)
The problem here is that you try to fool the Ext. You create new record with id - normally ids are assigned by the server. Therefore, you need to commit it to clear it phantom (new record) flag, so that Ext thinks it is already existing record. But, after commit, the record has no modified fields and, by default, only modified fields are sent to the server. Therefore, you need a writer configured, something like this:
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
{name: 'id', type: 'int'},
{name: 'userName', type: 'string'},
{name: 'country', type: 'string'}
],
proxy: {
type: 'rest',
url : 'success.php',
listeners: {
exception: function(proxy, response, operation) {
Ext.Msg.alert('Failed', 'Save the user Failed!');
}
}
,writer:{
type:'json'
,writeAllFields:true
}
}
});

ExtJS store/proxy doesn't send delete method to server

I'm trying to create simple ExtJs application that manages Users and User's Roles. Set of REST services provide this functionality on back end.
When I assign a new Role to a User, appropriate data store sends POST (create) requests to the service. However when I remove existing Role from a User, it's removed only from store locally without sending DELETE request to the service.
Here is my code:
Model:
Ext.define('UserRole', {
extend: 'Ext.data.Model',
fields: [
{ name: 'Id', mapping: "Id" },
{ name: 'RoleId', mapping: "RoleId" },
{ name: 'UserId', mapping: "UserId" }
]
});
Store With proxy:
Ext.define('UserRoleStore', {
extend: 'Ext.data.Store',
model: 'UserRole',
autoload: false,
proxy: {
type: 'ajax',
reader: {
type: 'json',
root: 'd.results'
},
api: {
read: '/accessmanager.svc/Users(\'{userid}\')/Roles?$format=json',
create: '/accessmanager.svc/UserRoles?$format=json',
update: '/accessmanager.svc/UserRoles?$format=json',
destroy: '/accessmanager.svc/UserRoles?$format=json'
},
updateApiUrlWithUserId: function (userId) {
this.api.read = this.api.read.replace('{userid}', userId);
}
}
});
Method that based on selected checkboxes updates the UserRole store
var chekboxes = Ext.ComponentQuery.query('userdetails #roleslist')[0];
var selectedUserId = this.selectedUserId;
var selectedUserRoleStore = this.selectedUserRoleStore;
Ext.each(chekboxes.items.items, function (cb) {
var exists = false;
Ext.each(selectedUserRoleStore.data.items, function (cs) {
if (cs.data.RoleId === cb.inputValue) {
exists = true;
}
});
if (cb.getValue() && !exists) {
var newRole = Ext.create('UserRole', { RoleId: cb.inputValue, UserId: selectedUserId });
selectedUserRoleStore.add(newRole);
} else if (exists && !cb.getValue()) {
// delete existing role
var record = selectedUserRoleStore.findRecord("RoleId", cb.inputValue);
selectedUserRoleStore.remove(record);
}
});
selectedUserRoleStore.sync();
Presumably your Id field is assigned on the server end when record is created. Correct? First try to specify idProperty: 'Id' in the model. Default value for this is 'id' but I think these are case sensitive.
Using idProperty ExtJs recognizes records as being 'dirty' and required to be updated on the server end.
The issue is your proxy needs to be a specialized REST type:
proxy: {
type: 'rest',
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.proxy.Rest
Also, you will probably be able to use the buildURL method to replace your own updateAPI... method.

Categories

Resources