change password not working amplify amazon - reactjs

i am trying to implement a simple password change after user gets invitation by email.
my code for changing password is from documentation:
https://docs.amplify.aws/lib/auth/manageusers/q/platform/js/
import { Auth } from 'aws-amplify';
Auth.currentAuthenticatedUser()
.then(user => {
return Auth.changePassword(user, 'oldPassword', 'newPassword');
})
.then(data => console.log(data))
.catch(err => console.log(err));
it is showing an error
NotAuthorizedException: Incorrect username or password.
which is not true, anyone had similar issue?,
I tried different solutions for this pasword change but seems I can get my head around it

Related

Firebase sendPasswordResetEmail in JS SDK, doesn't send confirmation code

I am trying to do the following:
User asks to reset his password
Email is sent with a CODE and an URL to visit to reset his password
User visits the URL inputs the code and the new password and I call the confirmPasswordReset
But this doesn't work, the docs, their examples and also their functionality differs. Here's what happens
Greeting,
Follow this link to reset the example#gmail.com account password for the Example Dev app.
the URL
No Code, nothing, if I follow the URL it will take me to Firebase hosted app that will handle the reset with an ugly looking UI and THEN redirect me to the specified URL in the settings for sendResetEmail...
While the docs specify expected behavior, it differs from the actual one.
Sends a password reset email to the given email address.
#remarks
To complete the password reset, call confirmPasswordReset with the code supplied in the email sent to the user, along with the new password specified by the user.
#example
const actionCodeSettings = {
url: 'https://www.example.com/?email=user#example.com',
iOS: {
bundleId: 'com.example.ios'
},
android: {
packageName: 'com.example.android',
installApp: true,
minimumVersion: '12'
},
handleCodeInApp: true
};
await sendPasswordResetEmail(auth, 'user#example.com', actionCodeSettings);
// Obtain code from user.
await confirmPasswordReset('user#example.com', code);
The docs specify my intended behavior, but when used, it's totally different. What is happening here?
const onSubmit = (data: PasswordResetData) => {
setIsLoading(true);
sendPasswordResetEmail(getAuth(), data.email, {
url: "http://localhost:3002/en/auth/reset/confirm?email=" + data.email,
handleCodeInApp: true,
})
.then(() => {
})
.catch((err) => {
console.error(err);
})
.finally(() => {
setIsLoading(false);
});
};

Login with Facebook in react native return "The App_id in the input_token did not match the Viewing App"

I come to you after hours of research.
I have created my facebook account with the application I am working on and also my firebase account that I have linked through the OAuth redirection URI to the configuration of your Facebook application.
But I always get the same mistake. Do you have any leads? Knowing that my APP_ID is the same in the code, on facebook developers and Firebase. And that I redirected the URI of firebase in facebook developpers.
Here is my code :
async function loginWithFacebook(){
await Facebook.initializeAsync({
appId : '1027709424451081'});
const {type,token} =
await Facebook.logInWithReadPermissionsAsync({
permissions:['public_profile'],
});
if (type === 'success') {
const credential = firebase.auth.FacebookAuthProvider.credential(token);
Firebase.auth().signInWithCredential(credential)
.then(user => { // All the details about user are in here returned from firebase
console.log('Logged in successfully', user)
})
.catch((error) => {
console.log('Error occurred ', error)
});
}
}
Thanks in advance for all suggestions.
When using the function "signInWithCredentials" you need to pass the auth also which you will get by
const auth = getAuth()
and then after getting the credentials
signInWithCredential(auth, credential)

Amplify and React : Code mismatch and fail enable Software Token MFA

I have a Cognito user pool that has MFA set to Optional with TOTP only.
I'm trying to set up a page that enables MultiFactorAuthentication for the user for the first time following this AWS Documentation.
As my component mounts, I generate a QR code and show it on screen using qrcode.react
useEffect(() => {
Auth.currentAuthenticatedUser({ bypassCache: true }).then(user => {
setUser(user);
Auth.setupTOTP(user).then(code => {
const authCode = "otpauth://totp/AWSCognito:" + user.username + "?secret=" + code + "&issuer=ivt";
setQrCode(authCode);
});
});
}, []);
Then, when the user puts the input, I verify it and call the setPrefferredMFA. Now here, I checked if "input" is correctly passed and no issues there.
const setupMFA = input => {
Auth.setupTOTP(user).then(() => {
Auth.verifyTotpToken(user, input)
.then(() => {
Auth.setPreferredMFA(user, "TOTP").then(() => {
props.setShowModal(false);
});
})
.catch(e => {
// Token is not verified
});
});
};
I'm still getting Code mismatch and fail enable Software Token MFA error and failing to set a MFA to the user.
I solved it.
Auth.verifyTotpToken() is not supposed to be in the .then() block of setupTOTP.
Pfft. Removing the Auth.setupTOTP in the setupMFA function made it work.

React login using context API with private route

In my react web app, login-logout functionality is implemented using context-API and hooks. Everything seems to work fine except for the fact that I have to click the 'Login' button twice to push the user to the dashboard.
The statement, return <Redirect to="/dashboard /> does not work, instead I have to use history.push('/dashboard'), which does not seems to be a better option to me while login.
Here is the working snippet :
https://codesandbox.io/s/wizardly-worker-mqkex?file=/src/AuthContext.js
Also, I need some suggestions for the best practise to fetch the logged user details in other components. Using localstorage or global context API state, which of them serves as the best option for the same ?
Any help to resolve this, appreciated :)
Well, it boils down to the simple fact that your context is not updated when you do your check. The simplest solution would be to remove the check for isLoggedIn and push the user to the Dashboard:
const postLogin = async (e) => {
e.preventDefault()
try {
await login()
props.history.push('/dashboard')
} catch (error) {
dispatch({
type: 'LOGIN_FAILURE',
payload: 'Unable to login'
})
}
}
Then throw an error in your login function when you don't get a 200 back:
const login = async () => {
const loginUser = { status: 200, id: '3654634565659abhdgh' }
if (loginUser.status === 200) {
dispatch({
type: 'LOGIN_SUCCESS',
payload: loginUser.id
})
} else {
throw new Error("Invalid Credentials")
}
}
As your login code is in a try catch block, the user won't get pushed to the Dashboard when the login fails.

Redirect 401 Error in React Redux Actions File

So I'm trying to redirect the user if the server responds with a 401 Unauthorized response based on the user authentication backend I've established. Currently I'm sending a request to the server to check if the user matches with the item I'm checking against. IF they don't match, a 401 Unauthorized response is returned. But I cannot properly redirect them in my .catch(err) statement in my actions file.
I've tried several different solutions, stackoverflow searches, google searches, tutorials, and still cannot get the results I want. I've also tried installing different packages to no avail.
Here is my actions file. The .catch(err) is where I'd like to redirect the user to if a 401 error comes back.
// Get Single Score
export const getScore = (id, history) => dispatch => {
dispatch(setScoreLoading());
axios
.get(`score/${id}`)
.then(res =>
dispatch({
type: GET_SCORE,
payload: res.data
})
)
.catch(err =>
dispatch({
type: SCORE_NOT_FOUND,
payload: err.response.data
})
history.push('/not-authorized')
);
}
Any help is greatly appreciated.
i think the problem is your arrow function . you use => directly that will return your dispatch but never touch your history.push
.catch(err => {dispatch({
type: SCORE_NOT_FOUND,
payload: err.response.data
})
return history.push('/not-authorized')
)}
Hope this help.
Btw use history.replace is better in this case in my opinion

Resources