Backbone Login Verification - javascript

I'm asking this question in part for a whole class. We are having a hard time getting a token for login. Also, if you guys don't mind, tells us how we can improve our question asking skills.
"I am trying to use my API to assign the account we are logging in as with a token. I've tried various things, but nothing really seems to work. What needs to be sent to the URL for the token to be generated looks like this:
{
"grant_type": "password",
"username": "user#example.com",
"password": "password"
}
Then we need to be able to receive the token so that we can do some things with that account. Could anybody push me in the right direction to accomplish this? Also want to add - do we need a model and collection for our token?
Our Goal is to be able to retrieve a token, so that after we create a user we can login into our app on the login page.
// User Model and Collection. Used to input user data.
var User = Backbone.Model.extend({
url: "https://twitterapii.herokuapp.com/users"
});
//Collection for when we GET data from API
var Users = Backbone.Collection.extend({
model: User,
url: "https://twitterapii.herokuapp.com/users",
parse: function(response) {
return response.data;
}
})
//Collection for when we GET data from API
var UsersTokens = Backbone.Collection.extend({
model: User,
url: "https://twitterapii.herokuapp.com/oauth/token",
parse: function(response) {
return response.data;
}
})
var signinView = Backbone.View.extend({
tagName: 'section',
template: _.template($('#signInTemplate').html()),
events: {
"click .signinButton": 'handleLoginClick'
},
send: function(){
var signin = this.$('.signinButton').val();
console.log("clicking!!");
var email = this.$(".email").val();
var password = this.$(".password").val();
logUser: UsersTokens.fetch( {
headers: {
grant_type: password,
username: email,
password: password
} });
},
render: function(){
this.$el.html(this.template());
},
handleLoginClick: function(){
event.preventDefault();
this.send();
console.log("login clicksss!!");
}
});

Related

I need to update/Refresh my JSON Web Token

I need to update/refresh my JSON web token. I have a value of hasPaid that is created and stored inside of my JWT. It works successfully when I login. Because that is when the JWT is created. However, when I pay inside of the application; the JWT isn't updated to reflect that I have paid. And the JWT is reading this data from the database. So i need the JWT to update or refresh and reflect this change.
Here is where my JWT is created:
userSchema.methods.generateJwt = function() {
console.log("I'm creating a JSON WebToken");
console.log(this.hasPaid);
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
hasPaid : this.hasPaid,
exp: parseInt(expiry.getTime() / 1000),
}, "MY_SECRET"); // DO NOT KEEP YOUR SECRET IN THE CODE!
};
Here is my AJAX request where I make the payment. I need it update here:
$.ajax({
url: 'http://localhost:8082/charge',
type: 'POST',
data: {
stripeToken: response.id,
currentUser: user
},
complete: function(response, state, e) {
window.location.assign("video");
return e.localStorage["token"]; // on success of ajax post update JWT
}
});

Ember not transitioning to profile after logging in

I am working on an Ember project with a Node backend. I would like to have a user login/ signup on the client side, send an AJAX POST request to the server to check its authentication and then send back a thumbs up or a thumbs down accordingly. If a thumbs up is returned I want to transition the user to their profile. However, when the person submits the form, a successful POST request is sent but nothing happens as far as transitioning to another page. Any ideas as to why this is happening?
Here is what my Route looks like:
// Username for the new user
email: '',
// Password for the new user
password: '',
actions: {
manualLogin: function() {
const email = this.get('email');
const password = this.get('password');
var temp = this;
Ember.$.ajax({
type: "POST",
url: "http://localhost:8080/api/login",
data: { email: email, password: password }
})
.done(function(data) {
console.log('transition to /user, ' + data);
temp.transitionTo('user');
})
.fail(function(data) {
console.log(data);
});
//this.transitionTo('user');
return;
}
}
Here is my Router:
Router.map(function() {
this.route('explore', { path: '/' });
this.route('user');
this.route('login');
this.route('signup');
});
And the code for the submit button with the login template:
<button class="button radius" type="submit" {{action 'manualLogin'}}>Login</button>

Backbone persistant view with persistant data

I have a navigation bar that is pretty much the only piece of persistant template in my web application (in that is always there regardless of route).
In that navbar I show a Login link if the user is not logged in, and if they are I show their name, the problem I having is that I can't get the nav to keep it's state. The uses logins,
runLogin: function(e) {
e.preventDefault();
var element = $(e.currentTarget),
self = this;
$.when($.ajax({
url: 'http://app-api.dev/api/oauth/access_token?grant_type=password&client_id=1&client_secret=xyz',
method: 'POST',
data: element.serialize(),
dataType: 'json',
success: function(data) {
// Set the cookie, this will need to be sent in every singal request going foward.
$.cookie('access_token', data.access_token);
// So we have the access token we use this to populate our user details
},
error: function(response) {
// We can build a universal error view that would be quite and pretty easy to do.
}
})).done(function() {
$.ajax({
url: 'http://app-api.dev/api/users/me',
dataType: 'json',
method: 'GET',
success:function(user) {
self.model.set(user);
self.launchDashboard();
}
});
})
},
launchDashboard: function() {
localStorage.setItem('user', '');
localStorage.setItem('user', JSON.stringify(this.me));
App.Routes.Application.navigate('dashboard', { trigger: true } );
}
Basically I login, request my details from the API, and use those to set a model, the model I am setting has already been passed in to the navigation view, and has a change listener on it.
showUserDetails: function() {
this.loggedInUserMenu = new App.Views.navigationViewLoggedIn({
model : this.model
});
},
the above fires this,
App.Views.navigationViewLoggedIn = Backbone.View.extend({
el: '.navbar-right',
template: _.template( $('#tpl-navigation-logged-in').html() ),
events: {
},
initialize: function() {
this.render();
},
render: function() {
this.$('.li-login').replaceWith( this.template({
user: this.model.toJSON()
}));
}
});
Router
initialize: function() {
Pops.Models.AuthUser = new Pops.Models.User;
this.navigation_bar = new Pops.Views.navigationView({
model: Pops.Models.AuthUser
});
},
On successful login the loggedInNavigation is visisble, and I am at app-client.dev/#dashboard however if I navigate to `app-client.dev/#groups I lose the loggedInNavigation and it reverts back to just saying "login".
Why?
=== Edit I ahve attached the method that creates the main nav it is done on the initialize of the routes. The method that does the view update is all the in the previous code, login sets the model that is int he navigation view, listening for a change ===

Fetch JSON Twitter search data with WinJS

Trying to authenticate to receive search data feed from Twitter in a Windows 8 app. This is straight from a text book written when Twitter didn't require authentication so it should work although I've added user and password without any results (worse, the app terminates).
JS:
args.setPromise(WinJS.UI.processAll().then(function () {
WinJS.xhr({
url: "http://search.twitter.com/search.json?q=windows8",
//type: "GET",
user: "myusername",
password: "mypassword"
}).then(
function (result) {
var jsonData = JSON.parse(result.responseText);
//create a binding list object from the json
var bindingList = new WinJS.Binding.List(jsonData.results);
//get the list view element from the DOM
var listView = document.getElementById("sampleListView").winControl;
//bind the data sources
listView.itemDataSource = bindingList.dataSource
});
}));
HTML:
<div id="sampleListView" data-win-control="WinJS.UI.ListView"></div>

create instance of model on AJAX call success

I have a User model:
var UserModel = Backbone.Model.extend({
defaults: {
handle: '',
email: '',
uuid: '',
userpic: '',
tokenlogin: ''
}
});
I also have a collection called UserSignIn, although I'm not sure why:
var UserSignIn = Backbone.Collection.extend({ model: UserModel });
And inside of my SignInView view, I have the following function...
signIn: function(e) {
e.preventDefault();
this.collection.fetch({
type: 'POST',
url: 'http://localhost/app/api/User.php',
dataType: "json",
data: $.param({
req: "REQUSERSIGNIN",
platform: "WEB",
useremail: $('#userSignIn #userEmail').val(),
userpass: $('#userSignIn #userPassword').val()
}),
success: function(data) {
// In here, I'd like to create an
// instance of the model which I'd
// like to pass around my app.
var user = new UserModel({
handle: data.HANDLE,
email: data.EMAIL,
uuid: data.UUIDUSER,
userpic: data.USERPIC,
tokenlogin: data.TOKENLOGIN
});
}
});
}
As you can see, all I am trying to do is create an instance of a User on success of the BackBone.fetch() function.
I'd like to understand how to then pass around this new "user" UserModel() instance around my app. When I try to console.log(user) I get a "ReferenceError: user is not defined" when clearly I just created it in the success callback of the fetch function.
Can someone explain to me why?
you have to insert it into your collection if you wanna follow the right way in backbone.
I think that you can do this:
into your initialize in the view insert this:
initialize: function(){
//..... your code in initialize
this.userModel = null;
this.collection = new UserCollection();
},
signIn: function(e) {
e.preventDefault();
var here = this;
this.collection.fetch({
type: 'POST',
url: 'http://localhost/app/api/User.php',
dataType: "json",
data: $.param({
req: "REQUSERSIGNIN",
platform: "WEB",
useremail: $('#userSignIn #userEmail').val(),
userpass: $('#userSignIn #userPassword').val()
}),
success: function(data) {
var user = {handle: data.HANDLE,email: data.EMAIL,uuid: data.UUIDUSER,userpic: data.USERPIC,tokenlogin: data.TOKENLOGIN};
here.userModel = new UserModel(user);
here.collection.addUser(here.userModel);
}
});
}
You UserCollection must be something like this:
var UserCollection = Backbone.Collection.extend({
model: UserModel,
initialize:function(){
console.log('Initialized User collection');
},
addUser: function(users, options) {
return this.add(users, options);
}
});
To console each element of your collection you can try this (if you run this code inside your success function use here instead of this):
this.collection.each(function(user, index) {
console.log(user);
//if you want to set a value of your model:
user.set('email', 'yournewemail#email.it');
//if you want to get some value
user.get('email');
});
The variable user is scoped only to within the success function of your SignInView view, so you can't console.log(user) which is looking for a user variable from the global scope. You could put console.log(user) right after creating the user within the success function to see that it is created, since this would find the local variable user.
To access it from the app, you could also declare var user; outside the fetch function and then simply set it within the fetch function.

Categories

Resources