Problem handling Parse users in a web app - javascript

Here is some JS code, related to handling Parse users in a web app, with unexpected behaviour.
......
Parse.initialize(process.env.APP_ID);
Parse.serverURL = process.env.SERVER_URL;
Parse.User.logIn(req.body.usrname, req.body.password, {
success: user => {
console.log("OK-OK:"+user);
checkIfLoggedIn();
res.render('pages/index.ejs', {});
},
error: (user, error) => {
console.log("NG-NG:"+user, error);
checkIfLoggedIn();
res.render('pages/login.ejs', {});
},
});
......
function checkIfLoggedIn() {
var currentUser = Parse.User.current();
if (currentUser) {
console.log("Parse.User.current is A REAL USER -- logged in!!")
} else {
console.log("Parse.User.current is NULL -- login failed!!")
}
}
Now, below is the question.
When running the code above, the messages:
"OK-OK:" and "NG-NG:" both show up in the logs as expected. But the call to the function checkIfLoggedIn() always displays a failure:
Parse.User.current is NULL -- login failed!!
Why is that? Shouldn't it display a success when we reach "OK-OK:"?

Related

Why does this javascript code not redirect the user after the metamask transaction?

I want to make a javascript code that does a metamask transaction and redirects the user to another page after the transation is completed. How easy this may sound, I can not figure it out.
My current code lets the user complete the transaction, but it does not redirect the user to another page. Instead, it gives this error: "MetaMask - RPC Error: invalid argument 0: json: cannot unmarshal non-string into Go value of type common.Hash"
I have looked it up, but I could not find any possible fix for my problem.
This is my code:
try {
// send the transaction
ethereum.send({
method: 'eth_sendTransaction',
params: [
{
to: contractAddress,
from: userAddress,
value: amt
},
],
}, (error, transactionHash) => {
if (error) {
console.error(error);
} else {
// check the status of the transaction using the transaction hash
ethereum.request({
method: 'eth_getTransactionReceipt',
params: [transactionHash],
}).then((receipt) => {
// check if the transaction was successful
if (receipt.status === '0x1') {
console.log(`Transaction was successful`);
// redirect to another page
window.location.href = "page.php";
} else {
console.log(`Transaction failed`);
}
}).catch((error) => {
// This is the line of code the error is assigned to:
console.error(error);
});
}
});
} catch (error) {
console.error(error);
}
});
} else {
document.getElementById("bericht").innerHTML = "Install Metamask before you continue";
return;
}
I have tried looking the error up on internet, but nothing significant showed up. Could anyone help? Thank you in advance!

react native TypeError: Cannot read property 'navigation' of undefined

I am using the FacebookAuthProvider by firebase to login my users from my platform.
I'm using react native in expo with firestore and it was working fine till I tried to add in some checks to redirect users to the correct screens after login. There are two different roles (administrators and users) which have to be separate right after the login.
if (/* user is administrator */) {
this.props.navigation.navigate('Admin');
} else {
this.props.navigation.navigate('Main');
}
After adding this method to separate users by there roles, I got this error:
react native TypeError: Cannot read property 'navigation' of undefined
Later I will add some more details (log files etc. as soon as I've learned how to grep them from my locale machine).
For better understanding I put my whole code here (sorry for the bad indentations which lesses the readability):
const auth = firebase.auth();
const firebaseUser = '';
const usersRef = firebase.firestore().collection('users');
async handleFacebookButton() {
const { type, token, } = await Facebook.logInWithReadPermissionsAsync(FACEBOOK_APP_ID, {
permissions: ['public_profile', 'email']
});
if (type === 'success') {
//Firebase credential is created with the Facebook access token.
const credential = firebase.auth.FacebookAuthProvider.credential(token);
auth.signInAndRetrieveDataWithCredential(credential)
.then(function(userCredential) {
newUserCheck = userCredential.additionalUserInfo.isNewUser;
console.log('newUserCheck = ', newUserCheck)
});
this.setState({loggedIn: "You are signed in"})
this.setState({signedIn: true})
console.log('you are signed in');
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
firebaseUser = {name: user.displayName, uid: user.uid, email: user.email}
console.log(firebaseUser.name, ' and ', firebaseUser.uid);
var existingRef = usersRef.doc(firebaseUser.uid);
existingRef.get().then(function(documentSnapshot) {
// check if user is registered
if(documentSnapshot) {
data = documentSnapshot.data();
console.log('existing user exists!!');
// check if user is an administrator
if (data.administrator == true) {
console.log('existing administrator exists!!');
this.props.navigation.navigate('Admin');
} else { this.props.navigation.navigate('Main');
}
}
});
(error => {
console.log('user not accessed: ', error);
});
//User is not yet in firebase database and needs to be saved
// double check that user is a new user
if (newUserCheck == true) {
this.ref
.doc(uid)
.set({
id: firebaseUser.uid,
username: firebaseUser.name,
email: firebaseUser.email,
})
this.props.navigation.navigate('ChooseRoute')
}
}
})
}
// If login type is not success:
(error => {
this.setState({loggedIn: "Login failed: log in again"})
this.setState({ errorMessage: error.message });
});
}
I fixed it!! 3 days later - it was a binding issue - after several unsuccessful attempts to work out which were the right parts of the functions to bind I converted both 'auth().onAuthStateChanged' and 'documentSnapshot' into fat arrow functions and the errors are gone!! Thank goodness for ES6...! Hope this helps someone else down the line...

Angular 4 & Passport API authentication

I'm building a web app with the MEAN Stack. What I am trying to achieve is that when the user logs in his user information get fetched by Angular from my REST API. I set up the API route http://localhost:3000/api/user/profile which should respond with json including the user object.
router.get('/user/profile', function(req, res, next){
//console.log(req);
if(req.user === undefined){
res.json({
success: false,
msg: 'Unautorized'
});
} else {
res.json({
success: true,
user: {
id: req.user.steam.id,
name: req.user.steam.name,
avatar: req.user.steam.avatar,
avatarmedium: req.user.steam.avatarmedium,
avatarfull: req.user.steam.avatarfull
}
});
}
});
When the user logs in Angular start a GET-Request:
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
this.user = profile.user;
console.log(profile);
},
err => {
console.log(err);
return false;
});
}
getProfile():
getProfile(){
return this.http.get('http://localhost:3000/api/user/profile')
.map(res => res.json());
}
When I load up my site, log in, and go to the profile page the returned object contains success: false and the message 'Unauthorized' instead of the user object. Why is this happening?
I completely redesigned my approach. I implemented json web token which now sends a token (containing all user data) to the user through a url parameter once he signs in.

How to preserve user logged in using Parse JS and Facebook SDK

I'm using Parse Server + Parse JS Sdk to handle user login through Facebook. Everything works fine until I refresh web browser. What data should I store after login process is done? I belive that FB AccessToken is important to keep Facebook Session, but what about Parse Session.
Current code:
login: function (callback) {
console.log('loggin in...')
Parse.FacebookUtils.logIn('user_likes,email', {
success: function (parseUser) {
if (!parseUser.existed()) {
console.log('signed up and logged in!')
} else {
console.log('logged in!')
}
console.log('parse user is: ', parseUser.id)
if (callback) { callback() }
},
error: function (parseUser, error) {
console.log('login cancelled: ', error.message)
}
})
}
You don't need to manually store anything. You can use the parse function:
Parse.User.current()
To see if there is already a user logged-in.
We made this function:
function userAuthenticated(){
if(Parse.User.current() === null){
return false;
}
if(Parse.User.current().authenticated()){
return true;
}
else{
return false
}
}

authWithOAuthPopup Error on Web Platform

I am trying to use Firebase's Facebook authentication on a webpage, but I get this error:
Login failed Error: Invalid authentication credentials provided.
at Error (native)
at http://45.55.203.213/js/firebase.js:160:367
at e (http://45.55.203.213/js/firebase.js:140:400)
Here's my Javascript code:
var ref = new Firebase("https://fantasy-smash-bros.firebaseio.com/");
function FBLogin() {
ref.authWithOAuthPopup("facebook", function(error, authData) {
if (error) {
console.log("Login failed", error);
} else {
loginWithAuthData(authData);
}
});
}
function loginWithAuthData(authData) {
username = authData.facebook.displayName;
avatarURL = authData.facebook.cachedUserProfile.picture.data.url;
userID = authData.facebook.id;
}
function attemptLogin() {
var user = ref.getAuth();
if (user) {
loginWithAuthData(user);
} else {
$("#fb-login").click(function () {
FBLogin();
});
}
}
$(document).ready(function () {
attemptLogin();
});
Note: I have imported firebase.js. Here's a copy of the Javascript I used.
I believe I have setup everything correctly: adding Firebase's callback URL to my Facebook app's whitelist, enabling Facebook authentication on the Firebase app. But I am still stumped on what to do. Any help would be greatly appreciated.

Categories

Resources