Supabase reset password for email - reactjs

Im try to reset password user for supabase in react but it says resetPasswordForEmail is undefined```
const { data, error } = await supabase.auth.api.resetPasswordForEmail(email)
if (data) {
console.log(data)
}
if (error) {
console.log(error)
}
}
I try to run the code but it gives and error because of an undefined function I expected to send an email

You're probably on v2, it should be:
supabase.auth.resetPasswordForEmail
Not:
supabase.auth.api.resetPasswordForEmail
For reference: https://supabase.com/docs/reference/javascript/auth-resetpasswordforemail
Check this out as well, it has some important notes you may need to know:
https://github.com/supabase/supabase/discussions/3360#discussioncomment-3947228

Related

react hook form - after first error cannot validate again

Good Day!
Today i am faced with a problem regarding react hook form.
I am setting a custom error using setError in case there is an error when loggin in.
The problem:
After the first error, I cannot validate the form again.
ex)
login fail with either wrong id or password => received error message from the backened.
error is set using setError
re-write the form and trying to submit again => cannot send login api to the backened.
Anyone had similar issues like myself?
const onValid = async (data) => {
const res = await SignIn(data);
if (res.data.result) {
const result = setSessionKey(res.data.loginInfo.sessionKey);
console.log(result);
clearErrors();
} else {
return setError('loginFail', { message: 'login failed' });
}
};

React native firebase phone authentication, if code sent navigate to otp screen

I am using react native firebase, if code sent then i want to navigate to otp screen
But it shows an warning :
Non-serializable values were found in the navigation state. Check:
OtpVerification > params.confirm._auth._app._deleteApp (Function)
This can break usage such as persisting and restoring state. This might happen if you passed non-serializable values such as function, class instances etc. in params. If you need to use components with callbacks in your options, you can use 'navigation.setOptions'
My code :
In login Screen :
async function signInWithPhoneNumber(phoneNumber) {
try {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
props.navigation.navigate('OtpVerification', {
confirm: confirmation,
phoneNo,
});
} catch (error) {
console.log(error);
}
}
In Otp Screen :
async function confirmCode() {
if (otp) {
try {
await confirm.confirm(otp);
props.navigation.navigate('OnBoarding');
} catch (error) {
AlertMsg('Invalid OTP');
}
} else {
AlertMsg('Please Enter OTP');
}
}
So I believe in belive function where you have confirmation variable, You might have to pass some constant value over there handling the return of firebase signin.
async function signInWithPhoneNumber(phoneNumber) {
try {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
props.navigation.navigate('OtpVerification', {
confirm: confirmation,
phoneNo,
});
} catch (error) {
console.log(error);
}
Check this document - https://reactnavigation.org/docs/troubleshooting/#i-get-the-warning-non-serializable-values-were-found-in-the-navigation-state
This expo for your navigation - https://snack.expo.dev/vKpugczaG

React Authentication - network error when verifying if user is logged in, via token in local storage

TL;DR: On production, our React app is throwing a network error when trying to verify whether a user is logged in, via a token from localstorage...
We're using Sentry for error tracking / reporting, and Sentry has now flagged a few times an error that we have been unable to recreate on our end:
and when we view the error in Sentry, we get some additional information, including a key breadcrumb pointing to our tokenIsValid post request:
Our react app calls tokenIsValid one-time in our top-level App.js file, and this request checks to see if a user was previously logged in (via a token saved in localstorage). Here's the useEffect from our App.js:
Edit: with error reporting added
router.post("/tokenIsValid", async (req, res) => {
try {
const token = req.header("x-auth-token");
if (!token) return res.json(false);
const verified = jwt.verify(token, process.env.JWT_SECRET);
if (!verified) return res.json(false);
const user = await User.findById(verified.id);
if (!user) return res.json(false);
return res.json(true);
} catch (err) {
// update: ive added Sentry error handling here
res.status(500).json({ error: err.message });
}
});
We followed this tutorial for react authentication with hooks. Everything seemed to work okay when we tested it, but now Sentry is alerting us of some errors as users try to sign up & log into our website.
Edit: Even though I've tagged this as a React + React Authentication problem, Network Error leads me to think the issue is related to our Node API simply not staying up, and users not being able to hit this endpoint in the Node API. This post hints at that... our Node API is deployed in a docker container using GCP's Cloud Run.
Also, maybe it's a cors issue, per this (last answer by Tiago), and I should add app.use(cors({origin: true, credentials: true})); when I call cors().
You may be facing issues due to the values returned and how you consume the returned value. With the below-refactored code, you can just check the authenticated key in the returned object, use the message key for human-readable status message, and use the error key for detailed error in the event of a 500 error.
// An authentication middleware, abstacted from the code within route controller
const authMiddlware = (req, res, next) => {
try {
// Get token from header
const token = req.header("x-auth-token");
if (!token) {
return res.status(401).json({
message: 'Token required'
});
}
// validate token
const { id } = jwt.verify(token, process.env.JWT_SECRET);
if (id) {
req.verified = {
id
};
return next();
} else {
return res.state(401).json({
message: 'Invalid token'
});
}
} catch (err) {
res.status(500).json({
error: err,
message: err.message
});
}
};
// Apply the auth middleware
router.post("/tokenIsValid", authMiddlware, async (req, res) => {
try {
const user = await User.findById(req.verified.id);
if (user) {
return res.status(200).json({
authenticated: true,
message: 'Authenticated successfully'
});
} else {
return res.state(401).json({
message: 'Invalid user'
});
}
} catch (err) {
res.status(500).json({
error: err,
message: err.message
});
}
});

How to fix this function to handle different error type of error catching

I have developing mern stack web site. In that I have added below codes to handle logging.
onSubmit(e) {
e.preventDefault();
const obj = {
user_name: this.state.user_name,
password: this.state.password
};
axios.post('http://localhost:4000/login', obj)
.then(res=> localStorage.setItem('token',(res.data.token))
//localstorage.setItem('username','res.data.user.username)
)
}
When I click on login button this onSubmit() function called and will save token in local storage.
But, res.data have more details. (from backend it passes logged users information too)
So I want to add those to local storage. I tried that as commented in above function. It says error in res. Note : I user react for frontend.
Also I want to handle handle errors in any cases axios.post() didn't work as planned. In server side it send different messages for unmatched credentials and wrong passwords. How can I show those in my page. Thank you.
Since the only accepted data type in localStorage is string, you should stringify it first using JSON API.
const userDataStr = JSON.stringify(res.data);
localStorage.setItem('userData', userDataStr);
Now if you want to access the userData from localStorage you just need to convert it back to javascript object.
const userDataStr = localStorage.getItem('userData', userData);
const userData = JSON.parse(userDataStr);
You can have multiple catch in the returned promise of axios.post
axios.post()
.catch((error) => { })
.catch((error) => { })
But those catch will called with the same error so you need to handle it differently in each catch
Another suggestion:
If you want to easily handle the error, you can use higher order function like this
const handleError = (status, callback) => (error) => {
if (status === error) {
callback(error);
}
}
axios.post()
.catch(handleError(404, (error) => { /* only called when status === 404 */ }))
.catch(handleError(500, (error) => { /* only called when status === 500 */ }))

Redux Post Request failed with status code 404

I am trying to do a request to my local host on my network in a redux app with axios.
here is the request code :
export function createAccount(userInfo){
return async (dispatch) => {
try {
const resp = await axios.post(`${BASE_URL}/signup`, userInfo);
localStorage.setItem('token', resp.data.token);
dispatch({ type: types.SIGN_UP });
} catch(err) {
console.log('Sign Up Error:', err.message);
}
}
}
And here is what error is displayed :
Sign Up Error: Request failed with status code 404
Another possible cause may be mismatch between the names of the sent parameters and the expected on the REDUX end (actions). Better provide the code for the reducers and the action index. In my case I got 404 on POST request and when I checked the Headers (under Network) I figured out that the Request Payload is empty. The reason was the following:
const data = {
linkIdCampaign,
linkIdMix
}
this.props.onAddLink(data);
on the front end part did not correspond to the:
return axios.post("http://localhost:5000/YOUR_URL", { newLink, newMix})
.then(response => {
in the actions index.

Resources