Handling INVALID_SESSION_TOKEN ERROR CODE 251 with React Native + Parse + Facebook - ios

It seems as though the solution cited here:
Parse Facebook login fails with error code 251
No longer works. I have attempted both that and reconfiguring my Facebook app by resetting the secret, reconfiguring Parse with my new app credentials, and resetting xCode for a new simulator environment and all have failed. I continue to get old authentication data when the following function is called:
//sign up into parse db
Parse.FacebookUtils.logIn(authData, {
success: (user) => {
if (user.existed()) {
// login: nothing to do
console.log('User Already Logged In');
that.setState({loadingCurrentUser: false});
that.props.navigator.immediatelyResetRouteStack([{ name: 'home'}]);
} else {
// signup: update user data, e.g. email
console.log('getting user additional information');
var data = user.get('authData').facebook;
var api = 'https://graph.facebook.com/v2.3/'+data.id+'?fields=name,email&access_token='+data.access_token;
var fetchProfile = new FBSDKGraphRequest((error, result) => {
if (error) {
// TODO: error
this.setState({loadingCurrentUser: false});
} else {
console.log(result);
var name = responseData.name;
var email = responseData.email;
// FIXME: https://github.com/ParsePlatform/ParseReact/issues/45
var userId = {
className: '_User',
objectId: user.id
};
ParseReact.Mutation.Set(userId, {
username: email,
email: email,
name: name
}).dispatch();
that.setState({loadingCurrentUser: false});
that.props.navigator.immediatelyResetRouteStack([{ name: 'onboarding'}]);
}
}, '/me?fields=name,email');
// FIXME https://github.com/facebook/react-native-fbsdk/issues/20
// fetchProfile.start();
FBSDKGraphRequestManager.batchRequests([fetchProfile], function() {}, 10)
}
},
error: (user, error) => {
console.log('Error', error);
console.log(user.token);
switch (error.code) {
case Parse.Error.INVALID_SESSION_TOKEN:
Parse.User.logOut().then(() => {
this.onFacebookLogin(token);
});
break;
default:
// TODO: error
}
that.setState({loadingCurrentUser: false});
that.setState({errorMessage: error.message});
}
});
I am not sure how to proceed. Any help with error 251 and the most recent version of React Native (iOS)?

Related

Expo Notification Error in ios [Error: Another async call to this method is in progress. Await the first Promise.]

Please provide the following:
SDK Version: "^42.0.0",
Platforms(Android/iOS/web/all): iOS
Add the appropriate "Tag" based on what Expo library you have a question on.
Hello,
[expo-notifications] Error encountered while updating server registration with latest device push token., [Error: Another async call to this method is in progress. Await the first Promise.]
This error often occurs in expo app. And always occurs in build ios app.
Using the following code:
async function registerForPushNotificationsAsync() {
let token
if (Constants.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync()
let finalStatus = existingStatus
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync({
ios: {
allowAlert: true,
allowBadge: true,
allowSound: true,
allowAnnouncements: true,
},
})
finalStatus = status
}
if (finalStatus !== 'granted') {
console.log('noti cancel')
return
}
// token = (await Notifications.getExpoPushTokenAsync()).data
try {
await Notifications.getExpoPushTokenAsync().then((res) => {
console.log('getExpoPUshTokenAsync >> ', res)
token = res.data
})
} catch (err) {
console.log('getExpoPushTokenAsync error >> ', err)
}
} else {
Alert.alert(
'Must use physical device for Push Notifications'
)
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
})
}
return token
}
I have received a new credential, but I am still getting the error.

user unable to log in with passport Js on ios

I have a nodejs/express app that runs passport js with local strategy for auth.
Everything works well so far, but i have one user who is unable to log in from his iphone 6s . it doesn't matter which browser (safari,chrome etc) he use. we tried allowing cookies, deleting history and changing different setting on his device but nothing helps.
he has no problem logging in using different devices or his desktop computer.
this is my set up for passport auth :
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.post('/home',
passport.authenticate('local', { successRedirect: 'main',
failureRedirect: '/',
failureFlash: true })
);
I get this flash message when he tries to log in : ["Incorrect username..Incorrect username"]
any ideas how to debug or solve this issue? thanks!

sendbird error 400 bad request /user not found

I am trying to play with sendbird. I am getting this error . I am trying to make sendbird api work in react.js app. I have read the documentation and it wasnt clear to me. I have looked at stackoverflow earlier replies and Thats why , i tried to create channel after i get connected to sendbird.
VM2257:1 POST https://api.sendbird.com/v3/group_channels 400 (BAD
REQUEST)
error is here p {name: "SendBirdException", code: 400201, message: "User not found."}
I am trying to implement it in react.js . Here's my code. Can someone help me out with how to rectify this error.
import React, { Component } from 'react';
import * as SendBird from 'sendbird';
import './App.css';
var sb = new SendBird({'appId': '59BEEA34-BDC7-461B-B10B-63705C8B57C2'});
class App extends Component {
componentWillMount(){
sb.connect("ankur1", function(user, error) {
if(user){
console.log("looks like connected",user)
var userIds = ['unique_user_id1', 'unique_user_id2','ankur1'];
var name = "amazing1";
sb.GroupChannel.createChannelWithUserIds(userIds, false, name, function(createdChannel, error) {
if (error) {
console.error("error is here",error);
return;
}
console.log("success",createdChannel);
});
}
else{
console.log("looks like error")
}
})
}
sm(){
console.log("button clicked",sb)
var channel = "amazing"
/*
sb.channel.sendUserMessage("that is cool", '', function(message, error){
if (error) {
console.error(error);
return;
}
console.log(message);
});
*/
}
componentDidMount(){
}
render() {
var sm = this.sm.bind(this)
return (
<div>
<h1>ankur is here </h1>
<button onClick={sm}>click here</button>
</div>
);
}
}
export default App;
I actually had a similar problem yesterday. Googling around it actually led me here. Eventually, I found a way around it.
So, the first thing I do after creating the connection to SendBird is to create a connection for that user I wish to connect to.
var sb = new SendBird({
appId: 'YOUR SENDBIRD APP ID HERE'
});
sb.connect(UNIQUE_USER_ID, function(user, error) {
connectToUser();
});
function connectToUser(){
sb.connect(YOUR_OWN_USERID, function(user, error) {
sb.GroupChannel.createChannelWithUserIds([UNIQUE_USER_ID], true, UNIQUE_USER_ID+YOUR_OWN_USERID, '', '', '', function(createdChannel, error){
$scope.chatChannel = createdChannel;
if (error) {
console.log(error);
return;
}
});
});
}
Then, you can proceed to send your messages using the createdChannel
$scope.chatChannel.sendUserMessage(YOUR_MESSAGE_HERE, '', '', function(message, error){
if (error) {
console.error(error);
return;
}
console.log(message);
});
Let me know if that works.

NodeJS and Socket.io session handling

I'm currently trying to set a session (req.session.username) inside a socket.io connection however it will set it but when I refresh and log out the req.session.username, it logs undefined.
I have my socket.io in a router.get callback:
router.get('/', function(req, res, next) {
var io = req.app.get('socketio');
io.sockets.on('connection', function(socket) {
socket.on('login', function(data) {
var username = data.username;
utils.getUser(data.username, function(obj) {
if(typeof obj != 'undefined') {
if(data.password == obj.password) {
req.session.username = username;
socket.emit('loginSuccess', {message: "You have successfully logged in, whats up " + data.username + "?"});
} else {
socket.emit('loginError', {message: "Invalid password, please try again."});
}
} else {
socket.emit('loginError', {message: data.username + " does not exist, please create an account."});
}
});
});
});
console.log(req.session.username);
res.render('./users/login', {
logged: false
});
});

How to get updated session data on rails using AngularJs without page refresh

I'm currently working on integrating devise as an authentication backend with angular as its frontend.
I have faced a problem on when login and logout, the session data will be updated untill the page refresh.
What i will do get session data without page refresh..?
Thanks for your Answers...
AngularJs Controller :
function UsersCtrl($scope, Session) {"use strict";
$scope.CurrentUser = Session.requestCurrentUser();
$scope.login = function(user) {
$scope.authError = null;
Session.login(user.email, user.password)
.then(function(response) {
if (!response) {
$scope.authError = 'Credentials are not valid';
} else {
$scope.authError = 'Success!';
}
}, function(response) {
$scope.authError = 'Server offline, please try later';
});
};
$scope.logout = function() {
// alert("woow");
Session.logout();
};
$scope.register = function(user) {
$scope.authError = null;
console.log(user);
Session.register(user.email, user.password, user.confirm_password)
.then(function(response) {
}, function(response) {
var errors = '';
$.each(response.data.errors, function(index, value) {
errors += index.substr(0,1).toUpperCase()+index.substr(1) + ' ' + value + ''
});
$scope.authError = errors;
});
};
}
AngularJs Session Service:
angular.module('sessionService', ['ngResource'])
.factory('Session', function($location, $http, $q) {
// Redirect to the given url (defaults to '/')
function redirect(url) {
url = url || '/';
$location.path(url);
}
var service = {
login: function(email, password) {
return $http.post('/users/login', {user: {email: email, password: password} })
.then(function(response) {
service.currentUser = response.data.user;
if (service.isAuthenticated()) {
//$location.path(response.data.redirect);
$location.path('/store');
}
});
},
logout: function() {
$http.delete('/sessions').then(function(response) {
$http.defaults.headers.common['X-CSRF-Token'] = response.data.csrfToken;
service.currentUser = null;
redirect('/store');
});
},
register: function(email, password, confirm_password) {
return $http.post('/users', {user: {email: email, password: password, password_confirmation: confirm_password} })
.then(function(response) {
service.currentUser = response.data;
if (service.isAuthenticated()) {
console.log("authenticated");
$location.path('/');
}
});
},
requestCurrentUser: function() {
if (service.isAuthenticated()) {
return $q.when(service.currentUser);
} else {
return $http.get('/users').then(function(response) {
service.currentUser = response.data.user;
return service.currentUser;
});
}
},
currentUser: null,
isAuthenticated: function(){
return !!service.currentUser;
}
};
return service;
console.log(service);
});
One Thing about building applications like this (restful) is that understanding the the backend as an api and app as a front-end very well.
Then think about a story as such;
In the login screen of your app
Front-end: You Provided the credentials to your backend;
Back-end: Checked and authenticated then It will create a unique hash stored in db (JWT recommended to check expiration in frontend) to your Front-end.
Front-end:Save it in a cookie.
Also place it in your ajax setting header part as "Authorization: {token}"
Front-end: Then send each request with this header to your backend.
Back-end: Always check if the token is present and valid to provide resources.
http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/ this link has helped me understand the whole thing and misconceptions in the past.
use $window.location.reload(); before page redirect.
One way to achieve this could be overriding the devise sessions_controller destroy action and afrer doing sign_out #current_user return the session as json

Resources