i need a very simple login system for my web application with backbone.js
Workflow:
App Start -> LoginView -> When Logged In -> App
Here is my solution. What can i do better?
Login Status Model:
window.LoginStatus = Backbone.Model.extend({
defaults: {
loggedIn: false,
userId: null,
username: null,
error: "An Error Message!"
},
initialize: function () {
_.bindAll(this, 'getSession', 'setStorage');
},
getSession: function (username, password) {
var tmpThis = this;
$.getJSON('http://requestURL.de/getSession.php?username=' + username + '&password=' + password, function(data) {
if (data != null) {
tmpThis.setStorage(data.id, data.username);
$.mobile.changePage("#home");
}
});
},
setStorage: function(userId, username) {
localStorage.setItem("userId", userId);
localStorage.setItem("username", username);
this.set({ "loggedIn" : true});
}
});
Here is my Login View:
window.LoginView = Backbone.View.extend({
el: $("#login"),
initialize:function () {
this.render();
},
events: {
"click input[type=submit]": "onSubmit"
},
onSubmit: function(event) {
var username = $(this.el).find("#user-username").val(),
password = $(this.el).find("#user-password").val();
this.model.getSession(username, password);
return false;
},
render:function () {
if (this.model.get("loggedIn")) {
var template = _.template( $("#login_template").html(), {} );
} else {
var template = _.template( $("#login_template").html(), { "error" : this.model.get("error") } );
}
$(this.el).html( template );
}
});
My suggestion to you is making the login outside the backbone app and only after a success login process let them access the "single page app"
You can refer to this backbone project which does the login request using POST method. https://github.com/denysonique/backbone-login
Related
I have the following backbone model node that I am trying to use to fetch data from the server but at the moment I get a 404 error, I have checked my files and they seem to be correct
var app = app || {};
app.NotesModel = Backbone.Model.extend({
url:'/usernotes',
defaults: {
username:'',
email:'',
about:'',
editorNote:''
}
});
app.NotesView = Backbone.View.extend({
el:'#notes',
events: {
'click #save': 'save'
},
template1: _.template($('#about').html()),
template2: _.template($('#facts').html()),
initialize: function() {
app.NotesModel = new app.NotesModel({});
var email = $('#data-user').text();
app.NotesModel.fetch({data: {email: email},type:'GET' });
this.render();
},
render: function() {
},
This is what the route file looks like
app.get('/account/usernotes/', require('./views/account/usernotes/index').init);
app.get('/account/usernotes/:email', require('./views/account/usernotes/index').find);
and the functions for the routes
'use strict';
exports.init = function(req, res){
if (req.isAuthenticated()) {
//console.log(req.user.email);
res.render('account/usernotes',
{ data : {
user : req.user.email
}
});
}
else {
res.render('signup/index', {
oauthMessage: '',
oauthTwitter: !!req.app.config.oauth.twitter.key,
oauthFacebook: !!req.app.config.oauth.facebook.key,
oauthGoogle: !!req.app.config.oauth.google.key
});
}
};
exports.find = function(req,res) {
console.log('here');
console.log(JSON.stringify(req));
}
Doing the console.log() doesn't give me any output at all.
Here is a similar question.
Try this:
app.NotesModel.fetch({data: $.param({email: email}) });
or this:
app.NotesModel.fetch({data: {email: email}, processData: true });
Calling navigate after saving a model.
this.model.save({},{
success: function(model, response, options){
Backbone.history.navigate('getCampaigns', {tigger: true});
}
});
But it never hits the specified route.
Route class
var Router = Backbone.Router.extend({
routes: {
"":"home",
"login":"login",
"getCampaigns":"getCampaigns"
},
start: function() {
Backbone.history.start({pushState:true});
},
home: function() {
var loginView = new LoginView({model: loginModel});
loginView.render();
$(".container").append(loginView.el);
},
login: function(event) {
event.preventDefault();
},
getCampaigns: function() {
this.dashboardList.fetch();
$('.container').html(this.dashboardListView.render().el);
}
});
var app = new Router();
app.start();
You have an error in your code :
Backbone.history.navigate('getCampaigns', {trigger: true}); // not {tigger: true}
Trying to implement Login functionality from the Node server. I am able to send the request from backbone model to node server. Node server calls another site and get the response back from another site.
Now if the login is successful, another page should display with response. But if the login turns unsuccessful, login page should display the error message.
Model:
var LoginModel = Backbone.Model.extend({
url:'http://localhost:3000/login',
defaults: {
email:"",
password:""
},
parse: function(resp) {
console.log('Model: Got the response back');
return resp;
},
login: function() {
console.log('Model: Login function:'+JSON.stringify(this));
this.save(
{}, {
success: function(resp) {
console.log('success'+JSON.stringify(resp));
},
error: function(error) {
console.log('error: '+JSON.stringify(error));
}
});
console.log('Model: Got the response back:');
}
});
var loginModel = new LoginModel();
View:
var LoginView = Backbone.View.extend({
url: 'http://localhost:3000/login',
template:_.template('<div class="form-signin">'+
'<h2 class="form-signin-heading">Please sign in</h2>'+
'<input type="text" id="email" class="form-control" placeholder="Email address" required="" autofocus="">'+
'<input type="password" id="password" class="form-control" placeholder="Password" required="">'+
'<button id="loginBtn" class="btn btn-lg btn-primary btn-block" >Sign in</button>'+
'</div>'),
events: {
"click #loginBtn":"login"
},
initialize: function() {
this.model.on('change', this.render, this);
},
render: function() {
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
},
login: function() {
console.log('view signIn');
this.model.set({
"email": $('#email').val(),
"password": $('#password').val()
});
this.model.login();
}
});
var loginView = new LoginView({model: loginModel});
loginView.render();
$(".container").append(loginView.el);
Note: I am new to backbone and read about routes. It was not very clear to me.
Backbone.Router provides methods for routing client-side pages
So in your case, your code should look like :
var LoginModel = Backbone.Model.extend({
url:'http://localhost:3000/login',
defaults: {
email:"",
password:""
}
}
View
var LoginView = Backbone.View.extend({
el: '.container'
template:_.template('...'),
events: {
"click #loginBtn":"login"
},
initialize: function() {
this.listenTo(this.model, 'change', this.render);
},
render: function() {
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
},
login: function() {
console.log('view signIn');
this.model.set({
"email": $('#email').val(),
"password": $('#password').val()
});
console.log('Model: Login function:'+JSON.stringify(this.model));
this.model.save(
{}, {
success: function(resp) {
console.log('success'+JSON.stringify(resp));
},
error: function(error) {
console.log('error: '+JSON.stringify(error));
}
});
console.log('Model: Got the response back:');
}
});
Router
var Router = Backbone.Router.extend({
routes : {
"": "home",
"login" : "login"
},
home: function() {
// your home page
}
login: function() {
var loginModel = new LoginModel();
var loginView = new LoginView({model: loginModel});
loginModel.fetch();
}
})
new Router();
Backbone.history.start();
I have an unwanted route redirect after authentification
My base url is
http://127.0.0.1:8020/VT/
If the user isn't logged in localstorage, i'll load the login view.
The main menu view render correctly if the login succeed,
I have this unwanted automaticaly redirection to
http://127.0.0.1:8020/
This only happen on webkit browser. (haven't tried on IE)
Router = new MainRouter();
Backbone.history.start({
pushState: false,
root: "/VT/"
});
var MainRouter = Backbone.Router.extend({
routes: {
"": "login",
"login": "login",
"main": "mainMenu"
},
showView: function(view){
if (this.currentView){
this.currentView.close();
}
this.currentView = view;
this.currentView.render();
$('#wrapper').html( this.currentView.el );
},
login: function(){
var result = app.session.isLoggedIn();
if(result == true){
this.navigate('main', {trigger: true, replace: true});
}
else{
var loginView = new LoginView();
this.showView( loginView );
}
},
mainMenu: function(){
var mainMenu = new MainMenuView();
this.showView( mainMenu );
},
});
var LoginView = Backbone.View.extend({
name: "Login",
el: $('#page-login'),
initialize : function() {
this.template = _.template( app.get("tpl/nav/login.html") );
this.clearStatusBar();
},
render: function(){
var renderedContent = this.template();
$(this.el).html(renderedContent);
return this;
},
events: {
"click input[type=submit]": "loginAction"
},
validate: function(){
// some validation code
},
loginAction: function(){
if( this.validate() ){
app.router.navigate('main', {trigger: true, replace: true});
}
else{
alert('Login failed');
}
},
});
I can't figure it out why. Any suggestions ?
I'm new to backbone and I'm trying to send and receive data from the server in Json format. It just won't work. Here's my code (BTW, I'm using backbone aura):
Collection
define(['sandbox', '../models/message'], function(sandbox, Message) {
'use strict';
var Messages = sandbox.mvc.Collection({
model: Message,
url: '/messagelist.php',
localStorage: new sandbox.data.Store('messages-backbone-require'),
parse: function(response){
return response.rows;
}
});
return Messages;
});
Model
define(['sandbox'], function(sandbox) {
'use strict';
var Message = sandbox.mvc.Model({
defaults: {
opened: '',
messageid: '',
phonenumber: '',
numbername: '',
text: ''
},
parse: function(data){
return data;
}
});
return Message;
});
View
define(['sandbox', '../models/message', 'text!../templates/incoming_messages.html'], function(sandbox, Message, incomingMessagesTemplate) {
'use strict';
var AppView = sandbox.mvc.View({
widgetTemplate: sandbox.template.parse(incomingMessagesTemplate),
events: {
'click .refresh': 'refresh'
},
initialize: function() {
this.$el.html(this.widgetTemplate);
sandbox.events.bindAll(this);
this.collection.bind('createMessageList', this.createMessageList);
},
createMessageList: function() {
// Will work with the received data here
},
render: function() {
var handle = 'h4';
this.$el.draggable({handle: handle});
this.createMessageList();
},
refresh: function() {
this.createMessageList();
}
});
return AppView;
});
Main
define(['sandbox', './views/app', './collections/messages'], function(sandbox, AppView, Messages) {
'use strict';
return function(options) {
var messages = new Messages();
new AppView({
el: sandbox.dom.find(options.element),
collection: messages
}).render();
messages.fetch({
data: {
type: 'incoming',
offset: 0,
offsetcount: 25
},
type: 'GET',
success: function() {
console.log(messages.models); // Shows an empty array.
}
});
};
});
I've check logs and it seems that the ajax request (collection.fetch()) is not firing or is not able to communicate with the server. How can I fix this?
The problem is with the Backbone.LocalStorage plugin. When you assign Collection.localStorage, the plugin takes over the fetch command and reads the data from local storage instead of the server.
See my answer in this SO question on some options on how to solve this.