Sequelize model only updates when I log out then log back in - sql-update

So basically my issue is that when a user is logged in they can take a test. When the test is passed a user is given points and their level is updated using a put route. Once the put route has run the user is redirected back to their homepage where their stats are displayed. If I look in Postman after the request is made I can see the changes. However, the get route on the user's homepage is still displaying as the previous data. Only when I log out then log back in does the user object actually update on the app.
the get request is called in the document. ready function for the user's page like so...
$(document).ready(() => {
// This file just does a GET request to figure out which user is logged in
// and updates the HTML on the page
$.get("/api/user_data").then(data => {
console.log(data)
$(".user-name").text(data.username);
$(".first-name").text(data.first);
$(".last-name").text(data.last);
$(".email").text(data.email);
$(".xp").text(data.points);
});
the put route is in a function that runs when the last question of the test is answered. It looks like this...
function endGame() {
console.log("END OF GAME SCORE: " + score);
$(".quiz-container").css("display", "none");
console.log(data.points);
console.log(data.level);
var addPoints = score * 100 + data.points;
var newLevel = data.level + 1;
$.ajax({
url: "/api/user_data",
method: "PUT",
data: {
id: data.id,
level: newLevel,
point: addPoints
},
error: function(req, err) {
console.log(err)
},
success: function(res, err) {
window.location.replace("/members");
}
}).then(result => {
console.log("user info updated");
console.log(result);
window.location.replace("/members");
});
}
As you can see the user is redirected over to the "members" page which is where the get request is sent on the document being ready. I'm pretty new so any help would be greatly appreciated.
also here is the db.sync method I had been working with force true and force false now i just have...
db.sequelize.sync({}).then(() => {
app.listen(PORT, () => {
console.log(
"==> 🌎 Listening on port %s. Visit http://localhost:%s/ in your browser.",
PORT,
PORT
);
});
});

Related

Ionic facebook login for native

I have implemented the facebook login for my ionic application, which works perfectly when run on web. When i build the application, create an apk of the same, and try to run on my mobile device, nothing happens.
The login is:
openFB.login(
function (response) {
if (response.status === 'connected') {
console.log('Facebook login succeeded, got access token: ', response);
openFB.api({
path: '/me',
success: function (data) {
console.log("My Data", data);
userData.name = data.name;
userData.picture = 'http://graph.facebook.com/' + data.id + '/picture?type=small';
localStorageService.set('user', userData);
$timeout(function() {
$state.go('app.home');
}, 0);
},
error: function(error) {
console.log("Error here:", error);
}
});
} else {
console.log('Facebook login failed: ' + response);
}
}, { scope: 'email, public_profile' });
Have used openFB for the login. After clicking, following popup comes up.
After clicking the okay, nothing gets logged. No console message.
Can some one help me for finding out this issue, where i am not able to do the facebook login, when run on actual device.
You need to whitelist the redirect url. You can set it in
Products > Facebook Login > Settings > Client OAuth Settings
Take a look into this question.
please set redirect URI in
Products > Facebook Login > Settings > Client OAuth Settings
http://localhost/callback
please follow the below procedure to register your app in facebook developer site
https://ccoenraets.github.io/ionic-tutorial/ionic-facebook-integration.html
and use the below code to complete the procedure of facebook login
$cordovaOauth.facebook("appId", ["email", "public_profile"]).then(function(result) {
//alert(JSON.stringify(result));
//$localStorage.accessToken = result.access_token;
$http.get("https://graph.facebook.com/v2.2/me", {
params: {
access_token: result.access_token,
fields: "id,name,gender,location,email,picture,relationship_status",
format: "json"
}
}).then(function(result) {
// alert(JSON.stringify(result));
$scope.loginflowusingsociallogin(result.data.email);
}, function(error) {
alert("There was a problem getting your profile. Check the logs for details.");
alert(JSON.stringify(error));
});
});
i used Oauth 2.0 authentication for ionic.
I used this code and worked fine for me

Can't push data to Firebase from within an Alexa Skill hosted on AWS Lambda

I have a database in Firebase to which I'm trying to write some data from within my Alexa Skill. The Node.js code for that skill sits inside an AWS Lambda function and when that code is run I want to push some data to Firebase.
I've tested the code that connects to and pushes to Firebase outside of Lambda and it works exactly as expected. Below is that code:
var firebase = require('firebase');
firebase.initializeApp({
databaseURL: 'https://myapp.firebaseio.com',
serviceAccount: './myapp.json',
});
var cart = firebase.database().ref('/cart');
console.log(cart);
cart.push( {
item: 'apples', quantity: '1', amount: '0'
}, function(error) {
if (error) {
console.log("Data could not be saved." + error);
} else {
console.log("Data saved successfully.");
}
});
This same code doesn't push anything to the database instance when executed from within the Lambda function. I read online that Lambda timeout limit could be a reason for this, so I increased the timeout limit to a minute, and it still doesn't run as expected. I've also tried using the Firebase REST API instead of their Node.js SDK and that didn't work either. What is the correct way to push data to Firebase from within AWS Lambda?
I think I know why this happens, I had a similar issue and this is what I've done.
If you want to write some date into your database you need to make sure that you don't call this.emit(*****) until you are done. As soon as you return the response to the user the Thread gets closed and your information doesn't get saved.
The easiest way to solve this problem is to return the response to the user once you get confirmation that the information has been saved.
In case of Firebase something like this:
function writeUserData(userId) {
// Get a key for a new Post.
var userKey = db.ref('users/').push().key;
var reference = db.ref('users/' + userKey).set({
user: userId
});
reference.then(() => {
alexa.emit(':ask', "Works");
},
(err) => {
alexa.emit(':ask', "Does not work");
});
}
I couldn't get anything saved until I started doing it like this.
Hope it helps.
I've run into this too and the only way I've figured out how to get it to work is to delay the lambda callback function in the handler. Try this and let me know if it works.
var firebase = require('firebase');
firebase.initializeApp({
databaseURL: 'https://myapp.firebaseio.com',
serviceAccount: './myapp.json',
});
exports.handler = (event, context, callback) => {
var cart = firebase.database().ref('/cart');
console.log(cart);
cart.push( {
item: 'apples', quantity: '1', amount: '0'
setTimeout(()=>{
callback(null, 'success');
},2000);
}, function(error) {
if (error) {
console.log("Data could not be saved." + error);
setTimeout(()=>{
callback(error);
},2000);
} else {
console.log("Data saved successfully.");
setTimeout(()=>{
callback(null, 'success');
},2000);
}
});
}

Parse Cloud Code with facebook API not working properly

I want to get a location Id from facebook API (that is already in my DB) and than use this to get the events from that location.
So, i'm first running a query to get this info and than adding this result as a parameter in my url. The fact is that the query is returning the result properly but when calling the httpRequest this is failling. Its important to say that my httpRequest works when I use the locationId hard coded.
I guess this problem is occuring because of the response calls but i cant figure out how to fix it. I'm also looking on a better way to design this code. Any ideas?
Parse.Cloud.define("hello", function(request, response) {
var query = new Parse.Query("Location");
query.find({
success: function(results) {
locationId = results[0].get("locationFbId");
console.log(locationId);
},
error: function() {
response.error("Failed on getting locationId");
}
});
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken,
success: function(httpResponse) {
console.log(httpResponse.data);
response.success("result");
},
error:function(httpResponse){
console.error(httpResponse.message);
response.error("Failed to get events");
}
});
});
Adolfosrs, your problem here is that your two requests are running asynchronously on different threads. Therefore, your first request isn't returning until after your second request has been called. I would suggest chaining the requests as below so that your second request will be initialized with the data retrieved from the first request.
Parse.Cloud.define("hello", function(request, response) {
var query = new Parse.Query("Location");
query.find({
success: function(results) {
locationId = results[0].get("locationFbId");
console.log(locationId);
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken,
success: function(httpResponse) {
console.log(httpResponse.data);
response.success("result");
},
error:function(httpResponse){
console.error(httpResponse.message);
response.error("Failed to get events");
}
});
},
error: function() {
response.error("Failed on getting locationId");
}
});
});

How to client side authentication with Emberjs

First of all I don't use Ruby nor Devise :) (all my searches led me to plugins that kind of rely on Devise)
I want to do pretty simple authentication with Ember, I have a REST backend that blocks requests without a proper cookie(user-pass) and i want Ember to watch when it gets 403 forbidden (won't let you to transition into protected URLs) and then pop up a user-login dialog.
So when a user tries to send a new message for example(lets say i've built a forum) Ember will fire the request and if it gets 403 it will block the transition and popup a login form and will retry the transition after the login have completed
Also is there a way to get the errors from ember-data and respond to them? (if a user tries to change an attribute he can't access i would like to inform him about it[Access denied or something like that])
I want to use custom errors that my server will send to ember data not just error numbers but words like "Sorry you can't change this before 12 PM"
You can simply listen to the response of your server and transition to your LOGIN (or whatever you call it) route. In my apps I happen to keep two types of routes (LOGIN and AUTHENTICATED). When they access the authenticated routes without logging in, they get a 401 unauthorized error and get transitioned to the LOGIN route.
// AuthenticatedRoute.js
redirectToLogin: function(transition) {
// alert('You must log in!');
var loginController = this.controllerFor('login');
loginController.set('attemptedTransition', transition);
this.transitionTo('login');
},
events: {
error: function(reason, transition) {
if (reason.status === 401) {
this.redirectToLogin(transition);
} else {
console.log(reason);
window.alert('Something went wrong');
}
}
},
model: function () {
return this.store.find('post');
},
So now when the user requests for post he gets a 401 and gets transitioned to LOGIN controller.
// LoginController.js
login: function() {
var self = this, data = this.getProperties('username', 'password');
// Clear out any error messages.
this.set('errorMessage', null);
$.post('/login', data).then(function(response) {
self.set('errorMessage', response.message);
if (response.success) {
alert('Login succeeded!');
// Redirecting to the actual route the user tried to access
var attemptedTransition = self.get('attemptedTransition');
if (attemptedTransition) {
attemptedTransition.retry();
self.set('attemptedTransition', null);
} else {
// Redirect to 'defaultRoute' by default.
self.transitionToRoute('defaultRoute');
}
}
});
}
The basic answer you need is capturing the events in the route and transitioning accordingly. I just happened to include the code for attempted transition as it comes in handy at times.

Update / Delete a tab from a facebook page using the Graph API returns "(#210) Subject must be a page."

I am trying to delete an application tab from a facebook page.
According to the documentation, I should issue a DELETE request to "https://graph.facebook.com/PAGE_ID/tabs/TAB_ID" with a PAGE access token, but when I do so I get the error "(#210) Subject must be a page."
The same happens when trying to update a tab.
I have requested the user for "manage_pages" permission and I have the correct access_token (Adding a tab works perfectly).
the exact request is: https://graph.facebook.com/212757048770606/tabs/app_289329597785433 (with an access token)
Does anyone know what am I doing wrong?? or is there an open bug report?
Thanks alot
I don't have a solution for you, but I do know that I had some problems with removing a tab that boiled down to the fact that the tab's ID (returned from a call to get /PAGE_ID/tabs) already includes the page ID and "tabs" path.
Initially I was building my URL by taking the tab ID and sticking it on the end of /PAGE_ID/tabs/, but that didn't work because the URL ended up being something like /12345/tabs/12345/tabs/app_4567. Once I realized that the tab ID was sort of "compound" already, I got the Remove to work.
Add the page access token to the call of Facebook API
var PageAccessToken = 123456789123456789123456789123456789;
FB.api(
"/{page_id}/tabs",
"POST",
{
"object": {
"app_id": "{page_id}"
}
},{
"access_token": PageAccessToken
},
function (response) {
if (response && !response.error) {
console.log(response);
} else {
console.log(response.error);
}
}
);
function DeleteTabPage(){
var pid = page_id;
var at = access_tocken;
debugger;
FB.api(pid + '/tabs/app_{your app id}', 'DELETE', { app_id: your app id, access_token: at }, function (response) {
debugger;
if (!response || response.error) {
debugger;`enter code here`
alert('Facebook add app error ' + response.error);
} else {
console.log(response);
debugger;
// alert('App has been added');
}
}); /* end of page/tabs*/
}