I am using react-native-fbsdk and tried to get data of user while user is logging in my app using facebook.
I am able to get name,first_name,last_name,email and picture but I also want profile link of user profile of facebook.
I have permssion of user_link.
Can someone explain where I am going or what I need to get the profile url.
LoginManager.logInWithPermissions(['email', 'public_profile', 'user_link'])
.then(
login => {
AccessToken.getCurrentAccessToken().then(data => {
const accessToken = data.accessToken.toString();accessToken);
this.getInfoFromToken(accessToken);
});
})
getInfoFromToken = token => {
const PROFILE_REQUEST_PARAMS = {
fields: {
string: 'id,name,first_name,last_name,email,picture',
},
};
const profileRequest = new GraphRequest(
'/me',
{ token, parameters: PROFILE_REQUEST_PARAMS },
(error, user) => {
if (error) {
//this.setState({ userInfo: error }, () => this.getData())
console.log('login info has error: ' + error);
} else {
this.setState({ userInfo: user }, () =>
console.log('result:', user);
}
},
);
new GraphRequestManager().addRequest(profileRequest).start();
};
Related
this is the route:
router.post(
'/',
[ auth,
check('status', 'Status is required').not().isEmpty(),
check('skills', 'Skills is required').not().isEmpty(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// destructure the request
const {
website,
skills,
youtube,
twitter,
instagram,
linkedin,
facebook,
// spread the rest of the fields we don't need to check
...rest
} = req.body;
// build a profile
const profileFields = {
user: req.user.id,
website:
website && website !== ''
? normalize(website, { forceHttps: true })
: '',
skills: Array.isArray(skills)
? skills
: skills.split(',').map((skill) => ' ' + skill.trim()),
...rest
};
// Build socialFields object
const socialFields = { youtube, twitter, instagram, linkedin, facebook };
// normalize social fields to ensure valid url
for (const [key, value] of Object.entries(socialFields)) {
if (value && value.length > 0)
socialFields[key] = normalize(value, { forceHttps: true });
}
// add to profileFields
profileFields.social = socialFields;
try {
// Using upsert option (creates new doc if no match is found):
let profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true, upsert: true, setDefaultsOnInsert: true }
);
return res.json(profile);
} catch (err) {
console.error(err.message);
return res.status(500).send('Server Error');
}
}
);
this is Axios:
axios.post('/api/profile',profileData, {headers:{
'x-auth-token': localStorage.getItem('jwtToken')
}}).then(data => console.log(data)).catch(e => console.error(e))
this is problem:
pending
Have you tried to use debugger in order to follow software flow?
Have you any log from express side?
I'd start checking if let profile = await Profile.findOneAndUpdate is reached in order to define if the problem starts on db request.
At this stage I would say that the execution is pending waiting for db timeout
I'm trying to use MSAL and React to login to MSGraph. I get the popup to authenticate when I call userAgentApplication.loginPopup({propt: "select_account", scopes: config.scopes})
After entering my login information, it appears that I authenticated but when I try to make a request the login popup continues to display as if I didn't authenticate already. I get no errors on the console.
I refresh the page and check localStorage and see msal.error = invalid_state_error
I'm using MSAL version v1.4.6
Here is my code
ContextualMenu.js
import { msgraph } from './actions/graphAction';
const graph = useSelector((state) => state.graph);
const userAgentApplication = new UserAgentApplication({
auth: {
clientId: config.appId,
redirectUri: config.redirectUri
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: true
}
});
const getUserProfile = async () => {
try {
let accessToken = await userAgentApplication.acquireTokenSilent({
scopes: config.scopes
});
if (accessToken) {
let user = await getUserDetails(accessToken);
let uu = {
displayName: user.displayName,
email: user.mail || user.userPrincipalName,
givenName: user.givenName,
surname: user.surname
}
dispatch(msgraph(true, uu, null));
}
} catch (err) {
console.log(err);
}
};
const msLogin = async () => {
try {
await userAgentApplication.loginPopup({
prompt: "select_account"
});
getUserProfile();
}
catch (err) {
console.log('failed', err);
}
};
const emailFiles = () => {
setRootClassName('close');
if (graph.isAuthenticated) {
checkSelectedFile();
return false;
}
msLogin();
}
After loginPopup is called it never gets to getUserProfile and doesn't error either.
Please any help is appreciated
I'm trying to create sign up form in react-native using Firebase.I've used Fetch Blob and Document Picker libraries for getting image and upload it to firebase. And I'm also trying to save the user's name, email, and password in realtime database. But unfortunately, the user data is not going to save in database except the image is uploaded in the firebase storage.
Here is my Firebase Auth Code
handleSignupOnPress = () => {
const {image, email, password} = this.state;
let validation = this.validateData();
console.warn(validation);
if (validation == true) {
this.toggleLoading();
firebaseService
.auth()
.createUserWithEmailAndPassword(email, password)
.then(() => {
// console.warn("User SignUp Successfully");
this.uploadImage(image);
})
.catch(error => {
this.toggleLoading();
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
// console.warn("ERROR => ", errorCode, errorMessage);
});
}
};
Here is image Upload Code
// First Uploading image and download Image URI then call saveUserToDB()...
uploadImage(uri, mime = 'image/jpeg') {
return new Promise((resolve, reject) => {
const uploadUri =
Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
let uploadBlob = '';
const imageRef = firebaseService
.storage()
.ref('images')
.child(uuid.v4());
fs.readFile(uploadUri, 'base64')
.then(data => {
return Blob.build(data, {type: `${mime};BASE64`});
})
.then(blob => {
uploadBlob = blob;
return imageRef.put(blob, {contentType: mime});
})
.then(() => {
uploadBlob.close();
const downnloadImageURI = imageRef.getDownloadURL().then(url => {
this.setState(
{
imageURI: url,
},
() => {
alert('ImageURI ==> ', this.state.imageURI);
this.saveUserInfo();
},
);
});
return downnloadImageURI;
})
.then(url => {
resolve(url);
})
.catch(error => {
this.toggleLoading();
reject(error);
});
});
}
Here is code for saving user's data
saveUserInfo = () => {
const {userName, email, password, imageURI} = this.state;
const {navigate} = this.props.navigation;
const uid = firebaseService.auth().currentUser.uid;
const params = {
image: imageURI,
username: userName,
email: email,
password: password,
};
//firebaseService.database().ref('/Users').push(params)
firebaseService
.database()
.ref('/Users')
.child(uid)
.set(params)
.then(res => {
this.toggleLoading();
navigate('Login');
})
.catch(err => {
alert(err);
});
};
Here are screenshots of Firebase Console
Are the "Rules" in database given permission to "Write"
Go to the firebase console and open your project.
Go to the database and search for "Rules" tab.
Check the rules are set as below
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
".read": true,
".write": true
}
}
I've solved this issue. The issue was in this piece of code.
const downnloadImageURI = imageRef.getDownloadURL().then(url => {
this.setState(
{
imageURI: url,
},
() => {
alert('ImageURI ==> ', this.state.imageURI);
this.saveUserInfo();
},
);
setState was not working and calback was not fired.
And I've made it like this way
const downnloadImageURI = imageRef.getDownloadURL().then(url => {
this.saveUserInfo(url)
);}
This my first time in React and Axios. I have a login form and sign up form and don't have any database. I want any mock API to simulate a login and sign up which provides a token in the response, in order to save it in a local storage in order to keep the user logged in. Also how do I prevent the user to go the home page (login/logout screen). When they type for example www.blabla.com, I want, if the token exists they still in the app, otherwise the token will be erased.
I tried to fetch data from mock API by axios.get(), it worked but it still static
componentDidMount() { // this For Testing Until Now
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => {
console.log(res);
this.setState({
users: res.data
}, () => {
console.log('state', this.state.users)
})
});
}
I want to communicate with API that allows my to fetch data and post data to it. This is my login function
handleLogin(e) {
e.preventDefault();
const email = e.target.elements.email.value;
const password = e.target.elements.password.value;
let userData = {};
if(validator.isEmpty(email) || validator.isEmpty(password) || !validator.isEmail(email)) {
this.setState({
error: 'You Have To Complete Your Data Correctly'
}, () => {
console.log('failed');
});
} else {
userData = {email, password};
const { users } = this.state;
if(users.find(item => item.email === userData.email)) {
const index = users.findIndex(item => item.email === userData.email);
this.props.history.push(`./create/${users[index].username}`);
}
}
}
and this is my signup function
handleAddNewUser(e) {
e.preventDefault();
const name = e.target.elements.userName.value.toLowerCase().trim();
const email = e.target.elements.userEmail.value.toLowerCase().trim();
const password = e.target.elements.pass.value;
const repassword = e.target.elements.re_pass.value;
let userInfo = {};
const { users } = this.state;
console.log(name, email);
if (validator.isEmpty(name) || validator.isEmpty(email) ||
validator.isEmpty(password) || validator.isEmpty(repassword) ||
!validator.isEmail(email) || !validator.equals(password, repassword)) {
this.setState({
error: 'You Have to enter valid data, Make Sure That The Fields are Complete',
open: true
});
} else {
userInfo = { name, email, password };
if (
users.find(item => item.name === userInfo.name) ||
users.find(item => item.email === userInfo.email)
) {
this.setState({
error: 'This username or email is used',
open: true
});
} else {
this.setState({
users: this.state.users.concat(userInfo),
success: true
}, () => {
// this.props.history.push(`./create/${userInfo.name}`);
// console.log(users)
});
console.log(users)
}
}
}
You can use axios.post() to send post request.
// POST
const userData = {
email: 'demouser#gmail.com',
username: 'demouser',
password: '1a2b3c4d5e' //This should be encoded
}
axios.post('https://example.com/createUser', userData)
.then(res => {
responseData = res.data
if (responseData.status == 'success') {
const user = responseData.user
...
} else {
alert('Something went wrong while creating account')
}
})
I'm using AWS Cognito Javascript SDK in a react application. I have a user that was created in the AWS Console by an admin, and when the user is logged in for the first time they have to reset their password. I go through the newPasswordRequired flow, and when I call the completeNewPasswordChallenge function with the parameters, the onFailure callback is ran. When I log the error I get, {code: "UnknownError", message: "Unknown error"}. However, when I check the AWS Console, the user in the user pool is changed from FORCE_CHANGE_PASSWORD to CONFIRMED.
My code is:
class LoginScreenContainer extends Component {
constructor(props) {
super(props);
this.state = {
isInvalidForm: null,
isFirstLogin: false,
user: null,
userAttr: null
}
this.onFormSubmission = this.onFormSubmission.bind(this);
this.updatePassword = this.updatePassword.bind(this);
}
onFormSubmission = (username, password) => {
const poolData = {
UserPoolId : AWSConfig.cognito.USER_POOL_ID,
ClientId : AWSConfig.cognito.APP_CLIENT_ID
}
const userPool = new CognitoUserPool(poolData);
const userData = {
Username: username,
Pool: userPool
}
const cognitoUser = new CognitoUser(userData);
const authenticationData = {
Username : username,
Password : password
}
const authenticationDetails = new AuthenticationDetails(authenticationData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
console.log(result);
},
onFailure: (err) => {
console.log("Authenticate user failure");
console.log(err);
this.setState({ isInvalidForm: true });
},
newPasswordRequired: (userAttributes) => {
delete userAttributes.email_verified;
delete userAttributes.phone_number_verified;
userAttributes.name = authenticationDetails.username;
console.log(userAttributes);
this.setState({
isFirstLogin: true,
user: cognitoUser,
userAttr: userAttributes
});
}
});
}
updatePassword = (newPassword) => {
const cognitoUser = this.state.user;
const userAttr = this.state.userAttr;
cognitoUser.completeNewPasswordChallenge(newPassword, userAttr, {
onSuccess: (result) => {
console.log("NEW PASSWORD COMPLETED: ");
console.log(result);
},
onFailure: (err) => {
console.log(err);
}
});
}
render() {
return (
<div>
{this.state.isFirstLogin ? (
<NewPasswordForm updatePassword={this.updatePassword} />
) : (
<LoginScreenComponent isInvalidForm={this.state.isInvalidForm} onFormSubmission={this.onFormSubmission}/>
)}
</div>
);
}
}
I believe you need to call completeNewPasswordChallenge within the newPasswordRequired callback.
newPasswordRequired: (userAttributes, requiredAttributes) => {
delete userAttributes.email_verified
cognitoUser.completeNewPasswordChallenge(newPw, userAttributes, {
onSuccess: result => {
AWS.config.credentials.refresh(err => {
if (err) {
throw err
} else {
// do something
}
})
},
newPasswordRequired: (userAttributes, requiredAttributes) => {
delete userAttributes.email_verified
// phone number as well
cognitoUser.completeNewPasswordChallenge(newPw, userAttributes, this.newPasswordRequired)
},
onFailure: err => {
throw err
}
})
},
I believe you have MFA on your account and you need to handle it from callback:
mfaSetup: (challengeName, challengeParameters) => { ... }
When you're handling mfaSetup form cognitoUser.authenticateUser() callback all is good if it's required, but from completeNewPasswordChallenge() callback there is no mfaSetup() in typings, which I believe AWS colleagues should fix it ASAP.
That's why you have empty error code, please check response tab in network dev tools on post req you made. I believe you'll find there MFA_SETUP challenge to solve.