I've got a simple Backbone.js app which uses json-server as a backend. I have a function to log in, that finds a user from the collection, but I don't get how will I save my session. I thought about storing a parameter in cookies that later will be checked on every redirect. Here is my model:
var User = Backbone.Model.extend({
defaults: {
login: '',
password: '',
authToken: ''
}
});
And here is my collection:
var UserCollection = Backbone.Collection.extend({
url: 'http://localhost:3000/users',
// creates a random token
setToken: function () {
var rand = function () {
return Math.random().toString(36).substr(2)
}
var token = rand() + rand();
this.set({authToken: token});
}
});
And this is the view with login function
var LoginView = Backbone.View.extend({
initialize: function () {
this.collection = new UserCollection();
// template
}
// render function omitted
signIn: function () {
var login = $('#login').val();
var password = $('#password').val();
/**
finds a user within with the values from input fields
inside the collection
*/
if (login && password) {
this.collection.fetch({
data: {
login: login,
password: password
}
});
}
}
});
This function returns me an array with one object that is my requested model. All that I need is to use my setToken
method and to save this model's authToken
in cookie so that I could use it elsewhere in app, but I don't actually get how to do that.